diff --git a/src/components/BootstrapBlazor.EmbedPDF/BootstrapBlazor.EmbedPDF.csproj b/src/components/BootstrapBlazor.EmbedPDF/BootstrapBlazor.EmbedPDF.csproj index efd6200a..2b700f12 100644 --- a/src/components/BootstrapBlazor.EmbedPDF/BootstrapBlazor.EmbedPDF.csproj +++ b/src/components/BootstrapBlazor.EmbedPDF/BootstrapBlazor.EmbedPDF.csproj @@ -1,7 +1,7 @@  - 10.0.2 + 10.0.3 diff --git a/src/components/BootstrapBlazor.EmbedPDF/wwwroot/browser-BISJ9naB-D71PyCCt.js b/src/components/BootstrapBlazor.EmbedPDF/wwwroot/browser-BISJ9naB-D71PyCCt.js new file mode 100644 index 00000000..e623f6cd --- /dev/null +++ b/src/components/BootstrapBlazor.EmbedPDF/wwwroot/browser-BISJ9naB-D71PyCCt.js @@ -0,0 +1 @@ +import{N as e,T as t,K as r,P as n,L as o}from"./embedpdf-xgzA9lZs.js";const i="TaskQueue",a="Queue";var u=(e=>(e[e.CRITICAL=3]="CRITICAL",e[e.HIGH=2]="HIGH",e[e.MEDIUM=1]="MEDIUM",e[e.LOW=0]="LOW",e))(u||{});class s{constructor(t={}){this.queue=[],this.running=0,this.resultTasks=new Map,this.idleListeners=new Set;const{concurrency:r=1,comparator:n,ranker:o,onIdle:i,maxQueueSize:a,autoStart:u=!0,logger:s}=t;this.logger=s??new e,this.opts={concurrency:Math.max(1,r),comparator:n,ranker:o,onIdle:i??(()=>{}),maxQueueSize:a??Number.POSITIVE_INFINITY,autoStart:u}}setComparator(e){this.opts.comparator=e}setRanker(e){this.opts.ranker=e}size(){return this.queue.length}inFlight(){return this.running}isIdle(){return 0===this.queue.length&&0===this.running}async drain(){this.isIdle()||await new Promise(e=>{const t=()=>{this.isIdle()&&(this.offIdle(t),e())};this.onIdle(t)})}notifyIdle(){this.isIdle()&&([...this.idleListeners].forEach(e=>e()),this.idleListeners.clear(),this.opts.onIdle())}onIdle(e){this.idleListeners.add(e)}offIdle(e){this.idleListeners.delete(e)}enqueue(e,r={}){const n=this.generateId(),o=r.priority??1,u=new t;if(this.queue.length>=this.opts.maxQueueSize){const e=new Error("Queue is full (maxQueueSize reached).");return u.reject(e),u}this.resultTasks.set(n,u);const s={id:n,priority:o,meta:r.meta??e.meta,executeFactory:e.execute};this.queue.push(s),this.logger.debug(i,a,`Task enqueued: ${n} | Priority: ${o} | Running: ${this.running} | Queued: ${this.queue.length}`);const c=u.abort.bind(u);return u.abort=e=>{this.logger.debug(i,a,`Task aborted: ${n}`),this.cancel(n),c(e)},this.opts.autoStart&&this.process(!0===r.fifo),u}cancel(e){const t=this.queue.length;this.queue=this.queue.filter(t=>t.id!==e||(t.cancelled=!0,!1)),this.resultTasks.delete(e),t!==this.queue.length&&(this.logger.debug(i,a,`Task cancelled and removed: ${e}`),this.kick())}kick(){queueMicrotask(()=>this.process())}async process(e=!1){for(this.logger.debug(i,a,`process() called | Running: ${this.running} | Concurrency: ${this.opts.concurrency} | Queued: ${this.queue.length}`);this.running0;){this.logger.debug(i,a,`Starting new task | Running: ${this.running} | Queued: ${this.queue.length}`),e||this.sortQueue();const t=this.queue.shift();if(t.cancelled){this.logger.debug(i,a,`Skipping cancelled task: ${t.id}`);continue}const r=this.resultTasks.get(t.id);r&&(this.running++,(async()=>{let e=null;try{if(e=t.executeFactory(),!e)throw new Error("Task factory returned null/undefined");e.wait(e=>{0===r.state.stage&&r.resolve(e)},e=>{0===r.state.stage&&("abort"===e.type?r.abort(e.reason):r.reject(e.reason))}),e.onProgress(e=>{r.progress(e)}),await e.toPromise()}catch(e){0===r.state.stage&&r.reject(e)}finally{this.resultTasks.delete(t.id),this.running--,this.logger.debug(i,a,`Task completed: ${t.id} | Running: ${this.running} | Queued: ${this.queue.length}`),this.isIdle()?this.notifyIdle():this.queue.length>0&&this.kick()}})().catch(e=>{this.logger.error(i,a,"Unhandled error in task execution wrapper:",e),this.running=Math.max(0,this.running-1),this.isIdle()?this.notifyIdle():this.queue.length>0&&this.kick()}))}}sortQueue(){const{comparator:e,ranker:t}=this.opts;if(e)return void this.queue.sort(e);const r=new Map,n=e=>t?(r.has(e.id)||r.set(e.id,t(e)),r.get(e.id)):this.defaultRank(e);this.queue.sort((e,t)=>{if(e.priority!==t.priority)return t.priority-e.priority;const r=n(e),o=n(t);return r!==o?o-r:this.extractTime(e.id)-this.extractTime(t.id)})}defaultRank(e){return 0}generateId(){return"undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}extractTime(e){const t=Number(e.split("-")[0]);return Number.isFinite(t)?t:0}}const c="PdfEngine",d="Orchestrator";class h{constructor(t,r){this.executor=t,this.logger=r.logger??new e,this.options={imageConverter:r.imageConverter,fetcher:r.fetcher??("undefined"!=typeof fetch?(e,t)=>fetch(e,t):void 0),logger:this.logger},this.workerQueue=new s({concurrency:1,autoStart:!0,logger:this.logger}),this.logger.debug(c,d,"PdfEngine orchestrator created")}chunkArray(e,t){const r=[];for(let n=0;n{try{if(!this.options.fetcher)throw new Error("Fetcher is not set");const t=await this.options.fetcher(e.url,null==r?void 0:r.requestOptions),n=await t.arrayBuffer(),i={id:e.id,content:n};this.openDocumentBuffer(i,{password:null==r?void 0:r.password,normalizeRotation:null==r?void 0:r.normalizeRotation}).wait(e=>o.resolve(e),e=>o.fail(e))}catch(e){o.reject({code:n.Unknown,message:String(e)})}})(),o}openDocumentBuffer(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.openDocumentBuffer(e,t),meta:{docId:e.id,operation:"openDocumentBuffer"}},{priority:u.CRITICAL})}getMetadata(e){return this.workerQueue.enqueue({execute:()=>this.executor.getMetadata(e),meta:{docId:e.id,operation:"getMetadata"}},{priority:u.MEDIUM})}setMetadata(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.setMetadata(e,t),meta:{docId:e.id,operation:"setMetadata"}},{priority:u.MEDIUM})}getDocPermissions(e){return this.workerQueue.enqueue({execute:()=>this.executor.getDocPermissions(e),meta:{docId:e.id,operation:"getDocPermissions"}},{priority:u.MEDIUM})}getDocUserPermissions(e){return this.workerQueue.enqueue({execute:()=>this.executor.getDocUserPermissions(e),meta:{docId:e.id,operation:"getDocUserPermissions"}},{priority:u.MEDIUM})}getSignatures(e){return this.workerQueue.enqueue({execute:()=>this.executor.getSignatures(e),meta:{docId:e.id,operation:"getSignatures"}},{priority:u.MEDIUM})}getBookmarks(e){return this.workerQueue.enqueue({execute:()=>this.executor.getBookmarks(e),meta:{docId:e.id,operation:"getBookmarks"}},{priority:u.MEDIUM})}setBookmarks(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.setBookmarks(e,t),meta:{docId:e.id,operation:"setBookmarks"}},{priority:u.MEDIUM})}deleteBookmarks(e){return this.workerQueue.enqueue({execute:()=>this.executor.deleteBookmarks(e),meta:{docId:e.id,operation:"deleteBookmarks"}},{priority:u.MEDIUM})}renderPage(e,t,r){return this.renderWithEncoding(()=>this.executor.renderPageRaw(e,t,r),r,e.id,t.index,u.CRITICAL)}renderPageRect(e,t,r,n){return this.renderWithEncoding(()=>this.executor.renderPageRect(e,t,r,n),n,e.id,t.index,u.HIGH)}renderPageRaw(e,t,r){return this.workerQueue.enqueue({execute:()=>this.executor.renderPageRaw(e,t,r),meta:{docId:e.id,pageIndex:t.index,operation:"renderPageRaw"}},{priority:u.HIGH})}renderPageRectRaw(e,t,r,n){return this.workerQueue.enqueue({execute:()=>this.executor.renderPageRect(e,t,r,n),meta:{docId:e.id,pageIndex:t.index,operation:"renderPageRectRaw"}},{priority:u.HIGH})}renderThumbnail(e,t,r){return this.renderWithEncoding(()=>this.executor.renderThumbnailRaw(e,t,r),r,e.id,t.index,u.MEDIUM)}renderPageAnnotation(e,t,r,n){return this.renderWithEncoding(()=>this.executor.renderPageAnnotationRaw(e,t,r,n),n,e.id,t.index,u.MEDIUM)}renderPageAnnotations(e,r,n){const o=new t,i=this.workerQueue.enqueue({execute:()=>this.executor.renderPageAnnotationsRaw(e,r,n),meta:{docId:e.id,pageIndex:r.index,operation:"renderPageAnnotationsRaw"}},{priority:u.MEDIUM}),a=o.abort.bind(o);return o.abort=e=>{i.abort(e),a(e)},i.wait(e=>{0===o.state.stage&&this.encodeAppearanceMap(e,n,o)},e=>{0===o.state.stage&&o.fail(e)}),o}renderPageAnnotationsRaw(e,t,r){return this.workerQueue.enqueue({execute:()=>this.executor.renderPageAnnotationsRaw(e,t,r),meta:{docId:e.id,pageIndex:t.index,operation:"renderPageAnnotationsRaw"}},{priority:u.MEDIUM})}renderWithEncoding(e,r,n,o,i=u.CRITICAL){const a=new t,s=this.workerQueue.enqueue({execute:()=>e(),meta:{docId:n,pageIndex:o,operation:"render"}},{priority:i}),c=a.abort.bind(a);return a.abort=e=>{s.abort(e),c(e)},s.wait(e=>{0===a.state.stage&&this.encodeImage(e,r,a)},e=>{0===a.state.stage&&a.fail(e)}),a}encodeImage(e,t,r){const o=(null==t?void 0:t.imageType)??"image/webp",i=null==t?void 0:t.quality,a={data:new Uint8ClampedArray(e.data),width:e.width,height:e.height};this.options.imageConverter(()=>a,o,i).then(e=>r.resolve(e)).catch(e=>r.reject({code:n.Unknown,message:String(e)}))}encodeAppearanceMap(e,t,r){const o=(null==t?void 0:t.imageType)??"image/webp",i=null==t?void 0:t.imageQuality,a=e=>{const t={data:new Uint8ClampedArray(e.data),width:e.width,height:e.height};return this.options.imageConverter(()=>t,o,i)},u=[],s={},c=["normal","rollover","down"];for(const[t,r]of Object.entries(e)){const e={};s[t]=e;for(const t of c){const n=r[t];n&&u.push(a(n.data).then(r=>{e[t]={data:r,rect:n.rect}}))}}Promise.all(u).then(()=>{0===r.state.stage&&r.resolve(s)}).catch(e=>{0===r.state.stage&&r.reject({code:n.Unknown,message:String(e)})})}getPageAnnotations(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.getPageAnnotations(e,t),meta:{docId:e.id,pageIndex:t.index,operation:"getPageAnnotations"}},{priority:u.MEDIUM})}createPageAnnotation(e,t,r,n){return this.workerQueue.enqueue({execute:()=>this.executor.createPageAnnotation(e,t,r,n),meta:{docId:e.id,pageIndex:t.index,operation:"createPageAnnotation"}},{priority:u.MEDIUM})}updatePageAnnotation(e,t,r,n){return this.workerQueue.enqueue({execute:()=>this.executor.updatePageAnnotation(e,t,r,n),meta:{docId:e.id,pageIndex:t.index,operation:"updatePageAnnotation"}},{priority:u.MEDIUM})}removePageAnnotation(e,t,r){return this.workerQueue.enqueue({execute:()=>this.executor.removePageAnnotation(e,t,r),meta:{docId:e.id,pageIndex:t.index,operation:"removePageAnnotation"}},{priority:u.MEDIUM})}getAllAnnotations(e){const t=this.chunkArray(e.pages,500);this.logger.debug(c,d,`getAllAnnotations: ${e.pages.length} pages in ${t.length} chunks`);const r=new o({aggregate:e=>Object.assign({},...e)});return t.forEach((t,n)=>{const o=this.workerQueue.enqueue({execute:()=>this.executor.getAnnotationsBatch(e,t),meta:{docId:e.id,operation:"getAnnotationsBatch",chunkSize:t.length}},{priority:u.LOW});o.onProgress(e=>{r.progress({page:e.pageIndex,result:e.result})}),r.addChild(o,n)}),r.finalize(),r}getPageTextRects(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.getPageTextRects(e,t),meta:{docId:e.id,pageIndex:t.index,operation:"getPageTextRects"}},{priority:u.MEDIUM})}searchAllPages(e,t,r){const n=Array.isArray(null==r?void 0:r.flags)?r.flags.reduce((e,t)=>e|t,0):(null==r?void 0:r.flags)??0,i=this.chunkArray(e.pages,25);this.logger.debug(c,d,`searchAllPages: ${e.pages.length} pages in ${i.length} chunks`);const a=new o({aggregate:e=>{const t=e.flatMap(e=>Object.values(e).flat());return{results:t,total:t.length}}});return i.forEach((r,o)=>{const i=this.workerQueue.enqueue({execute:()=>this.executor.searchBatch(e,r,t,n),meta:{docId:e.id,operation:"searchBatch",chunkSize:r.length}},{priority:u.LOW});i.onProgress(e=>{a.progress({page:e.pageIndex,results:e.result})}),a.addChild(i,o)}),a.finalize(),a}getAttachments(e){return this.workerQueue.enqueue({execute:()=>this.executor.getAttachments(e),meta:{docId:e.id,operation:"getAttachments"}},{priority:u.MEDIUM})}addAttachment(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.addAttachment(e,t),meta:{docId:e.id,operation:"addAttachment"}},{priority:u.MEDIUM})}removeAttachment(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.removeAttachment(e,t),meta:{docId:e.id,operation:"removeAttachment"}},{priority:u.MEDIUM})}readAttachmentContent(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.readAttachmentContent(e,t),meta:{docId:e.id,operation:"readAttachmentContent"}},{priority:u.MEDIUM})}setFormFieldValue(e,t,r,n){return this.workerQueue.enqueue({execute:()=>this.executor.setFormFieldValue(e,t,r,n),meta:{docId:e.id,pageIndex:t.index,operation:"setFormFieldValue"}},{priority:u.MEDIUM})}flattenPage(e,t,r){return this.workerQueue.enqueue({execute:()=>this.executor.flattenPage(e,t,r),meta:{docId:e.id,pageIndex:t.index,operation:"flattenPage"}},{priority:u.MEDIUM})}extractPages(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.extractPages(e,t),meta:{docId:e.id,pageIndexes:t,operation:"extractPages"}},{priority:u.MEDIUM})}extractText(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.extractText(e,t),meta:{docId:e.id,pageIndexes:t,operation:"extractText"}},{priority:u.MEDIUM})}redactTextInRects(e,t,r,n){return this.workerQueue.enqueue({execute:()=>this.executor.redactTextInRects(e,t,r,n),meta:{docId:e.id,pageIndex:t.index,operation:"redactTextInRects"}},{priority:u.MEDIUM})}applyRedaction(e,t,r){return this.workerQueue.enqueue({execute:()=>this.executor.applyRedaction(e,t,r),meta:{docId:e.id,pageIndex:t.index,operation:"applyRedaction"}},{priority:u.MEDIUM})}applyAllRedactions(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.applyAllRedactions(e,t),meta:{docId:e.id,pageIndex:t.index,operation:"applyAllRedactions"}},{priority:u.MEDIUM})}flattenAnnotation(e,t,r){return this.workerQueue.enqueue({execute:()=>this.executor.flattenAnnotation(e,t,r),meta:{docId:e.id,pageIndex:t.index,operation:"flattenAnnotation"}},{priority:u.MEDIUM})}getTextSlices(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.getTextSlices(e,t),meta:{docId:e.id,slices:t,operation:"getTextSlices"}},{priority:u.MEDIUM})}getPageGlyphs(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.getPageGlyphs(e,t),meta:{docId:e.id,pageIndex:t.index,operation:"getPageGlyphs"}},{priority:u.MEDIUM})}getPageGeometry(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.getPageGeometry(e,t),meta:{docId:e.id,pageIndex:t.index,operation:"getPageGeometry"}},{priority:u.MEDIUM})}getPageTextRuns(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.getPageTextRuns(e,t),meta:{docId:e.id,pageIndex:t.index,operation:"getPageTextRuns"}},{priority:u.MEDIUM})}merge(e){return this.workerQueue.enqueue({execute:()=>this.executor.merge(e),meta:{docId:e.map(e=>e.id).join(","),operation:"merge"}},{priority:u.MEDIUM})}mergePages(e){return this.workerQueue.enqueue({execute:()=>this.executor.mergePages(e),meta:{docId:e.map(e=>e.docId).join(","),operation:"mergePages"}},{priority:u.MEDIUM})}preparePrintDocument(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.preparePrintDocument(e,t),meta:{docId:e.id,operation:"preparePrintDocument"}},{priority:u.MEDIUM})}saveAsCopy(e){return this.workerQueue.enqueue({execute:()=>this.executor.saveAsCopy(e),meta:{docId:e.id,operation:"saveAsCopy"}},{priority:u.MEDIUM})}closeDocument(e){return this.workerQueue.enqueue({execute:()=>this.executor.closeDocument(e),meta:{docId:e.id,operation:"closeDocument"}},{priority:u.MEDIUM})}closeAllDocuments(){return this.workerQueue.enqueue({execute:()=>this.executor.closeAllDocuments(),meta:{operation:"closeAllDocuments"}},{priority:u.MEDIUM})}setDocumentEncryption(e,t,r,n){return this.workerQueue.enqueue({execute:()=>this.executor.setDocumentEncryption(e,t,r,n),meta:{docId:e.id,operation:"setDocumentEncryption"}},{priority:u.MEDIUM})}removeEncryption(e){return this.workerQueue.enqueue({execute:()=>this.executor.removeEncryption(e),meta:{docId:e.id,operation:"removeEncryption"}},{priority:u.MEDIUM})}unlockOwnerPermissions(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.unlockOwnerPermissions(e,t),meta:{docId:e.id,operation:"unlockOwnerPermissions"}},{priority:u.MEDIUM})}isEncrypted(e){return this.workerQueue.enqueue({execute:()=>this.executor.isEncrypted(e),meta:{docId:e.id,operation:"isEncrypted"}},{priority:u.MEDIUM})}isOwnerUnlocked(e){return this.workerQueue.enqueue({execute:()=>this.executor.isOwnerUnlocked(e),meta:{docId:e.id,operation:"isOwnerUnlocked"}},{priority:u.MEDIUM})}}class g extends Error{constructor(e){super(e),this.name="ImageConverterError"}}const p=(e,t="image/webp",r)=>{if("undefined"==typeof document)return Promise.reject(new g("document is not available. This converter requires a browser environment."));const n=e(),o=new ImageData(n.data,n.width,n.height);return new Promise((e,n)=>{const i=document.createElement("canvas");i.width=o.width,i.height=o.height,i.getContext("2d").putImageData(o,0,0),i.toBlob(t=>{t?e(t):n(new g("Canvas toBlob returned null"))},t,r)})};function l(e){const t=async(t,r="image/webp",n)=>{try{const o=t(),i=new Uint8ClampedArray(o.data);return await e.encode({data:i,width:o.width,height:o.height},r,n)}catch(e){return console.warn("Worker encoding failed, falling back to main-thread Canvas:",e),p(t,r,n)}};return t.destroy=()=>e.destroy(),t}export{h as P,p as b,l as c}; diff --git a/src/components/BootstrapBlazor.EmbedPDF/wwwroot/browser-BISJ9naB-DfsGA31F.js b/src/components/BootstrapBlazor.EmbedPDF/wwwroot/browser-BISJ9naB-DfsGA31F.js deleted file mode 100644 index c083a2e5..00000000 --- a/src/components/BootstrapBlazor.EmbedPDF/wwwroot/browser-BISJ9naB-DfsGA31F.js +++ /dev/null @@ -1 +0,0 @@ -import{N as e,T as t,H as r,P as n,I as i}from"./embedpdf-DX_zb2Zx.js";const o="TaskQueue",u="Queue";var s=(e=>(e[e.CRITICAL=3]="CRITICAL",e[e.HIGH=2]="HIGH",e[e.MEDIUM=1]="MEDIUM",e[e.LOW=0]="LOW",e))(s||{});class a{constructor(t={}){this.queue=[],this.running=0,this.resultTasks=new Map,this.idleListeners=new Set;const{concurrency:r=1,comparator:n,ranker:i,onIdle:o,maxQueueSize:u,autoStart:s=!0,logger:a}=t;this.logger=a??new e,this.opts={concurrency:Math.max(1,r),comparator:n,ranker:i,onIdle:o??(()=>{}),maxQueueSize:u??Number.POSITIVE_INFINITY,autoStart:s}}setComparator(e){this.opts.comparator=e}setRanker(e){this.opts.ranker=e}size(){return this.queue.length}inFlight(){return this.running}isIdle(){return 0===this.queue.length&&0===this.running}async drain(){this.isIdle()||await new Promise(e=>{const t=()=>{this.isIdle()&&(this.offIdle(t),e())};this.onIdle(t)})}notifyIdle(){this.isIdle()&&([...this.idleListeners].forEach(e=>e()),this.idleListeners.clear(),this.opts.onIdle())}onIdle(e){this.idleListeners.add(e)}offIdle(e){this.idleListeners.delete(e)}enqueue(e,r={}){const n=this.generateId(),i=r.priority??1,s=new t;if(this.queue.length>=this.opts.maxQueueSize){const e=new Error("Queue is full (maxQueueSize reached).");return s.reject(e),s}this.resultTasks.set(n,s);const a={id:n,priority:i,meta:r.meta??e.meta,executeFactory:e.execute};this.queue.push(a),this.logger.debug(o,u,`Task enqueued: ${n} | Priority: ${i} | Running: ${this.running} | Queued: ${this.queue.length}`);const c=s.abort.bind(s);return s.abort=e=>{this.logger.debug(o,u,`Task aborted: ${n}`),this.cancel(n),c(e)},this.opts.autoStart&&this.process(!0===r.fifo),s}cancel(e){const t=this.queue.length;this.queue=this.queue.filter(t=>t.id!==e||(t.cancelled=!0,!1)),this.resultTasks.delete(e),t!==this.queue.length&&(this.logger.debug(o,u,`Task cancelled and removed: ${e}`),this.kick())}kick(){queueMicrotask(()=>this.process())}async process(e=!1){for(this.logger.debug(o,u,`process() called | Running: ${this.running} | Concurrency: ${this.opts.concurrency} | Queued: ${this.queue.length}`);this.running0;){this.logger.debug(o,u,`Starting new task | Running: ${this.running} | Queued: ${this.queue.length}`),e||this.sortQueue();const t=this.queue.shift();if(t.cancelled){this.logger.debug(o,u,`Skipping cancelled task: ${t.id}`);continue}const r=this.resultTasks.get(t.id);r&&(this.running++,(async()=>{let e=null;try{if(e=t.executeFactory(),!e)throw new Error("Task factory returned null/undefined");e.wait(e=>{0===r.state.stage&&r.resolve(e)},e=>{0===r.state.stage&&("abort"===e.type?r.abort(e.reason):r.reject(e.reason))}),e.onProgress(e=>{r.progress(e)}),await e.toPromise()}catch(e){0===r.state.stage&&r.reject(e)}finally{this.resultTasks.delete(t.id),this.running--,this.logger.debug(o,u,`Task completed: ${t.id} | Running: ${this.running} | Queued: ${this.queue.length}`),this.isIdle()?this.notifyIdle():this.queue.length>0&&this.kick()}})().catch(e=>{this.logger.error(o,u,"Unhandled error in task execution wrapper:",e),this.running=Math.max(0,this.running-1),this.isIdle()?this.notifyIdle():this.queue.length>0&&this.kick()}))}}sortQueue(){const{comparator:e,ranker:t}=this.opts;if(e)return void this.queue.sort(e);const r=new Map,n=e=>t?(r.has(e.id)||r.set(e.id,t(e)),r.get(e.id)):this.defaultRank(e);this.queue.sort((e,t)=>{if(e.priority!==t.priority)return t.priority-e.priority;const r=n(e),i=n(t);return r!==i?i-r:this.extractTime(e.id)-this.extractTime(t.id)})}defaultRank(e){return 0}generateId(){return"undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}extractTime(e){const t=Number(e.split("-")[0]);return Number.isFinite(t)?t:0}}const c="PdfEngine",d="Orchestrator";class h{constructor(t,r){this.executor=t,this.logger=r.logger??new e,this.options={imageConverter:r.imageConverter,fetcher:r.fetcher??("undefined"!=typeof fetch?(e,t)=>fetch(e,t):void 0),logger:this.logger},this.workerQueue=new a({concurrency:1,autoStart:!0,logger:this.logger}),this.logger.debug(c,d,"PdfEngine orchestrator created")}chunkArray(e,t){const r=[];for(let n=0;n{try{if(!this.options.fetcher)throw new Error("Fetcher is not set");const t=await this.options.fetcher(e.url,null==r?void 0:r.requestOptions),n=await t.arrayBuffer(),o={id:e.id,content:n};this.openDocumentBuffer(o,{password:null==r?void 0:r.password,normalizeRotation:null==r?void 0:r.normalizeRotation}).wait(e=>i.resolve(e),e=>i.fail(e))}catch(e){i.reject({code:n.Unknown,message:String(e)})}})(),i}openDocumentBuffer(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.openDocumentBuffer(e,t),meta:{docId:e.id,operation:"openDocumentBuffer"}},{priority:s.CRITICAL})}getMetadata(e){return this.workerQueue.enqueue({execute:()=>this.executor.getMetadata(e),meta:{docId:e.id,operation:"getMetadata"}},{priority:s.MEDIUM})}setMetadata(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.setMetadata(e,t),meta:{docId:e.id,operation:"setMetadata"}},{priority:s.MEDIUM})}getDocPermissions(e){return this.workerQueue.enqueue({execute:()=>this.executor.getDocPermissions(e),meta:{docId:e.id,operation:"getDocPermissions"}},{priority:s.MEDIUM})}getDocUserPermissions(e){return this.workerQueue.enqueue({execute:()=>this.executor.getDocUserPermissions(e),meta:{docId:e.id,operation:"getDocUserPermissions"}},{priority:s.MEDIUM})}getSignatures(e){return this.workerQueue.enqueue({execute:()=>this.executor.getSignatures(e),meta:{docId:e.id,operation:"getSignatures"}},{priority:s.MEDIUM})}getBookmarks(e){return this.workerQueue.enqueue({execute:()=>this.executor.getBookmarks(e),meta:{docId:e.id,operation:"getBookmarks"}},{priority:s.MEDIUM})}setBookmarks(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.setBookmarks(e,t),meta:{docId:e.id,operation:"setBookmarks"}},{priority:s.MEDIUM})}deleteBookmarks(e){return this.workerQueue.enqueue({execute:()=>this.executor.deleteBookmarks(e),meta:{docId:e.id,operation:"deleteBookmarks"}},{priority:s.MEDIUM})}renderPage(e,t,r){return this.renderWithEncoding(()=>this.executor.renderPageRaw(e,t,r),r,e.id,t.index,s.CRITICAL)}renderPageRect(e,t,r,n){return this.renderWithEncoding(()=>this.executor.renderPageRect(e,t,r,n),n,e.id,t.index,s.HIGH)}renderPageRaw(e,t,r){return this.workerQueue.enqueue({execute:()=>this.executor.renderPageRaw(e,t,r),meta:{docId:e.id,pageIndex:t.index,operation:"renderPageRaw"}},{priority:s.HIGH})}renderPageRectRaw(e,t,r,n){return this.workerQueue.enqueue({execute:()=>this.executor.renderPageRect(e,t,r,n),meta:{docId:e.id,pageIndex:t.index,operation:"renderPageRectRaw"}},{priority:s.HIGH})}renderThumbnail(e,t,r){return this.renderWithEncoding(()=>this.executor.renderThumbnailRaw(e,t,r),r,e.id,t.index,s.MEDIUM)}renderPageAnnotation(e,t,r,n){return this.renderWithEncoding(()=>this.executor.renderPageAnnotationRaw(e,t,r,n),n,e.id,t.index,s.MEDIUM)}renderWithEncoding(e,r,n,i,o=s.CRITICAL){const u=new t,a=this.workerQueue.enqueue({execute:()=>e(),meta:{docId:n,pageIndex:i,operation:"render"}},{priority:o}),c=u.abort.bind(u);return u.abort=e=>{a.abort(e),c(e)},a.wait(e=>{0===u.state.stage&&this.encodeImage(e,r,u)},e=>{0===u.state.stage&&u.fail(e)}),u}encodeImage(e,t,r){const i=(null==t?void 0:t.imageType)??"image/webp",o=null==t?void 0:t.quality,u={data:new Uint8ClampedArray(e.data),width:e.width,height:e.height};this.options.imageConverter(()=>u,i,o).then(e=>r.resolve(e)).catch(e=>r.reject({code:n.Unknown,message:String(e)}))}getPageAnnotations(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.getPageAnnotations(e,t),meta:{docId:e.id,pageIndex:t.index,operation:"getPageAnnotations"}},{priority:s.MEDIUM})}createPageAnnotation(e,t,r,n){return this.workerQueue.enqueue({execute:()=>this.executor.createPageAnnotation(e,t,r,n),meta:{docId:e.id,pageIndex:t.index,operation:"createPageAnnotation"}},{priority:s.MEDIUM})}updatePageAnnotation(e,t,r){return this.workerQueue.enqueue({execute:()=>this.executor.updatePageAnnotation(e,t,r),meta:{docId:e.id,pageIndex:t.index,operation:"updatePageAnnotation"}},{priority:s.MEDIUM})}removePageAnnotation(e,t,r){return this.workerQueue.enqueue({execute:()=>this.executor.removePageAnnotation(e,t,r),meta:{docId:e.id,pageIndex:t.index,operation:"removePageAnnotation"}},{priority:s.MEDIUM})}getAllAnnotations(e){const t=this.chunkArray(e.pages,500);this.logger.debug(c,d,`getAllAnnotations: ${e.pages.length} pages in ${t.length} chunks`);const r=new i({aggregate:e=>Object.assign({},...e)});return t.forEach((t,n)=>{const i=this.workerQueue.enqueue({execute:()=>this.executor.getAnnotationsBatch(e,t),meta:{docId:e.id,operation:"getAnnotationsBatch",chunkSize:t.length}},{priority:s.LOW});i.onProgress(e=>{r.progress({page:e.pageIndex,result:e.result})}),r.addChild(i,n)}),r.finalize(),r}getPageTextRects(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.getPageTextRects(e,t),meta:{docId:e.id,pageIndex:t.index,operation:"getPageTextRects"}},{priority:s.MEDIUM})}searchAllPages(e,t,r){const n=Array.isArray(null==r?void 0:r.flags)?r.flags.reduce((e,t)=>e|t,0):(null==r?void 0:r.flags)??0,o=this.chunkArray(e.pages,25);this.logger.debug(c,d,`searchAllPages: ${e.pages.length} pages in ${o.length} chunks`);const u=new i({aggregate:e=>{const t=e.flatMap(e=>Object.values(e).flat());return{results:t,total:t.length}}});return o.forEach((r,i)=>{const o=this.workerQueue.enqueue({execute:()=>this.executor.searchBatch(e,r,t,n),meta:{docId:e.id,operation:"searchBatch",chunkSize:r.length}},{priority:s.LOW});o.onProgress(e=>{u.progress({page:e.pageIndex,results:e.result})}),u.addChild(o,i)}),u.finalize(),u}getAttachments(e){return this.workerQueue.enqueue({execute:()=>this.executor.getAttachments(e),meta:{docId:e.id,operation:"getAttachments"}},{priority:s.MEDIUM})}addAttachment(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.addAttachment(e,t),meta:{docId:e.id,operation:"addAttachment"}},{priority:s.MEDIUM})}removeAttachment(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.removeAttachment(e,t),meta:{docId:e.id,operation:"removeAttachment"}},{priority:s.MEDIUM})}readAttachmentContent(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.readAttachmentContent(e,t),meta:{docId:e.id,operation:"readAttachmentContent"}},{priority:s.MEDIUM})}setFormFieldValue(e,t,r,n){return this.workerQueue.enqueue({execute:()=>this.executor.setFormFieldValue(e,t,r,n),meta:{docId:e.id,pageIndex:t.index,operation:"setFormFieldValue"}},{priority:s.MEDIUM})}flattenPage(e,t,r){return this.workerQueue.enqueue({execute:()=>this.executor.flattenPage(e,t,r),meta:{docId:e.id,pageIndex:t.index,operation:"flattenPage"}},{priority:s.MEDIUM})}extractPages(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.extractPages(e,t),meta:{docId:e.id,pageIndexes:t,operation:"extractPages"}},{priority:s.MEDIUM})}extractText(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.extractText(e,t),meta:{docId:e.id,pageIndexes:t,operation:"extractText"}},{priority:s.MEDIUM})}redactTextInRects(e,t,r,n){return this.workerQueue.enqueue({execute:()=>this.executor.redactTextInRects(e,t,r,n),meta:{docId:e.id,pageIndex:t.index,operation:"redactTextInRects"}},{priority:s.MEDIUM})}applyRedaction(e,t,r){return this.workerQueue.enqueue({execute:()=>this.executor.applyRedaction(e,t,r),meta:{docId:e.id,pageIndex:t.index,operation:"applyRedaction"}},{priority:s.MEDIUM})}applyAllRedactions(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.applyAllRedactions(e,t),meta:{docId:e.id,pageIndex:t.index,operation:"applyAllRedactions"}},{priority:s.MEDIUM})}flattenAnnotation(e,t,r){return this.workerQueue.enqueue({execute:()=>this.executor.flattenAnnotation(e,t,r),meta:{docId:e.id,pageIndex:t.index,operation:"flattenAnnotation"}},{priority:s.MEDIUM})}getTextSlices(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.getTextSlices(e,t),meta:{docId:e.id,slices:t,operation:"getTextSlices"}},{priority:s.MEDIUM})}getPageGlyphs(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.getPageGlyphs(e,t),meta:{docId:e.id,pageIndex:t.index,operation:"getPageGlyphs"}},{priority:s.MEDIUM})}getPageGeometry(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.getPageGeometry(e,t),meta:{docId:e.id,pageIndex:t.index,operation:"getPageGeometry"}},{priority:s.MEDIUM})}getPageTextRuns(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.getPageTextRuns(e,t),meta:{docId:e.id,pageIndex:t.index,operation:"getPageTextRuns"}},{priority:s.MEDIUM})}merge(e){return this.workerQueue.enqueue({execute:()=>this.executor.merge(e),meta:{docId:e.map(e=>e.id).join(","),operation:"merge"}},{priority:s.MEDIUM})}mergePages(e){return this.workerQueue.enqueue({execute:()=>this.executor.mergePages(e),meta:{docId:e.map(e=>e.docId).join(","),operation:"mergePages"}},{priority:s.MEDIUM})}preparePrintDocument(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.preparePrintDocument(e,t),meta:{docId:e.id,operation:"preparePrintDocument"}},{priority:s.MEDIUM})}saveAsCopy(e){return this.workerQueue.enqueue({execute:()=>this.executor.saveAsCopy(e),meta:{docId:e.id,operation:"saveAsCopy"}},{priority:s.MEDIUM})}closeDocument(e){return this.workerQueue.enqueue({execute:()=>this.executor.closeDocument(e),meta:{docId:e.id,operation:"closeDocument"}},{priority:s.MEDIUM})}closeAllDocuments(){return this.workerQueue.enqueue({execute:()=>this.executor.closeAllDocuments(),meta:{operation:"closeAllDocuments"}},{priority:s.MEDIUM})}setDocumentEncryption(e,t,r,n){return this.workerQueue.enqueue({execute:()=>this.executor.setDocumentEncryption(e,t,r,n),meta:{docId:e.id,operation:"setDocumentEncryption"}},{priority:s.MEDIUM})}removeEncryption(e){return this.workerQueue.enqueue({execute:()=>this.executor.removeEncryption(e),meta:{docId:e.id,operation:"removeEncryption"}},{priority:s.MEDIUM})}unlockOwnerPermissions(e,t){return this.workerQueue.enqueue({execute:()=>this.executor.unlockOwnerPermissions(e,t),meta:{docId:e.id,operation:"unlockOwnerPermissions"}},{priority:s.MEDIUM})}isEncrypted(e){return this.workerQueue.enqueue({execute:()=>this.executor.isEncrypted(e),meta:{docId:e.id,operation:"isEncrypted"}},{priority:s.MEDIUM})}isOwnerUnlocked(e){return this.workerQueue.enqueue({execute:()=>this.executor.isOwnerUnlocked(e),meta:{docId:e.id,operation:"isOwnerUnlocked"}},{priority:s.MEDIUM})}}class g extends Error{constructor(e){super(e),this.name="ImageConverterError"}}const p=(e,t="image/webp",r)=>{if("undefined"==typeof document)return Promise.reject(new g("document is not available. This converter requires a browser environment."));const n=e(),i=new ImageData(n.data,n.width,n.height);return new Promise((e,n)=>{const o=document.createElement("canvas");o.width=i.width,o.height=i.height,o.getContext("2d").putImageData(i,0,0),o.toBlob(t=>{t?e(t):n(new g("Canvas toBlob returned null"))},t,r)})};function l(e){const t=async(t,r="image/webp",n)=>{try{const i=t(),o=new Uint8ClampedArray(i.data);return await e.encode({data:o,width:i.width,height:i.height},r,n)}catch(e){return console.warn("Worker encoding failed, falling back to main-thread Canvas:",e),p(t,r,n)}};return t.destroy=()=>e.destroy(),t}export{h as P,p as b,l as c}; diff --git a/src/components/BootstrapBlazor.EmbedPDF/wwwroot/direct-engine-BKalS8iM.js b/src/components/BootstrapBlazor.EmbedPDF/wwwroot/direct-engine-BKalS8iM.js deleted file mode 100644 index cf85e457..00000000 --- a/src/components/BootstrapBlazor.EmbedPDF/wwwroot/direct-engine-BKalS8iM.js +++ /dev/null @@ -1 +0,0 @@ -import{N as e,a as t,P as n,p as r,i as o,u as a,b as i,c as s,d as u,e as m,f as F,g as l,h as d,j as P,k as _,l as c,m as g,w as h,n as D,o as b,q as p,r as f,t as A,v as E,x as y,y as M,z as G,A as S,R as C,B as x,C as T,D as v,T as O,E as R,F as k,G as w}from"./embedpdf-DX_zb2Zx.js";import{P as I,b as B}from"./browser-BISJ9naB-DfsGA31F.js";var j,L=(j=import.meta.url,async function(e={}){var t,n,r,o=e,a=new Promise((e,t)=>{n=e,r=t});["_EPDF_GetMetaKeyCount","_EPDF_GetMetaKeyName","_EPDF_GetMetaTrapped","_EPDF_GetPageRotationByIndex","_EPDF_GetPageSizeByIndexNormalized","_EPDF_HasMetaText","_EPDF_IsEncrypted","_EPDF_IsOwnerUnlocked","_EPDF_LoadPageNormalized","_EPDF_PNG_EncodeRGBA","_EPDF_RemoveEncryption","_EPDF_RenderAnnotBitmap","_EPDF_RenderAnnotBitmapUnrotated","_EPDF_SetEncryption","_EPDF_SetMetaText","_EPDF_SetMetaTrapped","_EPDF_UnlockOwnerPermissions","_EPDFAction_CreateGoTo","_EPDFAction_CreateGoToNamed","_EPDFAction_CreateLaunch","_EPDFAction_CreateRemoteGoToByName","_EPDFAction_CreateRemoteGoToDest","_EPDFAction_CreateURI","_EPDFAnnot_ApplyRedaction","_EPDFAnnot_ClearColor","_EPDFAnnot_Flatten","_EPDFAnnot_GenerateAppearance","_EPDFAnnot_GenerateAppearanceWithBlend","_EPDFAnnot_GetAPMatrix","_EPDFAnnot_GetAvailableAppearanceModes","_EPDFAnnot_GetBlendMode","_EPDFAnnot_GetBorderDashPattern","_EPDFAnnot_GetBorderDashPatternCount","_EPDFAnnot_GetBorderEffect","_EPDFAnnot_GetBorderStyle","_EPDFAnnot_GetColor","_EPDFAnnot_GetDefaultAppearance","_EPDFAnnot_GetExtendedRotation","_EPDFAnnot_GetIcon","_EPDFAnnot_GetIntent","_EPDFAnnot_GetLineEndings","_EPDFAnnot_GetOpacity","_EPDFAnnot_GetOverlayText","_EPDFAnnot_GetOverlayTextRepeat","_EPDFAnnot_GetRect","_EPDFAnnot_GetRectangleDifferences","_EPDFAnnot_GetReplyType","_EPDFAnnot_GetRichContent","_EPDFAnnot_GetRotate","_EPDFAnnot_GetTextAlignment","_EPDFAnnot_GetUnrotatedRect","_EPDFAnnot_GetVerticalAlignment","_EPDFAnnot_SetAction","_EPDFAnnot_SetAPMatrix","_EPDFAnnot_SetBorderDashPattern","_EPDFAnnot_SetBorderStyle","_EPDFAnnot_SetColor","_EPDFAnnot_SetDefaultAppearance","_EPDFAnnot_SetExtendedRotation","_EPDFAnnot_SetIcon","_EPDFAnnot_SetIntent","_EPDFAnnot_SetLine","_EPDFAnnot_SetLineEndings","_EPDFAnnot_SetLinkedAnnot","_EPDFAnnot_SetOpacity","_EPDFAnnot_SetOverlayText","_EPDFAnnot_SetOverlayTextRepeat","_EPDFAnnot_SetReplyType","_EPDFAnnot_SetRotate","_EPDFAnnot_SetTextAlignment","_EPDFAnnot_SetUnrotatedRect","_EPDFAnnot_SetVerticalAlignment","_EPDFAnnot_SetVertices","_EPDFAnnot_UpdateAppearanceToRect","_EPDFAttachment_GetDescription","_EPDFAttachment_GetIntegerValue","_EPDFAttachment_SetDescription","_EPDFAttachment_SetSubtype","_EPDFBookmark_AppendChild","_EPDFBookmark_Clear","_EPDFBookmark_ClearTarget","_EPDFBookmark_Create","_EPDFBookmark_Delete","_EPDFBookmark_InsertAfter","_EPDFBookmark_SetAction","_EPDFBookmark_SetDest","_EPDFBookmark_SetTitle","_EPDFCatalog_GetLanguage","_EPDFDest_CreateRemoteView","_EPDFDest_CreateRemoteXYZ","_EPDFDest_CreateView","_EPDFDest_CreateXYZ","_EPDFNamedDest_Remove","_EPDFNamedDest_SetDest","_EPDFPage_ApplyRedactions","_EPDFPage_CreateAnnot","_EPDFPage_GetAnnotByName","_EPDFPage_GetAnnotCountRaw","_EPDFPage_GetAnnotRaw","_EPDFPage_RemoveAnnotByName","_EPDFPage_RemoveAnnotRaw","_EPDFText_RedactInQuads","_EPDFText_RedactInRect","_FORM_CanRedo","_FORM_CanUndo","_FORM_DoDocumentAAction","_FORM_DoDocumentJSAction","_FORM_DoDocumentOpenAction","_FORM_DoPageAAction","_FORM_ForceToKillFocus","_FORM_GetFocusedAnnot","_FORM_GetFocusedText","_FORM_GetSelectedText","_FORM_IsIndexSelected","_FORM_OnAfterLoadPage","_FORM_OnBeforeClosePage","_FORM_OnChar","_FORM_OnFocus","_FORM_OnKeyDown","_FORM_OnKeyUp","_FORM_OnLButtonDoubleClick","_FORM_OnLButtonDown","_FORM_OnLButtonUp","_FORM_OnMouseMove","_FORM_OnMouseWheel","_FORM_OnRButtonDown","_FORM_OnRButtonUp","_FORM_Redo","_FORM_ReplaceAndKeepSelection","_FORM_ReplaceSelection","_FORM_SelectAllText","_FORM_SetFocusedAnnot","_FORM_SetIndexSelected","_FORM_Undo","_FPDF_AddInstalledFont","_FPDF_CloseDocument","_FPDF_ClosePage","_FPDF_CloseXObject","_FPDF_CopyViewerPreferences","_FPDF_CountNamedDests","_FPDF_CreateClipPath","_FPDF_CreateNewDocument","_FPDF_DestroyClipPath","_FPDF_DestroyLibrary","_FPDF_DeviceToPage","_FPDF_DocumentHasValidCrossReferenceTable","_FPDF_FFLDraw","_FPDF_FreeDefaultSystemFontInfo","_FPDF_GetDefaultSystemFontInfo","_FPDF_GetDefaultTTFMap","_FPDF_GetDefaultTTFMapCount","_FPDF_GetDefaultTTFMapEntry","_FPDF_GetDocPermissions","_FPDF_GetDocUserPermissions","_FPDF_GetFileIdentifier","_FPDF_GetFileVersion","_FPDF_GetFormType","_FPDF_GetLastError","_FPDF_GetMetaText","_FPDF_GetNamedDest","_FPDF_GetNamedDestByName","_FPDF_GetPageAAction","_FPDF_GetPageBoundingBox","_FPDF_GetPageCount","_FPDF_GetPageHeight","_FPDF_GetPageHeightF","_FPDF_GetPageLabel","_FPDF_GetPageSizeByIndex","_FPDF_GetPageSizeByIndexF","_FPDF_GetPageWidth","_FPDF_GetPageWidthF","_FPDF_GetSecurityHandlerRevision","_FPDF_GetSignatureCount","_FPDF_GetSignatureObject","_FPDF_GetTrailerEnds","_FPDF_GetXFAPacketContent","_FPDF_GetXFAPacketCount","_FPDF_GetXFAPacketName","_FPDF_ImportNPagesToOne","_FPDF_ImportPages","_FPDF_ImportPagesByIndex","_FPDF_InitLibrary","_FPDF_InitLibraryWithConfig","_FPDF_LoadCustomDocument","_FPDF_LoadDocument","_FPDF_LoadMemDocument","_FPDF_LoadMemDocument64","_FPDF_LoadPage","_FPDF_LoadXFA","_FPDF_MovePages","_FPDF_NewFormObjectFromXObject","_FPDF_NewXObjectFromPage","_FPDF_PageToDevice","_FPDF_RemoveFormFieldHighlight","_FPDF_RenderPage_Close","_FPDF_RenderPage_Continue","_FPDF_RenderPageBitmap","_FPDF_RenderPageBitmap_Start","_FPDF_RenderPageBitmapWithColorScheme_Start","_FPDF_RenderPageBitmapWithMatrix","_FPDF_SaveAsCopy","_FPDF_SaveWithVersion","_FPDF_SetFormFieldHighlightAlpha","_FPDF_SetFormFieldHighlightColor","_FPDF_SetSandBoxPolicy","_FPDF_SetSystemFontInfo","_FPDF_StructElement_Attr_CountChildren","_FPDF_StructElement_Attr_GetBlobValue","_FPDF_StructElement_Attr_GetBooleanValue","_FPDF_StructElement_Attr_GetChildAtIndex","_FPDF_StructElement_Attr_GetCount","_FPDF_StructElement_Attr_GetName","_FPDF_StructElement_Attr_GetNumberValue","_FPDF_StructElement_Attr_GetStringValue","_FPDF_StructElement_Attr_GetType","_FPDF_StructElement_Attr_GetValue","_FPDF_StructElement_CountChildren","_FPDF_StructElement_GetActualText","_FPDF_StructElement_GetAltText","_FPDF_StructElement_GetAttributeAtIndex","_FPDF_StructElement_GetAttributeCount","_FPDF_StructElement_GetChildAtIndex","_FPDF_StructElement_GetChildMarkedContentID","_FPDF_StructElement_GetID","_FPDF_StructElement_GetLang","_FPDF_StructElement_GetMarkedContentID","_FPDF_StructElement_GetMarkedContentIdAtIndex","_FPDF_StructElement_GetMarkedContentIdCount","_FPDF_StructElement_GetObjType","_FPDF_StructElement_GetParent","_FPDF_StructElement_GetStringAttribute","_FPDF_StructElement_GetTitle","_FPDF_StructElement_GetType","_FPDF_StructTree_Close","_FPDF_StructTree_CountChildren","_FPDF_StructTree_GetChildAtIndex","_FPDF_StructTree_GetForPage","_FPDF_VIEWERREF_GetDuplex","_FPDF_VIEWERREF_GetName","_FPDF_VIEWERREF_GetNumCopies","_FPDF_VIEWERREF_GetPrintPageRange","_FPDF_VIEWERREF_GetPrintPageRangeCount","_FPDF_VIEWERREF_GetPrintPageRangeElement","_FPDF_VIEWERREF_GetPrintScaling","_FPDFAction_GetDest","_FPDFAction_GetFilePath","_FPDFAction_GetType","_FPDFAction_GetURIPath","_FPDFAnnot_AddFileAttachment","_FPDFAnnot_AddInkStroke","_FPDFAnnot_AppendAttachmentPoints","_FPDFAnnot_AppendObject","_FPDFAnnot_CountAttachmentPoints","_FPDFAnnot_GetAP","_FPDFAnnot_GetAttachmentPoints","_FPDFAnnot_GetBorder","_FPDFAnnot_GetColor","_FPDFAnnot_GetFileAttachment","_FPDFAnnot_GetFlags","_FPDFAnnot_GetFocusableSubtypes","_FPDFAnnot_GetFocusableSubtypesCount","_FPDFAnnot_GetFontColor","_FPDFAnnot_GetFontSize","_FPDFAnnot_GetFormAdditionalActionJavaScript","_FPDFAnnot_GetFormControlCount","_FPDFAnnot_GetFormControlIndex","_FPDFAnnot_GetFormFieldAlternateName","_FPDFAnnot_GetFormFieldAtPoint","_FPDFAnnot_GetFormFieldExportValue","_FPDFAnnot_GetFormFieldFlags","_FPDFAnnot_GetFormFieldName","_FPDFAnnot_GetFormFieldType","_FPDFAnnot_GetFormFieldValue","_FPDFAnnot_GetInkListCount","_FPDFAnnot_GetInkListPath","_FPDFAnnot_GetLine","_FPDFAnnot_GetLink","_FPDFAnnot_GetLinkedAnnot","_FPDFAnnot_GetNumberValue","_FPDFAnnot_GetObject","_FPDFAnnot_GetObjectCount","_FPDFAnnot_GetOptionCount","_FPDFAnnot_GetOptionLabel","_FPDFAnnot_GetRect","_FPDFAnnot_GetStringValue","_FPDFAnnot_GetSubtype","_FPDFAnnot_GetValueType","_FPDFAnnot_GetVertices","_FPDFAnnot_HasAttachmentPoints","_FPDFAnnot_HasKey","_FPDFAnnot_IsChecked","_FPDFAnnot_IsObjectSupportedSubtype","_FPDFAnnot_IsOptionSelected","_FPDFAnnot_IsSupportedSubtype","_FPDFAnnot_RemoveInkList","_FPDFAnnot_RemoveObject","_FPDFAnnot_SetAP","_FPDFAnnot_SetAttachmentPoints","_FPDFAnnot_SetBorder","_FPDFAnnot_SetColor","_FPDFAnnot_SetFlags","_FPDFAnnot_SetFocusableSubtypes","_FPDFAnnot_SetFontColor","_FPDFAnnot_SetFormFieldFlags","_FPDFAnnot_SetRect","_FPDFAnnot_SetStringValue","_FPDFAnnot_SetURI","_FPDFAnnot_UpdateObject","_FPDFAttachment_GetFile","_FPDFAttachment_GetName","_FPDFAttachment_GetStringValue","_FPDFAttachment_GetSubtype","_FPDFAttachment_GetValueType","_FPDFAttachment_HasKey","_FPDFAttachment_SetFile","_FPDFAttachment_SetStringValue","_FPDFAvail_Create","_FPDFAvail_Destroy","_FPDFAvail_GetDocument","_FPDFAvail_GetFirstPageNum","_FPDFAvail_IsDocAvail","_FPDFAvail_IsFormAvail","_FPDFAvail_IsLinearized","_FPDFAvail_IsPageAvail","_FPDFBitmap_Create","_FPDFBitmap_CreateEx","_FPDFBitmap_Destroy","_FPDFBitmap_FillRect","_FPDFBitmap_GetBuffer","_FPDFBitmap_GetFormat","_FPDFBitmap_GetHeight","_FPDFBitmap_GetStride","_FPDFBitmap_GetWidth","_FPDFBookmark_Find","_FPDFBookmark_GetAction","_FPDFBookmark_GetCount","_FPDFBookmark_GetDest","_FPDFBookmark_GetFirstChild","_FPDFBookmark_GetNextSibling","_FPDFBookmark_GetTitle","_FPDFCatalog_GetLanguage","_FPDFCatalog_IsTagged","_FPDFCatalog_SetLanguage","_FPDFClipPath_CountPaths","_FPDFClipPath_CountPathSegments","_FPDFClipPath_GetPathSegment","_FPDFDest_GetDestPageIndex","_FPDFDest_GetLocationInPage","_FPDFDest_GetView","_FPDFDoc_AddAttachment","_FPDFDoc_CloseJavaScriptAction","_FPDFDoc_DeleteAttachment","_FPDFDOC_ExitFormFillEnvironment","_FPDFDoc_GetAttachment","_FPDFDoc_GetAttachmentCount","_FPDFDoc_GetJavaScriptAction","_FPDFDoc_GetJavaScriptActionCount","_FPDFDoc_GetPageMode","_FPDFDOC_InitFormFillEnvironment","_FPDFFont_Close","_FPDFFont_GetAscent","_FPDFFont_GetBaseFontName","_FPDFFont_GetDescent","_FPDFFont_GetFamilyName","_FPDFFont_GetFlags","_FPDFFont_GetFontData","_FPDFFont_GetGlyphPath","_FPDFFont_GetGlyphWidth","_FPDFFont_GetIsEmbedded","_FPDFFont_GetItalicAngle","_FPDFFont_GetWeight","_FPDFFormObj_CountObjects","_FPDFFormObj_GetObject","_FPDFFormObj_RemoveObject","_FPDFGlyphPath_CountGlyphSegments","_FPDFGlyphPath_GetGlyphPathSegment","_FPDFImageObj_GetBitmap","_FPDFImageObj_GetIccProfileDataDecoded","_FPDFImageObj_GetImageDataDecoded","_FPDFImageObj_GetImageDataRaw","_FPDFImageObj_GetImageFilter","_FPDFImageObj_GetImageFilterCount","_FPDFImageObj_GetImageMetadata","_FPDFImageObj_GetImagePixelSize","_FPDFImageObj_GetRenderedBitmap","_FPDFImageObj_LoadJpegFile","_FPDFImageObj_LoadJpegFileInline","_FPDFImageObj_SetBitmap","_FPDFImageObj_SetMatrix","_FPDFJavaScriptAction_GetName","_FPDFJavaScriptAction_GetScript","_FPDFLink_CloseWebLinks","_FPDFLink_CountQuadPoints","_FPDFLink_CountRects","_FPDFLink_CountWebLinks","_FPDFLink_Enumerate","_FPDFLink_GetAction","_FPDFLink_GetAnnot","_FPDFLink_GetAnnotRect","_FPDFLink_GetDest","_FPDFLink_GetLinkAtPoint","_FPDFLink_GetLinkZOrderAtPoint","_FPDFLink_GetQuadPoints","_FPDFLink_GetRect","_FPDFLink_GetTextRange","_FPDFLink_GetURL","_FPDFLink_LoadWebLinks","_FPDFPage_CloseAnnot","_FPDFPage_CountObjects","_FPDFPage_CreateAnnot","_FPDFPage_Delete","_FPDFPage_Flatten","_FPDFPage_FormFieldZOrderAtPoint","_FPDFPage_GenerateContent","_FPDFPage_GetAnnot","_FPDFPage_GetAnnotCount","_FPDFPage_GetAnnotIndex","_FPDFPage_GetArtBox","_FPDFPage_GetBleedBox","_FPDFPage_GetCropBox","_FPDFPage_GetDecodedThumbnailData","_FPDFPage_GetMediaBox","_FPDFPage_GetObject","_FPDFPage_GetRawThumbnailData","_FPDFPage_GetRotation","_FPDFPage_GetThumbnailAsBitmap","_FPDFPage_GetTrimBox","_FPDFPage_HasFormFieldAtPoint","_FPDFPage_HasTransparency","_FPDFPage_InsertClipPath","_FPDFPage_InsertObject","_FPDFPage_InsertObjectAtIndex","_FPDFPage_New","_FPDFPage_RemoveAnnot","_FPDFPage_RemoveObject","_FPDFPage_SetArtBox","_FPDFPage_SetBleedBox","_FPDFPage_SetCropBox","_FPDFPage_SetMediaBox","_FPDFPage_SetRotation","_FPDFPage_SetTrimBox","_FPDFPage_TransformAnnots","_FPDFPage_TransFormWithClip","_FPDFPageObj_AddMark","_FPDFPageObj_CountMarks","_FPDFPageObj_CreateNewPath","_FPDFPageObj_CreateNewRect","_FPDFPageObj_CreateTextObj","_FPDFPageObj_Destroy","_FPDFPageObj_GetBounds","_FPDFPageObj_GetClipPath","_FPDFPageObj_GetDashArray","_FPDFPageObj_GetDashCount","_FPDFPageObj_GetDashPhase","_FPDFPageObj_GetFillColor","_FPDFPageObj_GetIsActive","_FPDFPageObj_GetLineCap","_FPDFPageObj_GetLineJoin","_FPDFPageObj_GetMark","_FPDFPageObj_GetMarkedContentID","_FPDFPageObj_GetMatrix","_FPDFPageObj_GetRotatedBounds","_FPDFPageObj_GetStrokeColor","_FPDFPageObj_GetStrokeWidth","_FPDFPageObj_GetType","_FPDFPageObj_HasTransparency","_FPDFPageObj_NewImageObj","_FPDFPageObj_NewTextObj","_FPDFPageObj_RemoveMark","_FPDFPageObj_SetBlendMode","_FPDFPageObj_SetDashArray","_FPDFPageObj_SetDashPhase","_FPDFPageObj_SetFillColor","_FPDFPageObj_SetIsActive","_FPDFPageObj_SetLineCap","_FPDFPageObj_SetLineJoin","_FPDFPageObj_SetMatrix","_FPDFPageObj_SetStrokeColor","_FPDFPageObj_SetStrokeWidth","_FPDFPageObj_Transform","_FPDFPageObj_TransformClipPath","_FPDFPageObj_TransformF","_FPDFPageObjMark_CountParams","_FPDFPageObjMark_GetName","_FPDFPageObjMark_GetParamBlobValue","_FPDFPageObjMark_GetParamFloatValue","_FPDFPageObjMark_GetParamIntValue","_FPDFPageObjMark_GetParamKey","_FPDFPageObjMark_GetParamStringValue","_FPDFPageObjMark_GetParamValueType","_FPDFPageObjMark_RemoveParam","_FPDFPageObjMark_SetBlobParam","_FPDFPageObjMark_SetFloatParam","_FPDFPageObjMark_SetIntParam","_FPDFPageObjMark_SetStringParam","_FPDFPath_BezierTo","_FPDFPath_Close","_FPDFPath_CountSegments","_FPDFPath_GetDrawMode","_FPDFPath_GetPathSegment","_FPDFPath_LineTo","_FPDFPath_MoveTo","_FPDFPath_SetDrawMode","_FPDFPathSegment_GetClose","_FPDFPathSegment_GetPoint","_FPDFPathSegment_GetType","_FPDFSignatureObj_GetByteRange","_FPDFSignatureObj_GetContents","_FPDFSignatureObj_GetDocMDPPermission","_FPDFSignatureObj_GetReason","_FPDFSignatureObj_GetSubFilter","_FPDFSignatureObj_GetTime","_FPDFText_ClosePage","_FPDFText_CountChars","_FPDFText_CountRects","_FPDFText_FindClose","_FPDFText_FindNext","_FPDFText_FindPrev","_FPDFText_FindStart","_FPDFText_GetBoundedText","_FPDFText_GetCharAngle","_FPDFText_GetCharBox","_FPDFText_GetCharIndexAtPos","_FPDFText_GetCharIndexFromTextIndex","_FPDFText_GetCharOrigin","_FPDFText_GetFillColor","_FPDFText_GetFontInfo","_FPDFText_GetFontSize","_FPDFText_GetFontWeight","_FPDFText_GetLooseCharBox","_FPDFText_GetMatrix","_FPDFText_GetRect","_FPDFText_GetSchCount","_FPDFText_GetSchResultIndex","_FPDFText_GetStrokeColor","_FPDFText_GetText","_FPDFText_GetTextIndexFromCharIndex","_FPDFText_GetTextObject","_FPDFText_GetUnicode","_FPDFText_HasUnicodeMapError","_FPDFText_IsGenerated","_FPDFText_IsHyphen","_FPDFText_LoadCidType2Font","_FPDFText_LoadFont","_FPDFText_LoadPage","_FPDFText_LoadStandardFont","_FPDFText_SetCharcodes","_FPDFText_SetText","_FPDFTextObj_GetFont","_FPDFTextObj_GetFontSize","_FPDFTextObj_GetRenderedBitmap","_FPDFTextObj_GetText","_FPDFTextObj_GetTextRenderMode","_FPDFTextObj_SetTextRenderMode","_PDFiumExt_CloseFileWriter","_PDFiumExt_CloseFormFillInfo","_PDFiumExt_ExitFormFillEnvironment","_PDFiumExt_GetFileWriterData","_PDFiumExt_GetFileWriterSize","_PDFiumExt_Init","_PDFiumExt_InitFormFillEnvironment","_PDFiumExt_OpenFileWriter","_PDFiumExt_OpenFormFillInfo","_PDFiumExt_SaveAsCopy","_malloc","_free","_memory","___indirect_function_table","onRuntimeInitialized"].forEach(e=>{Object.getOwnPropertyDescriptor(a,e)||Object.defineProperty(a,e,{get:()=>W("You are getting "+e+" on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js"),set:()=>W("You are setting "+e+" on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js")})});var i="object"==typeof window,s="function"==typeof importScripts;"object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node&&process.type;var u,m,F=!i&&!s,l=Object.assign({},o),d="./this.program",P="";if(F){if("object"==typeof window||"function"==typeof importScripts)throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");m=e=>{if("function"==typeof readbuffer)return new Uint8Array(readbuffer(e));let t=read(e,"binary");return C("object"==typeof t),t},u=e=>new Promise((t,n)=>{setTimeout(()=>t(m(e)))}),globalThis.clearTimeout??=e=>{},globalThis.setTimeout??=e=>"function"==typeof e?e():W(),"undefined"!=typeof print&&(globalThis.console??={},console.log=print,console.warn=console.error=globalThis.printErr??print)}else{if(!i&&!s)throw new Error("environment detection error");if(s?P=self.location.href:"undefined"!=typeof document&&document.currentScript&&(P=document.currentScript.src),j&&(P=j),P=P.startsWith("blob:")?"":P.substr(0,P.replace(/[?#].*/,"").lastIndexOf("/")+1),"object"!=typeof window&&"function"!=typeof importScripts)throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");s&&(m=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),u=e=>(C(!J(e),"readAsync does not work with file:// URLs"),fetch(e,{credentials:"same-origin"}).then(e=>e.ok?e.arrayBuffer():Promise.reject(new Error(e.status+" : "+e.url))))}var _,c=o.print||console.log.bind(console),g=o.printErr||console.error.bind(console);Object.assign(o,l),l=null,_="fetchSettings",Object.getOwnPropertyDescriptor(o,_)&&W(`\`Module.${_}\` was supplied but \`${_}\` not included in INCOMING_MODULE_JS_API`),o.arguments&&o.arguments,te("arguments","arguments_"),o.thisProgram&&(d=o.thisProgram),te("thisProgram","thisProgram"),C(void 0===o.memoryInitializerPrefixURL,"Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead"),C(void 0===o.pthreadMainPrefixURL,"Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead"),C(void 0===o.cdInitializerPrefixURL,"Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead"),C(void 0===o.filePackagePrefixURL,"Module.filePackagePrefixURL option was removed, use Module.locateFile instead"),C(void 0===o.read,"Module.read option was removed"),C(void 0===o.readAsync,"Module.readAsync option was removed (modify readAsync in JS)"),C(void 0===o.readBinary,"Module.readBinary option was removed (modify readBinary in JS)"),C(void 0===o.setWindowTitle,"Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)"),C(void 0===o.TOTAL_MEMORY,"Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY"),te("asm","wasmExports"),te("readAsync","readAsync"),te("readBinary","readBinary"),te("setWindowTitle","setWindowTitle");var h,D=o.wasmBinary;te("wasmBinary","wasmBinary"),"object"!=typeof WebAssembly&&g("no native wasm support detected");var b,p,f,A,E,y,M,G,S=!1;function C(e,t){e||W("Assertion failed"+(t?": "+t:""))}function x(){var e=h.buffer;o.HEAP8=b=new Int8Array(e),o.HEAP16=f=new Int16Array(e),o.HEAPU8=p=new Uint8Array(e),o.HEAPU16=A=new Uint16Array(e),o.HEAP32=E=new Int32Array(e),o.HEAPU32=y=new Uint32Array(e),o.HEAPF32=M=new Float32Array(e),o.HEAPF64=G=new Float64Array(e)}function T(){if(!S){var e=it();0==e&&(e+=4);var t=y[e>>2],n=y[e+4>>2];34821223==t&&2310721022==n||W(`Stack overflow! Stack cookie has been overwritten at ${se(e)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${se(n)} ${se(t)}`),1668509029!=y[0]&&W("Runtime error: The application has corrupted its heap memory area (address zero)!")}}C(!o.STACK_SIZE,"STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time"),C("undefined"!=typeof Int32Array&&"undefined"!=typeof Float64Array&&null!=Int32Array.prototype.subarray&&null!=Int32Array.prototype.set,"JS engine does not provide full typed array support"),C(!o.wasmMemory,"Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally"),C(!o.INITIAL_MEMORY,"Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically");var v=[],O=[],R=[],k=!1;function w(e){v.unshift(e)}function I(e){R.unshift(e)}C(Math.imul,"This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"),C(Math.fround,"This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"),C(Math.clz32,"This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"),C(Math.trunc,"This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill");var B=0,L=null,N=null,V={};function U(e){for(var t=e;;){if(!V[e])return e;e=t+Math.random()}}function z(e){B++,o.monitorRunDependencies?.(B),e?(C(!V[e]),V[e]=1,null===L&&"undefined"!=typeof setInterval&&(L=setInterval(()=>{if(S)return clearInterval(L),void(L=null);var e=!1;for(var t in V)e||(e=!0,g("still waiting on run dependencies:")),g(`dependency: ${t}`);e&&g("(end of list)")},1e4))):g("warning: run dependency added without ID")}function $(e){if(B--,o.monitorRunDependencies?.(B),e?(C(V[e]),delete V[e]):g("warning: run dependency removed without ID"),0==B&&(null!==L&&(clearInterval(L),L=null),N)){var t=N;N=null,t()}}function W(e){o.onAbort?.(e),g(e="Aborted("+e+")"),S=!0;var t=new WebAssembly.RuntimeError(e);throw r(t),t}var H,X,Y,K=e=>e.startsWith("data:application/octet-stream;base64,"),J=e=>e.startsWith("file://");function q(e,t){return(...n)=>{C(k,`native function \`${e}\` called before runtime initialization`);var r=Qe[e];return C(r,`exported native function \`${e}\` not found`),C(n.length<=t,`native function \`${e}\` called with ${n.length} args but expects ${t}`),r(...n)}}function Q(){if(o.locateFile){var e="pdfium.wasm";return K(e)?e:(t=e,o.locateFile?o.locateFile(t,P):P+t)}var t;return F?"pdfium.wasm":new URL("pdfium.wasm",import.meta.url).href}function Z(e){if(e==H&&D)return new Uint8Array(D);if(m)return m(e);throw"both async and sync fetching of the wasm failed"}function ee(e,t,n){return function(e){return D?Promise.resolve().then(()=>Z(e)):u(e).then(e=>new Uint8Array(e),()=>Z(e))}(e).then(e=>WebAssembly.instantiate(e,t)).then(n,e=>{g(`failed to asynchronously prepare wasm: ${e}`),J(H)&&g(`warning: Loading from a file URI (${H}) is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing`),W(e)})}if((()=>{var e=new Int16Array(1),t=new Int8Array(e.buffer);if(e[0]=25459,115!==t[0]||99!==t[1])throw"Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)"})(),o.ENVIRONMENT)throw new Error("Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)");function te(e,t,n=!0){Object.getOwnPropertyDescriptor(o,e)||Object.defineProperty(o,e,{configurable:!0,get(){W(`\`Module.${e}\` has been replaced by \`${t}\``+(n?" (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)":""))}})}function ne(e){return"FS_createPath"===e||"FS_createDataFile"===e||"FS_createPreloadedFile"===e||"FS_unlink"===e||"addRunDependency"===e||"FS_createLazyFile"===e||"FS_createDevice"===e||"removeRunDependency"===e}function re(e,t){"undefined"==typeof globalThis||Object.getOwnPropertyDescriptor(globalThis,e)||Object.defineProperty(globalThis,e,{configurable:!0,get(){t()}})}function oe(e,t){re(e,()=>{Fe(`\`${e}\` is not longer defined by emscripten. ${t}`)})}function ae(e){Object.getOwnPropertyDescriptor(o,e)||Object.defineProperty(o,e,{configurable:!0,get(){var t=`'${e}' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)`;ne(e)&&(t+=". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you"),W(t)}})}oe("buffer","Please use HEAP8.buffer or wasmMemory.buffer"),oe("asm","Please use wasmExports instead");var ie=e=>{e.forEach(e=>e(o))};o.noExitRuntime;var se=e=>(C("number"==typeof e),"0x"+(e>>>=0).toString(16).padStart(8,"0")),ue=e=>st(e),me=()=>mt(),Fe=e=>{Fe.shown||={},Fe.shown[e]||(Fe.shown[e]=1,g(e))},le="undefined"!=typeof TextDecoder?new TextDecoder:void 0,de=(e,t=0,n=NaN)=>{for(var r=t+n,o=t;e[o]&&!(o>=r);)++o;if(o-t>16&&e.buffer&&le)return le.decode(e.subarray(t,o));for(var a="";t>10,56320|1023&m)}}else a+=String.fromCharCode((31&i)<<6|s)}else a+=String.fromCharCode(i)}return a},Pe=(e,t)=>(C("number"==typeof e,`UTF8ToString expects a number (got ${typeof e})`),e?de(p,e,t):"");function _e(){C(null!=Re.varargs);var e=E[+Re.varargs>>2];return Re.varargs+=4,e}var ce=_e,ge={isAbs:e=>"/"===e.charAt(0),splitPath:e=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1),normalizeArray:(e,t)=>{for(var n=0,r=e.length-1;r>=0;r--){var o=e[r];"."===o?e.splice(r,1):".."===o?(e.splice(r,1),n++):n&&(e.splice(r,1),n--)}if(t)for(;n;n--)e.unshift("..");return e},normalize:e=>{var t=ge.isAbs(e),n="/"===e.substr(-1);return(e=ge.normalizeArray(e.split("/").filter(e=>!!e),!t).join("/"))||t||(e="."),e&&n&&(e+="/"),(t?"/":"")+e},dirname:e=>{var t=ge.splitPath(e),n=t[0],r=t[1];return n||r?(r&&(r=r.substr(0,r.length-1)),n+r):"."},basename:e=>{if("/"===e)return"/";var t=(e=(e=ge.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)},join:(...e)=>ge.normalize(e.join("/")),join2:(e,t)=>ge.normalize(e+"/"+t)},he=e=>(he=(()=>{if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues)return e=>crypto.getRandomValues(e);W("no cryptographic support found for randomDevice. consider polyfilling it if you want to use something insecure like Math.random(), e.g. put this in a --pre-js: var crypto = { getRandomValues: (array) => { for (var i = 0; i < array.length; i++) array[i] = (Math.random()*256)|0 } };")})())(e),De={resolve:(...e)=>{for(var t="",n=!1,r=e.length-1;r>=-1&&!n;r--){var o=r>=0?e[r]:Oe.cwd();if("string"!=typeof o)throw new TypeError("Arguments to path.resolve must be strings");if(!o)return"";t=o+"/"+t,n=ge.isAbs(o)}return(n?"/":"")+(t=ge.normalizeArray(t.split("/").filter(e=>!!e),!n).join("/"))||"."},relative:(e,t)=>{function n(e){for(var t=0;t=0&&""===e[n];n--);return t>n?[]:e.slice(t,n-t+1)}e=De.resolve(e).substr(1),t=De.resolve(t).substr(1);for(var r=n(e.split("/")),o=n(t.split("/")),a=Math.min(r.length,o.length),i=a,s=0;s{for(var t=0,n=0;n=55296&&r<=57343?(t+=4,++n):t+=3}return t},fe=(e,t,n,r)=>{if(C("string"==typeof e,`stringToUTF8Array expects a string (got ${typeof e})`),!(r>0))return 0;for(var o=n,a=n+r-1,i=0;i=55296&&s<=57343&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++i)),s<=127){if(n>=a)break;t[n++]=s}else if(s<=2047){if(n+1>=a)break;t[n++]=192|s>>6,t[n++]=128|63&s}else if(s<=65535){if(n+2>=a)break;t[n++]=224|s>>12,t[n++]=128|s>>6&63,t[n++]=128|63&s}else{if(n+3>=a)break;s>1114111&&Fe("Invalid Unicode code point "+se(s)+" encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF)."),t[n++]=240|s>>18,t[n++]=128|s>>12&63,t[n++]=128|s>>6&63,t[n++]=128|63&s}}return t[n]=0,n-o};function Ae(e,t,n){var r=pe(e)+1,o=new Array(r),a=fe(e,o,0,o.length);return o.length=a,o}var Ee,ye,Me={ttys:[],init(){},shutdown(){},register(e,t){Me.ttys[e]={input:[],output:[],ops:t},Oe.registerDevice(e,Me.stream_ops)},stream_ops:{open(e){var t=Me.ttys[e.node.rdev];if(!t)throw new Oe.ErrnoError(43);e.tty=t,e.seekable=!1},close(e){e.tty.ops.fsync(e.tty)},fsync(e){e.tty.ops.fsync(e.tty)},read(e,t,n,r,o){if(!e.tty||!e.tty.ops.get_char)throw new Oe.ErrnoError(60);for(var a=0,i=0;i(()=>{if(!be.length){var e=null;if("undefined"!=typeof window&&"function"==typeof window.prompt?null!==(e=window.prompt("Input: "))&&(e+="\n"):"function"==typeof readline&&(e=readline())&&(e+="\n"),!e)return null;be=Ae(e)}return be.shift()})(),put_char(e,t){null===t||10===t?(c(de(e.output)),e.output=[]):0!=t&&e.output.push(t)},fsync(e){e.output&&e.output.length>0&&(c(de(e.output)),e.output=[])},ioctl_tcgets:e=>({c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}),ioctl_tcsets:(e,t,n)=>0,ioctl_tiocgwinsz:e=>[24,80]},default_tty1_ops:{put_char(e,t){null===t||10===t?(g(de(e.output)),e.output=[]):0!=t&&e.output.push(t)},fsync(e){e.output&&e.output.length>0&&(g(de(e.output)),e.output=[])}}},Ge=(e,t)=>(C(t,"alignment argument is required"),Math.ceil(e/t)*t),Se=e=>{e=Ge(e,65536);var t=nt(65536,e);return t&&((e,t)=>{p.fill(0,e,e+t)})(t,e),t},Ce={ops_table:null,mount:e=>Ce.createNode(null,"/",16895,0),createNode(e,t,n,r){if(Oe.isBlkdev(n)||Oe.isFIFO(n))throw new Oe.ErrnoError(63);Ce.ops_table||={dir:{node:{getattr:Ce.node_ops.getattr,setattr:Ce.node_ops.setattr,lookup:Ce.node_ops.lookup,mknod:Ce.node_ops.mknod,rename:Ce.node_ops.rename,unlink:Ce.node_ops.unlink,rmdir:Ce.node_ops.rmdir,readdir:Ce.node_ops.readdir,symlink:Ce.node_ops.symlink},stream:{llseek:Ce.stream_ops.llseek}},file:{node:{getattr:Ce.node_ops.getattr,setattr:Ce.node_ops.setattr},stream:{llseek:Ce.stream_ops.llseek,read:Ce.stream_ops.read,write:Ce.stream_ops.write,allocate:Ce.stream_ops.allocate,mmap:Ce.stream_ops.mmap,msync:Ce.stream_ops.msync}},link:{node:{getattr:Ce.node_ops.getattr,setattr:Ce.node_ops.setattr,readlink:Ce.node_ops.readlink},stream:{}},chrdev:{node:{getattr:Ce.node_ops.getattr,setattr:Ce.node_ops.setattr},stream:Oe.chrdev_stream_ops}};var o=Oe.createNode(e,t,n,r);return Oe.isDir(o.mode)?(o.node_ops=Ce.ops_table.dir.node,o.stream_ops=Ce.ops_table.dir.stream,o.contents={}):Oe.isFile(o.mode)?(o.node_ops=Ce.ops_table.file.node,o.stream_ops=Ce.ops_table.file.stream,o.usedBytes=0,o.contents=null):Oe.isLink(o.mode)?(o.node_ops=Ce.ops_table.link.node,o.stream_ops=Ce.ops_table.link.stream):Oe.isChrdev(o.mode)&&(o.node_ops=Ce.ops_table.chrdev.node,o.stream_ops=Ce.ops_table.chrdev.stream),o.timestamp=Date.now(),e&&(e.contents[t]=o,e.timestamp=o.timestamp),o},getFileDataAsTypedArray:e=>e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0),expandFileStorage(e,t){var n=e.contents?e.contents.length:0;if(!(n>=t)){t=Math.max(t,n*(n<1048576?2:1.125)>>>0),0!=n&&(t=Math.max(t,256));var r=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(r.subarray(0,e.usedBytes),0)}},resizeFileStorage(e,t){if(e.usedBytes!=t)if(0==t)e.contents=null,e.usedBytes=0;else{var n=e.contents;e.contents=new Uint8Array(t),n&&e.contents.set(n.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}},node_ops:{getattr(e){var t={};return t.dev=Oe.isChrdev(e.mode)?e.id:1,t.ino=e.id,t.mode=e.mode,t.nlink=1,t.uid=0,t.gid=0,t.rdev=e.rdev,Oe.isDir(e.mode)?t.size=4096:Oe.isFile(e.mode)?t.size=e.usedBytes:Oe.isLink(e.mode)?t.size=e.link.length:t.size=0,t.atime=new Date(e.timestamp),t.mtime=new Date(e.timestamp),t.ctime=new Date(e.timestamp),t.blksize=4096,t.blocks=Math.ceil(t.size/t.blksize),t},setattr(e,t){void 0!==t.mode&&(e.mode=t.mode),void 0!==t.timestamp&&(e.timestamp=t.timestamp),void 0!==t.size&&Ce.resizeFileStorage(e,t.size)},lookup(e,t){throw Oe.genericErrors[44]},mknod:(e,t,n,r)=>Ce.createNode(e,t,n,r),rename(e,t,n){if(Oe.isDir(e.mode)){var r;try{r=Oe.lookupNode(t,n)}catch(e){}if(r)for(var o in r.contents)throw new Oe.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=n,t.contents[n]=e,t.timestamp=e.parent.timestamp},unlink(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir(e,t){var n=Oe.lookupNode(e,t);for(var r in n.contents)throw new Oe.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir(e){var t=[".",".."];for(var n of Object.keys(e.contents))t.push(n);return t},symlink(e,t,n){var r=Ce.createNode(e,t,41471,0);return r.link=n,r},readlink(e){if(!Oe.isLink(e.mode))throw new Oe.ErrnoError(28);return e.link}},stream_ops:{read(e,t,n,r,o){var a=e.node.contents;if(o>=e.node.usedBytes)return 0;var i=Math.min(e.node.usedBytes-o,r);if(C(i>=0),i>8&&a.subarray)t.set(a.subarray(o,o+i),n);else for(var s=0;s0||n+t(Ce.stream_ops.write(e,t,0,r,n,!1),0)}},xe=o.preloadPlugins||[],Te=(e,t)=>{var n=0;return e&&(n|=365),t&&(n|=146),n},ve={EPERM:63,ENOENT:44,ESRCH:71,EINTR:27,EIO:29,ENXIO:60,E2BIG:1,ENOEXEC:45,EBADF:8,ECHILD:12,EAGAIN:6,EWOULDBLOCK:6,ENOMEM:48,EACCES:2,EFAULT:21,ENOTBLK:105,EBUSY:10,EEXIST:20,EXDEV:75,ENODEV:43,ENOTDIR:54,EISDIR:31,EINVAL:28,ENFILE:41,EMFILE:33,ENOTTY:59,ETXTBSY:74,EFBIG:22,ENOSPC:51,ESPIPE:70,EROFS:69,EMLINK:34,EPIPE:64,EDOM:18,ERANGE:68,ENOMSG:49,EIDRM:24,ECHRNG:106,EL2NSYNC:156,EL3HLT:107,EL3RST:108,ELNRNG:109,EUNATCH:110,ENOCSI:111,EL2HLT:112,EDEADLK:16,ENOLCK:46,EBADE:113,EBADR:114,EXFULL:115,ENOANO:104,EBADRQC:103,EBADSLT:102,EDEADLOCK:16,EBFONT:101,ENOSTR:100,ENODATA:116,ETIME:117,ENOSR:118,ENONET:119,ENOPKG:120,EREMOTE:121,ENOLINK:47,EADV:122,ESRMNT:123,ECOMM:124,EPROTO:65,EMULTIHOP:36,EDOTDOT:125,EBADMSG:9,ENOTUNIQ:126,EBADFD:127,EREMCHG:128,ELIBACC:129,ELIBBAD:130,ELIBSCN:131,ELIBMAX:132,ELIBEXEC:133,ENOSYS:52,ENOTEMPTY:55,ENAMETOOLONG:37,ELOOP:32,EOPNOTSUPP:138,EPFNOSUPPORT:139,ECONNRESET:15,ENOBUFS:42,EAFNOSUPPORT:5,EPROTOTYPE:67,ENOTSOCK:57,ENOPROTOOPT:50,ESHUTDOWN:140,ECONNREFUSED:14,EADDRINUSE:3,ECONNABORTED:13,ENETUNREACH:40,ENETDOWN:38,ETIMEDOUT:73,EHOSTDOWN:142,EHOSTUNREACH:23,EINPROGRESS:26,EALREADY:7,EDESTADDRREQ:17,EMSGSIZE:35,EPROTONOSUPPORT:66,ESOCKTNOSUPPORT:137,EADDRNOTAVAIL:4,ENETRESET:39,EISCONN:30,ENOTCONN:53,ETOOMANYREFS:141,EUSERS:136,EDQUOT:19,ESTALE:72,ENOTSUP:138,ENOMEDIUM:148,EILSEQ:25,EOVERFLOW:61,ECANCELED:11,ENOTRECOVERABLE:56,EOWNERDEAD:62,ESTRPIPE:135},Oe={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:class extends Error{constructor(e){for(var t in super(k?(e=>Pe(rt(e)))(e):""),this.name="ErrnoError",this.errno=e,ve)if(ve[t]===e){this.code=t;break}}},genericErrors:{},filesystems:null,syncFSRequests:0,readFiles:{},FSStream:class{constructor(){this.shared={}}get object(){return this.node}set object(e){this.node=e}get isRead(){return 1!=(2097155&this.flags)}get isWrite(){return!!(2097155&this.flags)}get isAppend(){return 1024&this.flags}get flags(){return this.shared.flags}set flags(e){this.shared.flags=e}get position(){return this.shared.position}set position(e){this.shared.position=e}},FSNode:class{constructor(e,t,n,r){e||(e=this),this.parent=e,this.mount=e.mount,this.mounted=null,this.id=Oe.nextInode++,this.name=t,this.mode=n,this.node_ops={},this.stream_ops={},this.rdev=r,this.readMode=365,this.writeMode=146}get read(){return(this.mode&this.readMode)===this.readMode}set read(e){e?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(e){e?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return Oe.isDir(this.mode)}get isDevice(){return Oe.isChrdev(this.mode)}},lookupPath(e,t={}){if(!(e=De.resolve(e)))return{path:"",node:null};if((t=Object.assign({follow_mount:!0,recurse_count:0},t)).recurse_count>8)throw new Oe.ErrnoError(32);for(var n=e.split("/").filter(e=>!!e),r=Oe.root,o="/",a=0;a40)throw new Oe.ErrnoError(32)}}return{path:o,node:r}},getPath(e){for(var t;;){if(Oe.isRoot(e)){var n=e.mount.mountpoint;return t?"/"!==n[n.length-1]?`${n}/${t}`:n+t:n}t=t?`${e.name}/${t}`:e.name,e=e.parent}},hashName(e,t){for(var n=0,r=0;r>>0)%Oe.nameTable.length},hashAddNode(e){var t=Oe.hashName(e.parent.id,e.name);e.name_next=Oe.nameTable[t],Oe.nameTable[t]=e},hashRemoveNode(e){var t=Oe.hashName(e.parent.id,e.name);if(Oe.nameTable[t]===e)Oe.nameTable[t]=e.name_next;else for(var n=Oe.nameTable[t];n;){if(n.name_next===e){n.name_next=e.name_next;break}n=n.name_next}},lookupNode(e,t){var n=Oe.mayLookup(e);if(n)throw new Oe.ErrnoError(n);for(var r=Oe.hashName(e.id,t),o=Oe.nameTable[r];o;o=o.name_next){var a=o.name;if(o.parent.id===e.id&&a===t)return o}return Oe.lookup(e,t)},createNode(e,t,n,r){C("object"==typeof e);var o=new Oe.FSNode(e,t,n,r);return Oe.hashAddNode(o),o},destroyNode(e){Oe.hashRemoveNode(e)},isRoot:e=>e===e.parent,isMountpoint:e=>!!e.mounted,isFile:e=>32768==(61440&e),isDir:e=>16384==(61440&e),isLink:e=>40960==(61440&e),isChrdev:e=>8192==(61440&e),isBlkdev:e=>24576==(61440&e),isFIFO:e=>4096==(61440&e),isSocket:e=>!(49152&~e),flagsToPermissionString(e){var t=["r","w","rw"][3&e];return 512&e&&(t+="w"),t},nodePermissions:(e,t)=>Oe.ignorePermissions||(!t.includes("r")||292&e.mode)&&(!t.includes("w")||146&e.mode)&&(!t.includes("x")||73&e.mode)?0:2,mayLookup(e){if(!Oe.isDir(e.mode))return 54;var t=Oe.nodePermissions(e,"x");return t||(e.node_ops.lookup?0:2)},mayCreate(e,t){try{return Oe.lookupNode(e,t),20}catch(e){}return Oe.nodePermissions(e,"wx")},mayDelete(e,t,n){var r;try{r=Oe.lookupNode(e,t)}catch(e){return e.errno}var o=Oe.nodePermissions(e,"wx");if(o)return o;if(n){if(!Oe.isDir(r.mode))return 54;if(Oe.isRoot(r)||Oe.getPath(r)===Oe.cwd())return 10}else if(Oe.isDir(r.mode))return 31;return 0},mayOpen:(e,t)=>e?Oe.isLink(e.mode)?32:Oe.isDir(e.mode)&&("r"!==Oe.flagsToPermissionString(t)||512&t)?31:Oe.nodePermissions(e,Oe.flagsToPermissionString(t)):44,MAX_OPEN_FDS:4096,nextfd(){for(var e=0;e<=Oe.MAX_OPEN_FDS;e++)if(!Oe.streams[e])return e;throw new Oe.ErrnoError(33)},getStreamChecked(e){var t=Oe.getStream(e);if(!t)throw new Oe.ErrnoError(8);return t},getStream:e=>Oe.streams[e],createStream:(e,t=-1)=>(C(t>=-1),e=Object.assign(new Oe.FSStream,e),-1==t&&(t=Oe.nextfd()),e.fd=t,Oe.streams[t]=e,e),closeStream(e){Oe.streams[e]=null},dupStream(e,t=-1){var n=Oe.createStream(e,t);return n.stream_ops?.dup?.(n),n},chrdev_stream_ops:{open(e){var t=Oe.getDevice(e.node.rdev);e.stream_ops=t.stream_ops,e.stream_ops.open?.(e)},llseek(){throw new Oe.ErrnoError(70)}},major:e=>e>>8,minor:e=>255&e,makedev:(e,t)=>e<<8|t,registerDevice(e,t){Oe.devices[e]={stream_ops:t}},getDevice:e=>Oe.devices[e],getMounts(e){for(var t=[],n=[e];n.length;){var r=n.pop();t.push(r),n.push(...r.mounts)}return t},syncfs(e,t){"function"==typeof e&&(t=e,e=!1),Oe.syncFSRequests++,Oe.syncFSRequests>1&&g(`warning: ${Oe.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var n=Oe.getMounts(Oe.root.mount),r=0;function o(e){return C(Oe.syncFSRequests>0),Oe.syncFSRequests--,t(e)}function a(e){if(e)return a.errored?void 0:(a.errored=!0,o(e));++r>=n.length&&o(null)}n.forEach(t=>{if(!t.type.syncfs)return a(null);t.type.syncfs(t,e,a)})},mount(e,t,n){if("string"==typeof e)throw e;var r,o="/"===n,a=!n;if(o&&Oe.root)throw new Oe.ErrnoError(10);if(!o&&!a){var i=Oe.lookupPath(n,{follow_mount:!1});if(n=i.path,r=i.node,Oe.isMountpoint(r))throw new Oe.ErrnoError(10);if(!Oe.isDir(r.mode))throw new Oe.ErrnoError(54)}var s={type:e,opts:t,mountpoint:n,mounts:[]},u=e.mount(s);return u.mount=s,s.root=u,o?Oe.root=u:r&&(r.mounted=s,r.mount&&r.mount.mounts.push(s)),u},unmount(e){var t=Oe.lookupPath(e,{follow_mount:!1});if(!Oe.isMountpoint(t.node))throw new Oe.ErrnoError(28);var n=t.node,r=n.mounted,o=Oe.getMounts(r);Object.keys(Oe.nameTable).forEach(e=>{for(var t=Oe.nameTable[e];t;){var n=t.name_next;o.includes(t.mount)&&Oe.destroyNode(t),t=n}}),n.mounted=null;var a=n.mount.mounts.indexOf(r);C(-1!==a),n.mount.mounts.splice(a,1)},lookup:(e,t)=>e.node_ops.lookup(e,t),mknod(e,t,n){var r=Oe.lookupPath(e,{parent:!0}).node,o=ge.basename(e);if(!o||"."===o||".."===o)throw new Oe.ErrnoError(28);var a=Oe.mayCreate(r,o);if(a)throw new Oe.ErrnoError(a);if(!r.node_ops.mknod)throw new Oe.ErrnoError(63);return r.node_ops.mknod(r,o,t,n)},create:(e,t)=>(t=void 0!==t?t:438,t&=4095,t|=32768,Oe.mknod(e,t,0)),mkdir:(e,t)=>(t=void 0!==t?t:511,t&=1023,t|=16384,Oe.mknod(e,t,0)),mkdirTree(e,t){for(var n=e.split("/"),r="",o=0;o(void 0===n&&(n=t,t=438),t|=8192,Oe.mknod(e,t,n)),symlink(e,t){if(!De.resolve(e))throw new Oe.ErrnoError(44);var n=Oe.lookupPath(t,{parent:!0}).node;if(!n)throw new Oe.ErrnoError(44);var r=ge.basename(t),o=Oe.mayCreate(n,r);if(o)throw new Oe.ErrnoError(o);if(!n.node_ops.symlink)throw new Oe.ErrnoError(63);return n.node_ops.symlink(n,r,e)},rename(e,t){var n,r,o=ge.dirname(e),a=ge.dirname(t),i=ge.basename(e),s=ge.basename(t);if(n=Oe.lookupPath(e,{parent:!0}).node,r=Oe.lookupPath(t,{parent:!0}).node,!n||!r)throw new Oe.ErrnoError(44);if(n.mount!==r.mount)throw new Oe.ErrnoError(75);var u,m=Oe.lookupNode(n,i),F=De.relative(e,a);if("."!==F.charAt(0))throw new Oe.ErrnoError(28);if("."!==(F=De.relative(t,o)).charAt(0))throw new Oe.ErrnoError(55);try{u=Oe.lookupNode(r,s)}catch(e){}if(m!==u){var l=Oe.isDir(m.mode),d=Oe.mayDelete(n,i,l);if(d)throw new Oe.ErrnoError(d);if(d=u?Oe.mayDelete(r,s,l):Oe.mayCreate(r,s))throw new Oe.ErrnoError(d);if(!n.node_ops.rename)throw new Oe.ErrnoError(63);if(Oe.isMountpoint(m)||u&&Oe.isMountpoint(u))throw new Oe.ErrnoError(10);if(r!==n&&(d=Oe.nodePermissions(n,"w")))throw new Oe.ErrnoError(d);Oe.hashRemoveNode(m);try{n.node_ops.rename(m,r,s),m.parent=r}catch(e){throw e}finally{Oe.hashAddNode(m)}}},rmdir(e){var t=Oe.lookupPath(e,{parent:!0}).node,n=ge.basename(e),r=Oe.lookupNode(t,n),o=Oe.mayDelete(t,n,!0);if(o)throw new Oe.ErrnoError(o);if(!t.node_ops.rmdir)throw new Oe.ErrnoError(63);if(Oe.isMountpoint(r))throw new Oe.ErrnoError(10);t.node_ops.rmdir(t,n),Oe.destroyNode(r)},readdir(e){var t=Oe.lookupPath(e,{follow:!0}).node;if(!t.node_ops.readdir)throw new Oe.ErrnoError(54);return t.node_ops.readdir(t)},unlink(e){var t=Oe.lookupPath(e,{parent:!0}).node;if(!t)throw new Oe.ErrnoError(44);var n=ge.basename(e),r=Oe.lookupNode(t,n),o=Oe.mayDelete(t,n,!1);if(o)throw new Oe.ErrnoError(o);if(!t.node_ops.unlink)throw new Oe.ErrnoError(63);if(Oe.isMountpoint(r))throw new Oe.ErrnoError(10);t.node_ops.unlink(t,n),Oe.destroyNode(r)},readlink(e){var t=Oe.lookupPath(e).node;if(!t)throw new Oe.ErrnoError(44);if(!t.node_ops.readlink)throw new Oe.ErrnoError(28);return De.resolve(Oe.getPath(t.parent),t.node_ops.readlink(t))},stat(e,t){var n=Oe.lookupPath(e,{follow:!t}).node;if(!n)throw new Oe.ErrnoError(44);if(!n.node_ops.getattr)throw new Oe.ErrnoError(63);return n.node_ops.getattr(n)},lstat:e=>Oe.stat(e,!0),chmod(e,t,n){var r;if(!(r="string"==typeof e?Oe.lookupPath(e,{follow:!n}).node:e).node_ops.setattr)throw new Oe.ErrnoError(63);r.node_ops.setattr(r,{mode:4095&t|-4096&r.mode,timestamp:Date.now()})},lchmod(e,t){Oe.chmod(e,t,!0)},fchmod(e,t){var n=Oe.getStreamChecked(e);Oe.chmod(n.node,t)},chown(e,t,n,r){var o;if(!(o="string"==typeof e?Oe.lookupPath(e,{follow:!r}).node:e).node_ops.setattr)throw new Oe.ErrnoError(63);o.node_ops.setattr(o,{timestamp:Date.now()})},lchown(e,t,n){Oe.chown(e,t,n,!0)},fchown(e,t,n){var r=Oe.getStreamChecked(e);Oe.chown(r.node,t,n)},truncate(e,t){if(t<0)throw new Oe.ErrnoError(28);var n;if(!(n="string"==typeof e?Oe.lookupPath(e,{follow:!0}).node:e).node_ops.setattr)throw new Oe.ErrnoError(63);if(Oe.isDir(n.mode))throw new Oe.ErrnoError(31);if(!Oe.isFile(n.mode))throw new Oe.ErrnoError(28);var r=Oe.nodePermissions(n,"w");if(r)throw new Oe.ErrnoError(r);n.node_ops.setattr(n,{size:t,timestamp:Date.now()})},ftruncate(e,t){var n=Oe.getStreamChecked(e);if(!(2097155&n.flags))throw new Oe.ErrnoError(28);Oe.truncate(n.node,t)},utime(e,t,n){var r=Oe.lookupPath(e,{follow:!0}).node;r.node_ops.setattr(r,{timestamp:Math.max(t,n)})},open(e,t,n){if(""===e)throw new Oe.ErrnoError(44);var r;if(n=64&(t="string"==typeof t?(e=>{var t={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[e];if(void 0===t)throw new Error(`Unknown file open mode: ${e}`);return t})(t):t)?4095&(n=void 0===n?438:n)|32768:0,"object"==typeof e)r=e;else{e=ge.normalize(e);try{r=Oe.lookupPath(e,{follow:!(131072&t)}).node}catch(e){}}var a=!1;if(64&t)if(r){if(128&t)throw new Oe.ErrnoError(20)}else r=Oe.mknod(e,n,0),a=!0;if(!r)throw new Oe.ErrnoError(44);if(Oe.isChrdev(r.mode)&&(t&=-513),65536&t&&!Oe.isDir(r.mode))throw new Oe.ErrnoError(54);if(!a){var i=Oe.mayOpen(r,t);if(i)throw new Oe.ErrnoError(i)}512&t&&!a&&Oe.truncate(r,0),t&=-131713;var s=Oe.createStream({node:r,path:Oe.getPath(r),flags:t,seekable:!0,position:0,stream_ops:r.stream_ops,ungotten:[],error:!1});return s.stream_ops.open&&s.stream_ops.open(s),!o.logReadFiles||1&t||e in Oe.readFiles||(Oe.readFiles[e]=1),s},close(e){if(Oe.isClosed(e))throw new Oe.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(e){throw e}finally{Oe.closeStream(e.fd)}e.fd=null},isClosed:e=>null===e.fd,llseek(e,t,n){if(Oe.isClosed(e))throw new Oe.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new Oe.ErrnoError(70);if(0!=n&&1!=n&&2!=n)throw new Oe.ErrnoError(28);return e.position=e.stream_ops.llseek(e,t,n),e.ungotten=[],e.position},read(e,t,n,r,o){if(C(n>=0),r<0||o<0)throw new Oe.ErrnoError(28);if(Oe.isClosed(e))throw new Oe.ErrnoError(8);if(1==(2097155&e.flags))throw new Oe.ErrnoError(8);if(Oe.isDir(e.node.mode))throw new Oe.ErrnoError(31);if(!e.stream_ops.read)throw new Oe.ErrnoError(28);var a=void 0!==o;if(a){if(!e.seekable)throw new Oe.ErrnoError(70)}else o=e.position;var i=e.stream_ops.read(e,t,n,r,o);return a||(e.position+=i),i},write(e,t,n,r,o,a){if(C(n>=0),r<0||o<0)throw new Oe.ErrnoError(28);if(Oe.isClosed(e))throw new Oe.ErrnoError(8);if(!(2097155&e.flags))throw new Oe.ErrnoError(8);if(Oe.isDir(e.node.mode))throw new Oe.ErrnoError(31);if(!e.stream_ops.write)throw new Oe.ErrnoError(28);e.seekable&&1024&e.flags&&Oe.llseek(e,0,2);var i=void 0!==o;if(i){if(!e.seekable)throw new Oe.ErrnoError(70)}else o=e.position;var s=e.stream_ops.write(e,t,n,r,o,a);return i||(e.position+=s),s},allocate(e,t,n){if(Oe.isClosed(e))throw new Oe.ErrnoError(8);if(t<0||n<=0)throw new Oe.ErrnoError(28);if(!(2097155&e.flags))throw new Oe.ErrnoError(8);if(!Oe.isFile(e.node.mode)&&!Oe.isDir(e.node.mode))throw new Oe.ErrnoError(43);if(!e.stream_ops.allocate)throw new Oe.ErrnoError(138);e.stream_ops.allocate(e,t,n)},mmap(e,t,n,r,o){if(2&r&&!(2&o)&&2!=(2097155&e.flags))throw new Oe.ErrnoError(2);if(1==(2097155&e.flags))throw new Oe.ErrnoError(2);if(!e.stream_ops.mmap)throw new Oe.ErrnoError(43);if(!t)throw new Oe.ErrnoError(28);return e.stream_ops.mmap(e,t,n,r,o)},msync:(e,t,n,r,o)=>(C(n>=0),e.stream_ops.msync?e.stream_ops.msync(e,t,n,r,o):0),ioctl(e,t,n){if(!e.stream_ops.ioctl)throw new Oe.ErrnoError(59);return e.stream_ops.ioctl(e,t,n)},readFile(e,t={}){if(t.flags=t.flags||0,t.encoding=t.encoding||"binary","utf8"!==t.encoding&&"binary"!==t.encoding)throw new Error(`Invalid encoding type "${t.encoding}"`);var n,r=Oe.open(e,t.flags),o=Oe.stat(e).size,a=new Uint8Array(o);return Oe.read(r,a,0,o,0),"utf8"===t.encoding?n=de(a):"binary"===t.encoding&&(n=a),Oe.close(r),n},writeFile(e,t,n={}){n.flags=n.flags||577;var r=Oe.open(e,n.flags,n.mode);if("string"==typeof t){var o=new Uint8Array(pe(t)+1),a=fe(t,o,0,o.length);Oe.write(r,o,0,a,void 0,n.canOwn)}else{if(!ArrayBuffer.isView(t))throw new Error("Unsupported data type");Oe.write(r,t,0,t.byteLength,void 0,n.canOwn)}Oe.close(r)},cwd:()=>Oe.currentPath,chdir(e){var t=Oe.lookupPath(e,{follow:!0});if(null===t.node)throw new Oe.ErrnoError(44);if(!Oe.isDir(t.node.mode))throw new Oe.ErrnoError(54);var n=Oe.nodePermissions(t.node,"x");if(n)throw new Oe.ErrnoError(n);Oe.currentPath=t.path},createDefaultDirectories(){Oe.mkdir("/tmp"),Oe.mkdir("/home"),Oe.mkdir("/home/web_user")},createDefaultDevices(){Oe.mkdir("/dev"),Oe.registerDevice(Oe.makedev(1,3),{read:()=>0,write:(e,t,n,r,o)=>r}),Oe.mkdev("/dev/null",Oe.makedev(1,3)),Me.register(Oe.makedev(5,0),Me.default_tty_ops),Me.register(Oe.makedev(6,0),Me.default_tty1_ops),Oe.mkdev("/dev/tty",Oe.makedev(5,0)),Oe.mkdev("/dev/tty1",Oe.makedev(6,0));var e=new Uint8Array(1024),t=0,n=()=>(0===t&&(t=he(e).byteLength),e[--t]);Oe.createDevice("/dev","random",n),Oe.createDevice("/dev","urandom",n),Oe.mkdir("/dev/shm"),Oe.mkdir("/dev/shm/tmp")},createSpecialDirectories(){Oe.mkdir("/proc");var e=Oe.mkdir("/proc/self");Oe.mkdir("/proc/self/fd"),Oe.mount({mount(){var t=Oe.createNode(e,"fd",16895,73);return t.node_ops={lookup(e,t){var n=+t,r=Oe.getStreamChecked(n),o={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>r.path}};return o.parent=o,o}},t}},{},"/proc/self/fd")},createStandardStreams(e,t,n){e?Oe.createDevice("/dev","stdin",e):Oe.symlink("/dev/tty","/dev/stdin"),t?Oe.createDevice("/dev","stdout",null,t):Oe.symlink("/dev/tty","/dev/stdout"),n?Oe.createDevice("/dev","stderr",null,n):Oe.symlink("/dev/tty1","/dev/stderr");var r=Oe.open("/dev/stdin",0),o=Oe.open("/dev/stdout",1),a=Oe.open("/dev/stderr",1);C(0===r.fd,`invalid handle for stdin (${r.fd})`),C(1===o.fd,`invalid handle for stdout (${o.fd})`),C(2===a.fd,`invalid handle for stderr (${a.fd})`)},staticInit(){[44].forEach(e=>{Oe.genericErrors[e]=new Oe.ErrnoError(e),Oe.genericErrors[e].stack=""}),Oe.nameTable=new Array(4096),Oe.mount(Ce,{},"/"),Oe.createDefaultDirectories(),Oe.createDefaultDevices(),Oe.createSpecialDirectories(),Oe.filesystems={MEMFS:Ce}},init(e,t,n){C(!Oe.initialized,"FS.init was previously called. If you want to initialize later with custom parameters, remove any earlier calls (note that one is automatically added to the generated code)"),Oe.initialized=!0,e??=o.stdin,t??=o.stdout,n??=o.stderr,Oe.createStandardStreams(e,t,n)},quit(){Oe.initialized=!1,tt(0);for(var e=0;ethis.length-1||e<0)){var t=e%this.chunkSize,n=e/this.chunkSize|0;return this.getter(n)[t]}}setDataGetter(e){this.getter=e}cacheLength(){var e=new XMLHttpRequest;if(e.open("HEAD",n,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+n+". Status: "+e.status);var t,r=Number(e.getResponseHeader("Content-length")),o=(t=e.getResponseHeader("Accept-Ranges"))&&"bytes"===t,a=(t=e.getResponseHeader("Content-Encoding"))&&"gzip"===t,i=1048576;o||(i=r);var s=this;s.setDataGetter(e=>{var t=e*i,o=(e+1)*i-1;if(o=Math.min(o,r-1),void 0===s.chunks[e]&&(s.chunks[e]=((e,t)=>{if(e>t)throw new Error("invalid range ("+e+", "+t+") or no bytes requested!");if(t>r-1)throw new Error("only "+r+" bytes available! programmer error!");var o=new XMLHttpRequest;if(o.open("GET",n,!1),r!==i&&o.setRequestHeader("Range","bytes="+e+"-"+t),o.responseType="arraybuffer",o.overrideMimeType&&o.overrideMimeType("text/plain; charset=x-user-defined"),o.send(null),!(o.status>=200&&o.status<300||304===o.status))throw new Error("Couldn't load "+n+". Status: "+o.status);return void 0!==o.response?new Uint8Array(o.response||[]):Ae(o.responseText||"")})(t,o)),void 0===s.chunks[e])throw new Error("doXHR failed!");return s.chunks[e]}),!a&&r||(i=r=1,r=this.getter(0).length,i=r,c("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=r,this._chunkSize=i,this.lengthKnown=!0}get length(){return this.lengthKnown||this.cacheLength(),this._length}get chunkSize(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}if("undefined"!=typeof XMLHttpRequest){if(!s)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var i={isDevice:!1,contents:new a}}else i={isDevice:!1,url:n};var u=Oe.createFile(e,t,i,r,o);i.contents?u.contents=i.contents:i.url&&(u.contents=null,u.url=i.url),Object.defineProperties(u,{usedBytes:{get:function(){return this.contents.length}}});var m={};function F(e,t,n,r,o){var a=e.node.contents;if(o>=a.length)return 0;var i=Math.min(a.length-o,r);if(C(i>=0),a.slice)for(var s=0;s{var t=u.stream_ops[e];m[e]=(...e)=>(Oe.forceLoadFile(u),t(...e))}),m.read=(e,t,n,r,o)=>(Oe.forceLoadFile(u),F(e,t,n,r,o)),m.mmap=(e,t,n,r,o)=>{Oe.forceLoadFile(u);var a=Se(t);if(!a)throw new Oe.ErrnoError(48);return F(e,b,a,t,n),{ptr:a,allocated:!0}},u.stream_ops=m,u},absolutePath(){W("FS.absolutePath has been removed; use PATH_FS.resolve instead")},createFolder(){W("FS.createFolder has been removed; use FS.mkdir instead")},createLink(){W("FS.createLink has been removed; use FS.symlink instead")},joinPath(){W("FS.joinPath has been removed; use PATH.join instead")},mmapAlloc(){W("FS.mmapAlloc has been replaced by the top level function mmapAlloc")},standardizePath(){W("FS.standardizePath has been removed; use PATH.normalize instead")}},Re={DEFAULT_POLLMASK:5,calculateAt(e,t,n){if(ge.isAbs(t))return t;var r;if(r=-100===e?Oe.cwd():Re.getStreamFromFD(e).path,0==t.length){if(!n)throw new Oe.ErrnoError(44);return r}return ge.join2(r,t)},doStat(e,t,n){var r=e(t);E[n>>2]=r.dev,E[n+4>>2]=r.mode,y[n+8>>2]=r.nlink,E[n+12>>2]=r.uid,E[n+16>>2]=r.gid,E[n+20>>2]=r.rdev,Y=[r.size>>>0,(X=r.size,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],E[n+24>>2]=Y[0],E[n+28>>2]=Y[1],E[n+32>>2]=4096,E[n+36>>2]=r.blocks;var o=r.atime.getTime(),a=r.mtime.getTime(),i=r.ctime.getTime();return Y=[Math.floor(o/1e3)>>>0,(X=Math.floor(o/1e3),+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],E[n+40>>2]=Y[0],E[n+44>>2]=Y[1],y[n+48>>2]=o%1e3*1e3*1e3,Y=[Math.floor(a/1e3)>>>0,(X=Math.floor(a/1e3),+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],E[n+56>>2]=Y[0],E[n+60>>2]=Y[1],y[n+64>>2]=a%1e3*1e3*1e3,Y=[Math.floor(i/1e3)>>>0,(X=Math.floor(i/1e3),+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],E[n+72>>2]=Y[0],E[n+76>>2]=Y[1],y[n+80>>2]=i%1e3*1e3*1e3,Y=[r.ino>>>0,(X=r.ino,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],E[n+88>>2]=Y[0],E[n+92>>2]=Y[1],0},doMsync(e,t,n,r,o){if(!Oe.isFile(t.node.mode))throw new Oe.ErrnoError(43);if(2&r)return 0;var a=p.slice(e,e+n);Oe.msync(t,a,o,n,r)},getStreamFromFD:e=>Oe.getStreamChecked(e),varargs:void 0,getStr:e=>Pe(e)},ke=(e,t)=>(C(e==e>>>0||e==(0|e)),C(t===(0|t)),t+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*t:NaN),we=(e,t,n)=>(C("number"==typeof n,"stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!"),fe(e,p,t,n)),Ie=[0,31,60,91,121,152,182,213,244,274,305,335],Be=[0,31,59,90,120,151,181,212,243,273,304,334],je=e=>{var t=h.buffer,n=(e-t.byteLength+65535)/65536|0;try{return h.grow(n),x(),1}catch(n){g(`growMemory: Attempted to grow heap from ${t.byteLength} bytes to ${e} bytes, but got error: ${n}`)}},Le={},Ne=()=>{if(!Ne.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:d||"./this.program"};for(var t in Le)void 0===Le[t]?delete e[t]:e[t]=Le[t];var n=[];for(var t in e)n.push(`${t}=${e[t]}`);Ne.strings=n}return Ne.strings},Ve=[],Ue=e=>{var t=Ve[e];return t||(e>=Ve.length&&(Ve.length=e+1),Ve[e]=t=Ee.get(e)),C(Ee.get(e)==t,"JavaScript-side Wasm function table mirror is out of date!"),t},ze="undefined"!=typeof TextDecoder?new TextDecoder("utf-16le"):void 0,$e=(e,t)=>{C(e<16384),e<128?t.push(e):t.push(e%128|128,e>>7)},We=(e,t)=>{if(C(!t.includes("j"),"i64 not permitted in function signatures when WASM_BIGINT is disabled"),"function"==typeof WebAssembly.Function)return new WebAssembly.Function((e=>{C(!e.includes("j"),"i64 not permitted in function signatures when WASM_BIGINT is disabled");for(var t={i:"i32",j:"i64",f:"f32",d:"f64",e:"externref",p:"i32"},n={parameters:[],results:"v"==e[0]?[]:[t[e[0]]]},r=1;r{var n=e.slice(0,1),r=e.slice(1),o={i:127,p:127,j:126,f:125,d:124,e:111};t.push(96),$e(r.length,t);for(var a=0;a(ye||(ye=new WeakMap,((e,t)=>{if(ye)for(var n=e;n{Ee.set(e,t),Ve[e]=Ee.get(e)},Ke=e=>ut(e),Je=(e,t,n,r,a)=>{var i={string:e=>{var t=0;return null!=e&&0!==e&&(t=(e=>{var t=pe(e)+1,n=Ke(t);return we(e,n,t),n})(e)),t},array:e=>{var t,n,r=Ke(e.length);return n=r,C((t=e).length>=0,"writeArrayToMemory array must have a length (should be an array or typed array)"),b.set(t,n),r}},s=(e=>{var t=o["_"+e];return C(t,"Cannot call unknown function "+e+", make sure it is exported"),t})(e),u=[],m=0;if(C("array"!==t,'Return type should not be "array".'),r)for(var F=0;F{var l=t?De.resolve(ge.join2(e,t)):e,d=U(`cp ${l}`);function P(n){function u(n){F?.(),s||((e,t,n,r,o,a)=>{Oe.createDataFile(e,t,n,r,o,a)})(e,t,n,r,o,m),a?.(),$(d)}((e,t,n,r)=>{"undefined"!=typeof Browser&&Browser.init();var o=!1;return xe.forEach(a=>{o||a.canHandle(t)&&(a.handle(e,t,n,r),o=!0)}),o})(n,l,u,()=>{i?.(),$(d)})||u(n)}z(d),"string"==typeof n?((e,t,n)=>{var r=U(`al ${e}`);u(e).then(n=>{C(n,`Loading data file "${e}" failed (no arrayBuffer).`),t(new Uint8Array(n)),r&&$(r)},t=>{if(!n)throw`Loading data file "${e}" failed.`;n()}),r&&z(r)})(n,P,i):P(n)},Oe.staticInit();var qe={__assert_fail:(e,t,n,r)=>{W(`Assertion failed: ${Pe(e)}, at: `+[t?Pe(t):"unknown filename",n,r?Pe(r):"unknown function"])},__syscall_fcntl64:function(e,t,n){Re.varargs=n;try{var r=Re.getStreamFromFD(e);switch(t){case 0:if((o=_e())<0)return-28;for(;Oe.streams[o];)o++;return Oe.dupStream(r,o).fd;case 1:case 2:case 13:case 14:return 0;case 3:return r.flags;case 4:var o=_e();return r.flags|=o,0;case 12:return o=ce(),f[o+0>>1]=2,0}return-28}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_fstat64:function(e,t){try{var n=Re.getStreamFromFD(e);return Re.doStat(Oe.stat,n.path,t)}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_ftruncate64:function(e,t,n){var r=ke(t,n);try{return isNaN(r)?61:(Oe.ftruncate(e,r),0)}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_getdents64:function(e,t,n){try{var r=Re.getStreamFromFD(e);r.getdents||=Oe.readdir(r.path);for(var o=280,a=0,i=Oe.llseek(r,0,1),s=Math.floor(i/o);s>>0,(X=u,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],E[t+a>>2]=Y[0],E[t+a+4>>2]=Y[1],Y=[(s+1)*o>>>0,(X=(s+1)*o,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],E[t+a+8>>2]=Y[0],E[t+a+12>>2]=Y[1],f[t+a+16>>1]=280,b[t+a+18]=m,we(F,t+a+19,256),a+=o,s+=1}return Oe.llseek(r,s*o,0),a}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_ioctl:function(e,t,n){Re.varargs=n;try{var r=Re.getStreamFromFD(e);switch(t){case 21509:case 21510:case 21511:case 21512:case 21524:case 21515:return r.tty?0:-59;case 21505:if(!r.tty)return-59;if(r.tty.ops.ioctl_tcgets){var o=r.tty.ops.ioctl_tcgets(r),a=ce();E[a>>2]=o.c_iflag||0,E[a+4>>2]=o.c_oflag||0,E[a+8>>2]=o.c_cflag||0,E[a+12>>2]=o.c_lflag||0;for(var i=0;i<32;i++)b[a+i+17]=o.c_cc[i]||0;return 0}return 0;case 21506:case 21507:case 21508:if(!r.tty)return-59;if(r.tty.ops.ioctl_tcsets){a=ce();var s=E[a>>2],u=E[a+4>>2],m=E[a+8>>2],F=E[a+12>>2],l=[];for(i=0;i<32;i++)l.push(b[a+i+17]);return r.tty.ops.ioctl_tcsets(r.tty,t,{c_iflag:s,c_oflag:u,c_cflag:m,c_lflag:F,c_cc:l})}return 0;case 21519:return r.tty?(a=ce(),E[a>>2]=0,0):-59;case 21520:return r.tty?-28:-59;case 21531:return a=ce(),Oe.ioctl(r,t,a);case 21523:if(!r.tty)return-59;if(r.tty.ops.ioctl_tiocgwinsz){var d=r.tty.ops.ioctl_tiocgwinsz(r.tty);a=ce(),f[a>>1]=d[0],f[a+2>>1]=d[1]}return 0;default:return-28}}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_lstat64:function(e,t){try{return e=Re.getStr(e),Re.doStat(Oe.lstat,e,t)}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_newfstatat:function(e,t,n,r){try{t=Re.getStr(t);var o=256&r,a=4096&r;return C(!(r&=-6401),`unknown flags in __syscall_newfstatat: ${r}`),t=Re.calculateAt(e,t,a),Re.doStat(o?Oe.lstat:Oe.stat,t,n)}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_openat:function(e,t,n,r){Re.varargs=r;try{t=Re.getStr(t),t=Re.calculateAt(e,t);var o=r?_e():0;return Oe.open(t,n,o).fd}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_rmdir:function(e){try{return e=Re.getStr(e),Oe.rmdir(e),0}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_stat64:function(e,t){try{return e=Re.getStr(e),Re.doStat(Oe.stat,e,t)}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_unlinkat:function(e,t,n){try{return t=Re.getStr(t),t=Re.calculateAt(e,t),0===n?Oe.unlink(t):512===n?Oe.rmdir(t):W("Invalid flags passed to unlinkat"),0}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return-e.errno}},_abort_js:()=>{W("native code called abort()")},_emscripten_memcpy_js:(e,t,n)=>p.copyWithin(e,t,t+n),_emscripten_throw_longjmp:()=>{throw 1/0},_gmtime_js:function(e,t,n){var r=ke(e,t),o=new Date(1e3*r);E[n>>2]=o.getUTCSeconds(),E[n+4>>2]=o.getUTCMinutes(),E[n+8>>2]=o.getUTCHours(),E[n+12>>2]=o.getUTCDate(),E[n+16>>2]=o.getUTCMonth(),E[n+20>>2]=o.getUTCFullYear()-1900,E[n+24>>2]=o.getUTCDay();var a=Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0),i=(o.getTime()-a)/864e5|0;E[n+28>>2]=i},_localtime_js:function(e,t,n){var r=ke(e,t),o=new Date(1e3*r);E[n>>2]=o.getSeconds(),E[n+4>>2]=o.getMinutes(),E[n+8>>2]=o.getHours(),E[n+12>>2]=o.getDate(),E[n+16>>2]=o.getMonth(),E[n+20>>2]=o.getFullYear()-1900,E[n+24>>2]=o.getDay();var a=0|(e=>{var t;return((t=e.getFullYear())%4!=0||t%100==0&&t%400!=0?Be:Ie)[e.getMonth()]+e.getDate()-1})(o);E[n+28>>2]=a,E[n+36>>2]=-60*o.getTimezoneOffset();var i=new Date(o.getFullYear(),0,1),s=new Date(o.getFullYear(),6,1).getTimezoneOffset(),u=i.getTimezoneOffset(),m=0|(s!=u&&o.getTimezoneOffset()==Math.min(u,s));E[n+32>>2]=m},_tzset_js:(e,t,n,r)=>{var o=(new Date).getFullYear(),a=new Date(o,0,1),i=new Date(o,6,1),s=a.getTimezoneOffset(),u=i.getTimezoneOffset(),m=Math.max(s,u);y[e>>2]=60*m,E[t>>2]=Number(s!=u);var F=e=>{var t=e>=0?"-":"+",n=Math.abs(e);return`UTC${t}${String(Math.floor(n/60)).padStart(2,"0")}${String(n%60).padStart(2,"0")}`},l=F(s),d=F(u);C(l),C(d),C(pe(l)<=16,`timezone name truncated to fit in TZNAME_MAX (${l})`),C(pe(d)<=16,`timezone name truncated to fit in TZNAME_MAX (${d})`),uDate.now(),emscripten_resize_heap:e=>{var t=p.length;C((e>>>=0)>t);var n=2147483648;if(e>n)return g(`Cannot enlarge memory, requested ${e} bytes, but the limit is 2147483648 bytes!`),!1;for(var r=1;r<=4;r*=2){var o=t*(1+.2/r);o=Math.min(o,e+100663296);var a=Math.min(n,Ge(Math.max(e,o),65536));if(je(a))return!0}return g(`Failed to grow the heap from ${t} bytes to ${a} bytes, not enough memory!`),!1},environ_get:(e,t)=>{var n=0;return Ne().forEach((r,o)=>{var a=t+n;y[e+4*o>>2]=a,((e,t)=>{for(var n=0;n{var n=Ne();y[e>>2]=n.length;var r=0;return n.forEach(e=>r+=e.length+1),y[t>>2]=r,0},fd_close:function(e){try{var t=Re.getStreamFromFD(e);return Oe.close(t),0}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return e.errno}},fd_read:function(e,t,n,r){try{var o=((e,t,n,r)=>{for(var o=0,a=0;a>2],s=y[t+4>>2];t+=8;var u=Oe.read(e,b,i,s,r);if(u<0)return-1;if(o+=u,u>2]=o,0}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return e.errno}},fd_seek:function(e,t,n,r,o){var a=ke(t,n);try{if(isNaN(a))return 61;var i=Re.getStreamFromFD(e);return Oe.llseek(i,a,r),Y=[i.position>>>0,(X=i.position,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],E[o>>2]=Y[0],E[o+4>>2]=Y[1],i.getdents&&0===a&&0===r&&(i.getdents=null),0}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return e.errno}},fd_sync:function(e){try{var t=Re.getStreamFromFD(e);return t.stream_ops?.fsync?t.stream_ops.fsync(t):0}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return e.errno}},fd_write:function(e,t,n,r){try{var o=((e,t,n,r)=>{for(var o=0,a=0;a>2],s=y[t+4>>2];t+=8;var u=Oe.write(e,b,i,s,r);if(u<0)return-1;if(o+=u,u>2]=o,0}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return e.errno}},invoke_ii:function(e,t){var n=me();try{return Ue(e)(t)}catch(e){if(ue(n),e!==e+0)throw e;ot(1,0)}},invoke_iii:function(e,t,n){var r=me();try{return Ue(e)(t,n)}catch(e){if(ue(r),e!==e+0)throw e;ot(1,0)}},invoke_iiii:function(e,t,n,r){var o=me();try{return Ue(e)(t,n,r)}catch(e){if(ue(o),e!==e+0)throw e;ot(1,0)}},invoke_iiiii:function(e,t,n,r,o){var a=me();try{return Ue(e)(t,n,r,o)}catch(e){if(ue(a),e!==e+0)throw e;ot(1,0)}},invoke_v:function(e){var t=me();try{Ue(e)()}catch(e){if(ue(t),e!==e+0)throw e;ot(1,0)}},invoke_vii:function(e,t,n){var r=me();try{Ue(e)(t,n)}catch(e){if(ue(r),e!==e+0)throw e;ot(1,0)}},invoke_viii:function(e,t,n,r){var o=me();try{Ue(e)(t,n,r)}catch(e){if(ue(o),e!==e+0)throw e;ot(1,0)}},invoke_viiii:function(e,t,n,r,o){var a=me();try{Ue(e)(t,n,r,o)}catch(e){if(ue(a),e!==e+0)throw e;ot(1,0)}},invoke_viiiiiiiii:function(e,t,n,r,o,a,i,s,u,m){var F=me();try{Ue(e)(t,n,r,o,a,i,s,u,m)}catch(e){if(ue(F),e!==e+0)throw e;ot(1,0)}}},Qe=function(){var e={env:qe,wasi_snapshot_preview1:qe};function t(e,t){var n;return Qe=e.exports,o.wasmExports=Qe,C(h=Qe.memory,"memory not found in wasm exports"),x(),C(Ee=Qe.__indirect_function_table,"table not found in wasm exports"),n=Qe.__wasm_call_ctors,O.unshift(n),$("wasm-instantiate"),Qe}z("wasm-instantiate");var n,a,i,s,u=o;if(o.instantiateWasm)try{return o.instantiateWasm(e,t)}catch(e){g(`Module.instantiateWasm callback failed with error: ${e}`),r(e)}return H??=Q(),(n=D,a=H,i=e,s=function(e){C(o===u,"the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?"),u=null,t(e.instance)},n||"function"!=typeof WebAssembly.instantiateStreaming||K(a)||"function"!=typeof fetch?ee(a,i,s):fetch(a,{credentials:"same-origin"}).then(e=>WebAssembly.instantiateStreaming(e,i).then(s,function(e){return g(`wasm streaming compile failed: ${e}`),g("falling back to ArrayBuffer instantiation"),ee(a,i,s)}))).catch(r),{}}();o._PDFiumExt_Init=q("PDFiumExt_Init",0),o._FPDF_InitLibraryWithConfig=q("FPDF_InitLibraryWithConfig",1),o._PDFiumExt_OpenFileWriter=q("PDFiumExt_OpenFileWriter",0),o._PDFiumExt_GetFileWriterSize=q("PDFiumExt_GetFileWriterSize",1),o._PDFiumExt_GetFileWriterData=q("PDFiumExt_GetFileWriterData",3),o._PDFiumExt_CloseFileWriter=q("PDFiumExt_CloseFileWriter",1),o._PDFiumExt_SaveAsCopy=q("PDFiumExt_SaveAsCopy",2),o._FPDF_SaveAsCopy=q("FPDF_SaveAsCopy",3),o._PDFiumExt_OpenFormFillInfo=q("PDFiumExt_OpenFormFillInfo",0),o._PDFiumExt_CloseFormFillInfo=q("PDFiumExt_CloseFormFillInfo",1),o._PDFiumExt_InitFormFillEnvironment=q("PDFiumExt_InitFormFillEnvironment",2),o._FPDFDOC_InitFormFillEnvironment=q("FPDFDOC_InitFormFillEnvironment",2),o._PDFiumExt_ExitFormFillEnvironment=q("PDFiumExt_ExitFormFillEnvironment",1),o._FPDFDOC_ExitFormFillEnvironment=q("FPDFDOC_ExitFormFillEnvironment",1),o._EPDFNamedDest_SetDest=q("EPDFNamedDest_SetDest",3),o._EPDFNamedDest_Remove=q("EPDFNamedDest_Remove",2),o._EPDFDest_CreateView=q("EPDFDest_CreateView",4),o._EPDFDest_CreateXYZ=q("EPDFDest_CreateXYZ",7),o._EPDFDest_CreateRemoteView=q("EPDFDest_CreateRemoteView",5),o._EPDFDest_CreateRemoteXYZ=q("EPDFDest_CreateRemoteXYZ",8),o._EPDFAction_CreateGoTo=q("EPDFAction_CreateGoTo",2),o._EPDFAction_CreateGoToNamed=q("EPDFAction_CreateGoToNamed",2),o._EPDFAction_CreateLaunch=q("EPDFAction_CreateLaunch",2),o._EPDFAction_CreateRemoteGoToByName=q("EPDFAction_CreateRemoteGoToByName",3),o._EPDFAction_CreateRemoteGoToDest=q("EPDFAction_CreateRemoteGoToDest",3),o._EPDFAction_CreateURI=q("EPDFAction_CreateURI",2),o._EPDFBookmark_Create=q("EPDFBookmark_Create",2),o._EPDFBookmark_Delete=q("EPDFBookmark_Delete",2),o._EPDFBookmark_AppendChild=q("EPDFBookmark_AppendChild",3),o._EPDFBookmark_InsertAfter=q("EPDFBookmark_InsertAfter",4),o._EPDFBookmark_Clear=q("EPDFBookmark_Clear",1),o._EPDFBookmark_SetTitle=q("EPDFBookmark_SetTitle",2),o._EPDFBookmark_SetDest=q("EPDFBookmark_SetDest",3),o._EPDFBookmark_SetAction=q("EPDFBookmark_SetAction",3),o._EPDFBookmark_ClearTarget=q("EPDFBookmark_ClearTarget",1),o._EPDF_PNG_EncodeRGBA=q("EPDF_PNG_EncodeRGBA",6),o._FPDFAnnot_IsSupportedSubtype=q("FPDFAnnot_IsSupportedSubtype",1),o._FPDFPage_CreateAnnot=q("FPDFPage_CreateAnnot",2),o._FPDFPage_GetAnnotCount=q("FPDFPage_GetAnnotCount",1),o._FPDFPage_GetAnnot=q("FPDFPage_GetAnnot",2),o._FPDFPage_GetAnnotIndex=q("FPDFPage_GetAnnotIndex",2),o._FPDFPage_CloseAnnot=q("FPDFPage_CloseAnnot",1),o._FPDFPage_RemoveAnnot=q("FPDFPage_RemoveAnnot",2),o._FPDFAnnot_GetSubtype=q("FPDFAnnot_GetSubtype",1),o._FPDFAnnot_IsObjectSupportedSubtype=q("FPDFAnnot_IsObjectSupportedSubtype",1),o._FPDFAnnot_UpdateObject=q("FPDFAnnot_UpdateObject",2),o._FPDFAnnot_AddInkStroke=q("FPDFAnnot_AddInkStroke",3),o._FPDFAnnot_RemoveInkList=q("FPDFAnnot_RemoveInkList",1),o._FPDFAnnot_AppendObject=q("FPDFAnnot_AppendObject",2),o._FPDFAnnot_GetObjectCount=q("FPDFAnnot_GetObjectCount",1),o._FPDFAnnot_GetObject=q("FPDFAnnot_GetObject",2),o._FPDFAnnot_RemoveObject=q("FPDFAnnot_RemoveObject",2),o._FPDFAnnot_SetColor=q("FPDFAnnot_SetColor",6),o._FPDFAnnot_GetColor=q("FPDFAnnot_GetColor",6),o._FPDFAnnot_HasAttachmentPoints=q("FPDFAnnot_HasAttachmentPoints",1),o._FPDFAnnot_SetAttachmentPoints=q("FPDFAnnot_SetAttachmentPoints",3),o._FPDFAnnot_AppendAttachmentPoints=q("FPDFAnnot_AppendAttachmentPoints",2),o._FPDFAnnot_CountAttachmentPoints=q("FPDFAnnot_CountAttachmentPoints",1),o._FPDFAnnot_GetAttachmentPoints=q("FPDFAnnot_GetAttachmentPoints",3),o._FPDFAnnot_SetRect=q("FPDFAnnot_SetRect",2),o._FPDFAnnot_GetRect=q("FPDFAnnot_GetRect",2),o._FPDFAnnot_GetVertices=q("FPDFAnnot_GetVertices",3),o._FPDFAnnot_GetInkListCount=q("FPDFAnnot_GetInkListCount",1),o._FPDFAnnot_GetInkListPath=q("FPDFAnnot_GetInkListPath",4),o._FPDFAnnot_GetLine=q("FPDFAnnot_GetLine",3),o._FPDFAnnot_SetBorder=q("FPDFAnnot_SetBorder",4),o._FPDFAnnot_GetBorder=q("FPDFAnnot_GetBorder",4),o._FPDFAnnot_HasKey=q("FPDFAnnot_HasKey",2),o._FPDFAnnot_GetValueType=q("FPDFAnnot_GetValueType",2),o._FPDFAnnot_SetStringValue=q("FPDFAnnot_SetStringValue",3),o._FPDFAnnot_GetStringValue=q("FPDFAnnot_GetStringValue",4),o._FPDFAnnot_GetNumberValue=q("FPDFAnnot_GetNumberValue",3),o._FPDFAnnot_SetAP=q("FPDFAnnot_SetAP",3),o._FPDFAnnot_GetAP=q("FPDFAnnot_GetAP",4),o._FPDFAnnot_GetLinkedAnnot=q("FPDFAnnot_GetLinkedAnnot",2),o._FPDFAnnot_GetFlags=q("FPDFAnnot_GetFlags",1),o._FPDFAnnot_SetFlags=q("FPDFAnnot_SetFlags",2),o._FPDFAnnot_GetFormFieldFlags=q("FPDFAnnot_GetFormFieldFlags",2),o._FPDFAnnot_SetFormFieldFlags=q("FPDFAnnot_SetFormFieldFlags",3),o._FPDFAnnot_GetFormFieldAtPoint=q("FPDFAnnot_GetFormFieldAtPoint",3),o._FPDFAnnot_GetFormFieldName=q("FPDFAnnot_GetFormFieldName",4),o._FPDFAnnot_GetFormFieldType=q("FPDFAnnot_GetFormFieldType",2),o._FPDFAnnot_GetFormAdditionalActionJavaScript=q("FPDFAnnot_GetFormAdditionalActionJavaScript",5),o._FPDFAnnot_GetFormFieldAlternateName=q("FPDFAnnot_GetFormFieldAlternateName",4),o._FPDFAnnot_GetFormFieldValue=q("FPDFAnnot_GetFormFieldValue",4),o._FPDFAnnot_GetOptionCount=q("FPDFAnnot_GetOptionCount",2),o._FPDFAnnot_GetOptionLabel=q("FPDFAnnot_GetOptionLabel",5),o._FPDFAnnot_IsOptionSelected=q("FPDFAnnot_IsOptionSelected",3),o._FPDFAnnot_GetFontSize=q("FPDFAnnot_GetFontSize",3),o._FPDFAnnot_SetFontColor=q("FPDFAnnot_SetFontColor",5),o._FPDFAnnot_GetFontColor=q("FPDFAnnot_GetFontColor",5),o._FPDFAnnot_IsChecked=q("FPDFAnnot_IsChecked",2),o._FPDFAnnot_SetFocusableSubtypes=q("FPDFAnnot_SetFocusableSubtypes",3),o._FPDFAnnot_GetFocusableSubtypesCount=q("FPDFAnnot_GetFocusableSubtypesCount",1),o._FPDFAnnot_GetFocusableSubtypes=q("FPDFAnnot_GetFocusableSubtypes",3),o._FPDFAnnot_GetLink=q("FPDFAnnot_GetLink",1),o._FPDFAnnot_GetFormControlCount=q("FPDFAnnot_GetFormControlCount",2),o._FPDFAnnot_GetFormControlIndex=q("FPDFAnnot_GetFormControlIndex",2),o._FPDFAnnot_GetFormFieldExportValue=q("FPDFAnnot_GetFormFieldExportValue",4),o._FPDFAnnot_SetURI=q("FPDFAnnot_SetURI",2),o._EPDFAnnot_SetAction=q("EPDFAnnot_SetAction",2),o._FPDFAnnot_GetFileAttachment=q("FPDFAnnot_GetFileAttachment",1),o._FPDFAnnot_AddFileAttachment=q("FPDFAnnot_AddFileAttachment",2),o._EPDFAnnot_SetColor=q("EPDFAnnot_SetColor",5),o._EPDFAnnot_GetColor=q("EPDFAnnot_GetColor",5),o._EPDFAnnot_ClearColor=q("EPDFAnnot_ClearColor",2),o._EPDFAnnot_SetOpacity=q("EPDFAnnot_SetOpacity",2),o._EPDFAnnot_GetOpacity=q("EPDFAnnot_GetOpacity",2),o._EPDFAnnot_GetBorderEffect=q("EPDFAnnot_GetBorderEffect",2),o._EPDFAnnot_GetRectangleDifferences=q("EPDFAnnot_GetRectangleDifferences",5),o._EPDFAnnot_GetBorderDashPatternCount=q("EPDFAnnot_GetBorderDashPatternCount",1),o._EPDFAnnot_GetBorderDashPattern=q("EPDFAnnot_GetBorderDashPattern",3),o._EPDFAnnot_SetBorderDashPattern=q("EPDFAnnot_SetBorderDashPattern",3),o._EPDFAnnot_GetBorderStyle=q("EPDFAnnot_GetBorderStyle",2),o._EPDFAnnot_SetBorderStyle=q("EPDFAnnot_SetBorderStyle",3),o._EPDFAnnot_GenerateAppearance=q("EPDFAnnot_GenerateAppearance",1),o._EPDFAnnot_GenerateAppearanceWithBlend=q("EPDFAnnot_GenerateAppearanceWithBlend",2),o._EPDFAnnot_GetBlendMode=q("EPDFAnnot_GetBlendMode",1),o._EPDFAnnot_SetIntent=q("EPDFAnnot_SetIntent",2),o._EPDFAnnot_GetIntent=q("EPDFAnnot_GetIntent",3),o._EPDFAnnot_GetRichContent=q("EPDFAnnot_GetRichContent",3),o._EPDFAnnot_SetLineEndings=q("EPDFAnnot_SetLineEndings",3),o._EPDFAnnot_GetLineEndings=q("EPDFAnnot_GetLineEndings",3),o._EPDFAnnot_SetVertices=q("EPDFAnnot_SetVertices",3),o._EPDFAnnot_SetLine=q("EPDFAnnot_SetLine",3),o._EPDFAnnot_SetDefaultAppearance=q("EPDFAnnot_SetDefaultAppearance",6),o._EPDFAnnot_GetDefaultAppearance=q("EPDFAnnot_GetDefaultAppearance",6),o._EPDFAnnot_SetTextAlignment=q("EPDFAnnot_SetTextAlignment",2),o._EPDFAnnot_GetTextAlignment=q("EPDFAnnot_GetTextAlignment",1),o._EPDFAnnot_SetVerticalAlignment=q("EPDFAnnot_SetVerticalAlignment",2),o._EPDFAnnot_GetVerticalAlignment=q("EPDFAnnot_GetVerticalAlignment",1),o._EPDFPage_GetAnnotByName=q("EPDFPage_GetAnnotByName",2),o._EPDFPage_RemoveAnnotByName=q("EPDFPage_RemoveAnnotByName",2),o._EPDFAnnot_SetLinkedAnnot=q("EPDFAnnot_SetLinkedAnnot",3),o._EPDFPage_GetAnnotCountRaw=q("EPDFPage_GetAnnotCountRaw",2),o._EPDFPage_GetAnnotRaw=q("EPDFPage_GetAnnotRaw",3),o._EPDFPage_RemoveAnnotRaw=q("EPDFPage_RemoveAnnotRaw",3),o._EPDFAnnot_SetIcon=q("EPDFAnnot_SetIcon",2),o._EPDFAnnot_GetIcon=q("EPDFAnnot_GetIcon",1),o._EPDFAnnot_UpdateAppearanceToRect=q("EPDFAnnot_UpdateAppearanceToRect",2),o._EPDFPage_CreateAnnot=q("EPDFPage_CreateAnnot",2),o._EPDFAnnot_SetRotate=q("EPDFAnnot_SetRotate",2),o._EPDFAnnot_GetRotate=q("EPDFAnnot_GetRotate",2),o._EPDFAnnot_GetReplyType=q("EPDFAnnot_GetReplyType",1),o._EPDFAnnot_SetReplyType=q("EPDFAnnot_SetReplyType",2),o._EPDFAnnot_SetOverlayText=q("EPDFAnnot_SetOverlayText",2),o._EPDFAnnot_GetOverlayText=q("EPDFAnnot_GetOverlayText",3),o._EPDFAnnot_SetOverlayTextRepeat=q("EPDFAnnot_SetOverlayTextRepeat",2),o._EPDFAnnot_GetOverlayTextRepeat=q("EPDFAnnot_GetOverlayTextRepeat",1),o._EPDFAnnot_ApplyRedaction=q("EPDFAnnot_ApplyRedaction",2),o._EPDFPage_ApplyRedactions=q("EPDFPage_ApplyRedactions",1),o._EPDFAnnot_Flatten=q("EPDFAnnot_Flatten",2),o._EPDFAnnot_SetExtendedRotation=q("EPDFAnnot_SetExtendedRotation",2),o._EPDFAnnot_GetExtendedRotation=q("EPDFAnnot_GetExtendedRotation",2),o._EPDFAnnot_SetUnrotatedRect=q("EPDFAnnot_SetUnrotatedRect",2),o._EPDFAnnot_GetUnrotatedRect=q("EPDFAnnot_GetUnrotatedRect",2),o._EPDFAnnot_GetRect=q("EPDFAnnot_GetRect",2),o._EPDFAnnot_SetAPMatrix=q("EPDFAnnot_SetAPMatrix",3),o._EPDFAnnot_GetAPMatrix=q("EPDFAnnot_GetAPMatrix",3),o._EPDFAnnot_GetAvailableAppearanceModes=q("EPDFAnnot_GetAvailableAppearanceModes",1),o._FPDFDoc_GetAttachmentCount=q("FPDFDoc_GetAttachmentCount",1),o._FPDFDoc_AddAttachment=q("FPDFDoc_AddAttachment",2),o._FPDFDoc_GetAttachment=q("FPDFDoc_GetAttachment",2),o._FPDFDoc_DeleteAttachment=q("FPDFDoc_DeleteAttachment",2),o._FPDFAttachment_GetName=q("FPDFAttachment_GetName",3),o._FPDFAttachment_HasKey=q("FPDFAttachment_HasKey",2),o._FPDFAttachment_GetValueType=q("FPDFAttachment_GetValueType",2),o._FPDFAttachment_SetStringValue=q("FPDFAttachment_SetStringValue",3),o._FPDFAttachment_GetStringValue=q("FPDFAttachment_GetStringValue",4),o._FPDFAttachment_SetFile=q("FPDFAttachment_SetFile",4),o._FPDFAttachment_GetFile=q("FPDFAttachment_GetFile",4),o._FPDFAttachment_GetSubtype=q("FPDFAttachment_GetSubtype",3),o._EPDFAttachment_SetSubtype=q("EPDFAttachment_SetSubtype",2),o._EPDFAttachment_SetDescription=q("EPDFAttachment_SetDescription",2),o._EPDFAttachment_GetDescription=q("EPDFAttachment_GetDescription",3),o._EPDFAttachment_GetIntegerValue=q("EPDFAttachment_GetIntegerValue",3),o._FPDFCatalog_IsTagged=q("FPDFCatalog_IsTagged",1),o._FPDFCatalog_GetLanguage=q("FPDFCatalog_GetLanguage",3),o._FPDFCatalog_SetLanguage=q("FPDFCatalog_SetLanguage",2),o._EPDFCatalog_GetLanguage=q("EPDFCatalog_GetLanguage",3),o._FPDFAvail_Create=q("FPDFAvail_Create",2),o._FPDFAvail_Destroy=q("FPDFAvail_Destroy",1),o._FPDFAvail_IsDocAvail=q("FPDFAvail_IsDocAvail",2),o._FPDFAvail_GetDocument=q("FPDFAvail_GetDocument",2),o._FPDFAvail_GetFirstPageNum=q("FPDFAvail_GetFirstPageNum",1),o._FPDFAvail_IsPageAvail=q("FPDFAvail_IsPageAvail",3),o._FPDFAvail_IsFormAvail=q("FPDFAvail_IsFormAvail",2),o._FPDFAvail_IsLinearized=q("FPDFAvail_IsLinearized",1),o._FPDFBookmark_GetFirstChild=q("FPDFBookmark_GetFirstChild",2),o._FPDFBookmark_GetNextSibling=q("FPDFBookmark_GetNextSibling",2),o._FPDFBookmark_GetTitle=q("FPDFBookmark_GetTitle",3),o._FPDFBookmark_GetCount=q("FPDFBookmark_GetCount",1),o._FPDFBookmark_Find=q("FPDFBookmark_Find",2),o._FPDFBookmark_GetDest=q("FPDFBookmark_GetDest",2),o._FPDFBookmark_GetAction=q("FPDFBookmark_GetAction",1),o._FPDFAction_GetType=q("FPDFAction_GetType",1),o._FPDFAction_GetDest=q("FPDFAction_GetDest",2),o._FPDFAction_GetFilePath=q("FPDFAction_GetFilePath",3),o._FPDFAction_GetURIPath=q("FPDFAction_GetURIPath",4),o._FPDFDest_GetDestPageIndex=q("FPDFDest_GetDestPageIndex",2),o._FPDFDest_GetView=q("FPDFDest_GetView",3),o._FPDFDest_GetLocationInPage=q("FPDFDest_GetLocationInPage",7),o._FPDFLink_GetLinkAtPoint=q("FPDFLink_GetLinkAtPoint",3),o._FPDFLink_GetLinkZOrderAtPoint=q("FPDFLink_GetLinkZOrderAtPoint",3),o._FPDFLink_GetDest=q("FPDFLink_GetDest",2),o._FPDFLink_GetAction=q("FPDFLink_GetAction",1),o._FPDFLink_Enumerate=q("FPDFLink_Enumerate",3),o._FPDFLink_GetAnnot=q("FPDFLink_GetAnnot",2),o._FPDFLink_GetAnnotRect=q("FPDFLink_GetAnnotRect",2),o._FPDFLink_CountQuadPoints=q("FPDFLink_CountQuadPoints",1),o._FPDFLink_GetQuadPoints=q("FPDFLink_GetQuadPoints",3),o._FPDF_GetPageAAction=q("FPDF_GetPageAAction",2),o._FPDF_GetFileIdentifier=q("FPDF_GetFileIdentifier",4),o._FPDF_GetMetaText=q("FPDF_GetMetaText",4),o._FPDF_GetPageLabel=q("FPDF_GetPageLabel",4),o._EPDF_SetMetaText=q("EPDF_SetMetaText",3),o._EPDF_HasMetaText=q("EPDF_HasMetaText",2),o._EPDF_GetMetaTrapped=q("EPDF_GetMetaTrapped",1),o._EPDF_SetMetaTrapped=q("EPDF_SetMetaTrapped",2),o._EPDF_GetMetaKeyCount=q("EPDF_GetMetaKeyCount",2),o._EPDF_GetMetaKeyName=q("EPDF_GetMetaKeyName",5),o._FPDFPageObj_NewImageObj=q("FPDFPageObj_NewImageObj",1),o._FPDFImageObj_LoadJpegFile=q("FPDFImageObj_LoadJpegFile",4),o._FPDFImageObj_LoadJpegFileInline=q("FPDFImageObj_LoadJpegFileInline",4),o._FPDFImageObj_SetMatrix=q("FPDFImageObj_SetMatrix",7),o._FPDFImageObj_SetBitmap=q("FPDFImageObj_SetBitmap",4),o._FPDFImageObj_GetBitmap=q("FPDFImageObj_GetBitmap",1),o._FPDFImageObj_GetRenderedBitmap=q("FPDFImageObj_GetRenderedBitmap",3),o._FPDFImageObj_GetImageDataDecoded=q("FPDFImageObj_GetImageDataDecoded",3),o._FPDFImageObj_GetImageDataRaw=q("FPDFImageObj_GetImageDataRaw",3),o._FPDFImageObj_GetImageFilterCount=q("FPDFImageObj_GetImageFilterCount",1),o._FPDFImageObj_GetImageFilter=q("FPDFImageObj_GetImageFilter",4),o._FPDFImageObj_GetImageMetadata=q("FPDFImageObj_GetImageMetadata",3),o._FPDFImageObj_GetImagePixelSize=q("FPDFImageObj_GetImagePixelSize",3),o._FPDFImageObj_GetIccProfileDataDecoded=q("FPDFImageObj_GetIccProfileDataDecoded",5),o._FPDF_CreateNewDocument=q("FPDF_CreateNewDocument",0),o._FPDFPage_Delete=q("FPDFPage_Delete",2),o._FPDF_MovePages=q("FPDF_MovePages",4),o._FPDFPage_New=q("FPDFPage_New",4),o._FPDFPage_GetRotation=q("FPDFPage_GetRotation",1),o._FPDFPage_InsertObject=q("FPDFPage_InsertObject",2),o._FPDFPage_InsertObjectAtIndex=q("FPDFPage_InsertObjectAtIndex",3),o._FPDFPage_RemoveObject=q("FPDFPage_RemoveObject",2),o._FPDFPage_CountObjects=q("FPDFPage_CountObjects",1),o._FPDFPage_GetObject=q("FPDFPage_GetObject",2),o._FPDFPage_HasTransparency=q("FPDFPage_HasTransparency",1),o._FPDFPageObj_Destroy=q("FPDFPageObj_Destroy",1),o._FPDFPageObj_GetMarkedContentID=q("FPDFPageObj_GetMarkedContentID",1),o._FPDFPageObj_CountMarks=q("FPDFPageObj_CountMarks",1),o._FPDFPageObj_GetMark=q("FPDFPageObj_GetMark",2),o._FPDFPageObj_AddMark=q("FPDFPageObj_AddMark",2),o._FPDFPageObj_RemoveMark=q("FPDFPageObj_RemoveMark",2),o._FPDFPageObjMark_GetName=q("FPDFPageObjMark_GetName",4),o._FPDFPageObjMark_CountParams=q("FPDFPageObjMark_CountParams",1),o._FPDFPageObjMark_GetParamKey=q("FPDFPageObjMark_GetParamKey",5),o._FPDFPageObjMark_GetParamValueType=q("FPDFPageObjMark_GetParamValueType",2),o._FPDFPageObjMark_GetParamIntValue=q("FPDFPageObjMark_GetParamIntValue",3),o._FPDFPageObjMark_GetParamFloatValue=q("FPDFPageObjMark_GetParamFloatValue",3),o._FPDFPageObjMark_GetParamStringValue=q("FPDFPageObjMark_GetParamStringValue",5),o._FPDFPageObjMark_GetParamBlobValue=q("FPDFPageObjMark_GetParamBlobValue",5),o._FPDFPageObj_HasTransparency=q("FPDFPageObj_HasTransparency",1),o._FPDFPageObjMark_SetIntParam=q("FPDFPageObjMark_SetIntParam",5),o._FPDFPageObjMark_SetFloatParam=q("FPDFPageObjMark_SetFloatParam",5),o._FPDFPageObjMark_SetStringParam=q("FPDFPageObjMark_SetStringParam",5),o._FPDFPageObjMark_SetBlobParam=q("FPDFPageObjMark_SetBlobParam",6),o._FPDFPageObjMark_RemoveParam=q("FPDFPageObjMark_RemoveParam",3),o._FPDFPageObj_GetType=q("FPDFPageObj_GetType",1),o._FPDFPageObj_GetIsActive=q("FPDFPageObj_GetIsActive",2),o._FPDFPageObj_SetIsActive=q("FPDFPageObj_SetIsActive",2),o._FPDFPage_GenerateContent=q("FPDFPage_GenerateContent",1),o._FPDFPageObj_Transform=q("FPDFPageObj_Transform",7),o._FPDFPageObj_TransformF=q("FPDFPageObj_TransformF",2),o._FPDFPageObj_GetMatrix=q("FPDFPageObj_GetMatrix",2),o._FPDFPageObj_SetMatrix=q("FPDFPageObj_SetMatrix",2),o._FPDFPageObj_SetBlendMode=q("FPDFPageObj_SetBlendMode",2),o._FPDFPage_TransformAnnots=q("FPDFPage_TransformAnnots",7),o._FPDFPage_SetRotation=q("FPDFPage_SetRotation",2),o._FPDFPageObj_SetFillColor=q("FPDFPageObj_SetFillColor",5),o._FPDFPageObj_GetFillColor=q("FPDFPageObj_GetFillColor",5),o._FPDFPageObj_GetBounds=q("FPDFPageObj_GetBounds",5),o._FPDFPageObj_GetRotatedBounds=q("FPDFPageObj_GetRotatedBounds",2),o._FPDFPageObj_SetStrokeColor=q("FPDFPageObj_SetStrokeColor",5),o._FPDFPageObj_GetStrokeColor=q("FPDFPageObj_GetStrokeColor",5),o._FPDFPageObj_SetStrokeWidth=q("FPDFPageObj_SetStrokeWidth",2),o._FPDFPageObj_GetStrokeWidth=q("FPDFPageObj_GetStrokeWidth",2),o._FPDFPageObj_GetLineJoin=q("FPDFPageObj_GetLineJoin",1),o._FPDFPageObj_SetLineJoin=q("FPDFPageObj_SetLineJoin",2),o._FPDFPageObj_GetLineCap=q("FPDFPageObj_GetLineCap",1),o._FPDFPageObj_SetLineCap=q("FPDFPageObj_SetLineCap",2),o._FPDFPageObj_GetDashPhase=q("FPDFPageObj_GetDashPhase",2),o._FPDFPageObj_SetDashPhase=q("FPDFPageObj_SetDashPhase",2),o._FPDFPageObj_GetDashCount=q("FPDFPageObj_GetDashCount",1),o._FPDFPageObj_GetDashArray=q("FPDFPageObj_GetDashArray",3),o._FPDFPageObj_SetDashArray=q("FPDFPageObj_SetDashArray",4),o._FPDFFormObj_CountObjects=q("FPDFFormObj_CountObjects",1),o._FPDFFormObj_GetObject=q("FPDFFormObj_GetObject",2),o._FPDFFormObj_RemoveObject=q("FPDFFormObj_RemoveObject",2),o._FPDFPageObj_CreateNewPath=q("FPDFPageObj_CreateNewPath",2),o._FPDFPageObj_CreateNewRect=q("FPDFPageObj_CreateNewRect",4),o._FPDFPath_CountSegments=q("FPDFPath_CountSegments",1),o._FPDFPath_GetPathSegment=q("FPDFPath_GetPathSegment",2),o._FPDFPath_MoveTo=q("FPDFPath_MoveTo",3),o._FPDFPath_LineTo=q("FPDFPath_LineTo",3),o._FPDFPath_BezierTo=q("FPDFPath_BezierTo",7),o._FPDFPath_Close=q("FPDFPath_Close",1),o._FPDFPath_SetDrawMode=q("FPDFPath_SetDrawMode",3),o._FPDFPath_GetDrawMode=q("FPDFPath_GetDrawMode",3),o._FPDFPathSegment_GetPoint=q("FPDFPathSegment_GetPoint",3),o._FPDFPathSegment_GetType=q("FPDFPathSegment_GetType",1),o._FPDFPathSegment_GetClose=q("FPDFPathSegment_GetClose",1),o._FPDFPageObj_NewTextObj=q("FPDFPageObj_NewTextObj",3),o._FPDFText_SetText=q("FPDFText_SetText",2),o._FPDFText_SetCharcodes=q("FPDFText_SetCharcodes",3),o._FPDFText_LoadFont=q("FPDFText_LoadFont",5),o._FPDFText_LoadStandardFont=q("FPDFText_LoadStandardFont",2),o._FPDFText_LoadCidType2Font=q("FPDFText_LoadCidType2Font",6),o._FPDFTextObj_GetFontSize=q("FPDFTextObj_GetFontSize",2),o._FPDFTextObj_GetText=q("FPDFTextObj_GetText",4),o._FPDFTextObj_GetRenderedBitmap=q("FPDFTextObj_GetRenderedBitmap",4),o._FPDFFont_Close=q("FPDFFont_Close",1),o._FPDFPageObj_CreateTextObj=q("FPDFPageObj_CreateTextObj",3),o._FPDFTextObj_GetTextRenderMode=q("FPDFTextObj_GetTextRenderMode",1),o._FPDFTextObj_SetTextRenderMode=q("FPDFTextObj_SetTextRenderMode",2),o._FPDFTextObj_GetFont=q("FPDFTextObj_GetFont",1),o._FPDFFont_GetBaseFontName=q("FPDFFont_GetBaseFontName",3),o._FPDFFont_GetFamilyName=q("FPDFFont_GetFamilyName",3),o._FPDFFont_GetFontData=q("FPDFFont_GetFontData",4),o._FPDFFont_GetIsEmbedded=q("FPDFFont_GetIsEmbedded",1),o._FPDFFont_GetFlags=q("FPDFFont_GetFlags",1),o._FPDFFont_GetWeight=q("FPDFFont_GetWeight",1),o._FPDFFont_GetItalicAngle=q("FPDFFont_GetItalicAngle",2),o._FPDFFont_GetAscent=q("FPDFFont_GetAscent",3),o._FPDFFont_GetDescent=q("FPDFFont_GetDescent",3),o._FPDFFont_GetGlyphWidth=q("FPDFFont_GetGlyphWidth",4),o._FPDFFont_GetGlyphPath=q("FPDFFont_GetGlyphPath",3),o._FPDFGlyphPath_CountGlyphSegments=q("FPDFGlyphPath_CountGlyphSegments",1),o._FPDFGlyphPath_GetGlyphPathSegment=q("FPDFGlyphPath_GetGlyphPathSegment",2),o._EPDFText_RedactInRect=q("EPDFText_RedactInRect",4),o._EPDFText_RedactInQuads=q("EPDFText_RedactInQuads",5),o._FPDFDoc_GetPageMode=q("FPDFDoc_GetPageMode",1),o._FPDFPage_Flatten=q("FPDFPage_Flatten",2),o._FPDFPage_HasFormFieldAtPoint=q("FPDFPage_HasFormFieldAtPoint",4),o._FPDFPage_FormFieldZOrderAtPoint=q("FPDFPage_FormFieldZOrderAtPoint",4),o._malloc=q("malloc",1),o._free=q("free",1),o._FORM_OnMouseMove=q("FORM_OnMouseMove",5),o._FORM_OnMouseWheel=q("FORM_OnMouseWheel",6),o._FORM_OnFocus=q("FORM_OnFocus",5),o._FORM_OnLButtonDown=q("FORM_OnLButtonDown",5),o._FORM_OnLButtonUp=q("FORM_OnLButtonUp",5),o._FORM_OnLButtonDoubleClick=q("FORM_OnLButtonDoubleClick",5),o._FORM_OnRButtonDown=q("FORM_OnRButtonDown",5),o._FORM_OnRButtonUp=q("FORM_OnRButtonUp",5),o._FORM_OnKeyDown=q("FORM_OnKeyDown",4),o._FORM_OnKeyUp=q("FORM_OnKeyUp",4),o._FORM_OnChar=q("FORM_OnChar",4),o._FORM_GetFocusedText=q("FORM_GetFocusedText",4),o._FORM_GetSelectedText=q("FORM_GetSelectedText",4),o._FORM_ReplaceAndKeepSelection=q("FORM_ReplaceAndKeepSelection",3),o._FORM_ReplaceSelection=q("FORM_ReplaceSelection",3),o._FORM_SelectAllText=q("FORM_SelectAllText",2),o._FORM_CanUndo=q("FORM_CanUndo",2),o._FORM_CanRedo=q("FORM_CanRedo",2),o._FORM_Undo=q("FORM_Undo",2),o._FORM_Redo=q("FORM_Redo",2),o._FORM_ForceToKillFocus=q("FORM_ForceToKillFocus",1),o._FORM_GetFocusedAnnot=q("FORM_GetFocusedAnnot",3),o._FORM_SetFocusedAnnot=q("FORM_SetFocusedAnnot",2),o._FPDF_FFLDraw=q("FPDF_FFLDraw",9),o._FPDF_SetFormFieldHighlightColor=q("FPDF_SetFormFieldHighlightColor",3),o._FPDF_SetFormFieldHighlightAlpha=q("FPDF_SetFormFieldHighlightAlpha",2),o._FPDF_RemoveFormFieldHighlight=q("FPDF_RemoveFormFieldHighlight",1),o._FORM_OnAfterLoadPage=q("FORM_OnAfterLoadPage",2),o._FORM_OnBeforeClosePage=q("FORM_OnBeforeClosePage",2),o._FORM_DoDocumentJSAction=q("FORM_DoDocumentJSAction",1),o._FORM_DoDocumentOpenAction=q("FORM_DoDocumentOpenAction",1),o._FORM_DoDocumentAAction=q("FORM_DoDocumentAAction",2),o._FORM_DoPageAAction=q("FORM_DoPageAAction",3),o._FORM_SetIndexSelected=q("FORM_SetIndexSelected",4),o._FORM_IsIndexSelected=q("FORM_IsIndexSelected",3),o._FPDFDoc_GetJavaScriptActionCount=q("FPDFDoc_GetJavaScriptActionCount",1),o._FPDFDoc_GetJavaScriptAction=q("FPDFDoc_GetJavaScriptAction",2),o._FPDFDoc_CloseJavaScriptAction=q("FPDFDoc_CloseJavaScriptAction",1),o._FPDFJavaScriptAction_GetName=q("FPDFJavaScriptAction_GetName",3),o._FPDFJavaScriptAction_GetScript=q("FPDFJavaScriptAction_GetScript",3),o._FPDF_ImportPagesByIndex=q("FPDF_ImportPagesByIndex",5),o._FPDF_ImportPages=q("FPDF_ImportPages",4),o._FPDF_ImportNPagesToOne=q("FPDF_ImportNPagesToOne",5),o._FPDF_NewXObjectFromPage=q("FPDF_NewXObjectFromPage",3),o._FPDF_CloseXObject=q("FPDF_CloseXObject",1),o._FPDF_NewFormObjectFromXObject=q("FPDF_NewFormObjectFromXObject",1),o._FPDF_CopyViewerPreferences=q("FPDF_CopyViewerPreferences",2),o._FPDF_RenderPageBitmapWithColorScheme_Start=q("FPDF_RenderPageBitmapWithColorScheme_Start",10),o._FPDF_RenderPageBitmap_Start=q("FPDF_RenderPageBitmap_Start",9),o._FPDF_RenderPage_Continue=q("FPDF_RenderPage_Continue",2),o._FPDF_RenderPage_Close=q("FPDF_RenderPage_Close",1),o._FPDF_SaveWithVersion=q("FPDF_SaveWithVersion",4),o._FPDFText_GetCharIndexFromTextIndex=q("FPDFText_GetCharIndexFromTextIndex",2),o._FPDFText_GetTextIndexFromCharIndex=q("FPDFText_GetTextIndexFromCharIndex",2),o._FPDF_GetSignatureCount=q("FPDF_GetSignatureCount",1),o._FPDF_GetSignatureObject=q("FPDF_GetSignatureObject",2),o._FPDFSignatureObj_GetContents=q("FPDFSignatureObj_GetContents",3),o._FPDFSignatureObj_GetByteRange=q("FPDFSignatureObj_GetByteRange",3),o._FPDFSignatureObj_GetSubFilter=q("FPDFSignatureObj_GetSubFilter",3),o._FPDFSignatureObj_GetReason=q("FPDFSignatureObj_GetReason",3),o._FPDFSignatureObj_GetTime=q("FPDFSignatureObj_GetTime",3),o._FPDFSignatureObj_GetDocMDPPermission=q("FPDFSignatureObj_GetDocMDPPermission",1),o._FPDF_StructTree_GetForPage=q("FPDF_StructTree_GetForPage",1),o._FPDF_StructTree_Close=q("FPDF_StructTree_Close",1),o._FPDF_StructTree_CountChildren=q("FPDF_StructTree_CountChildren",1),o._FPDF_StructTree_GetChildAtIndex=q("FPDF_StructTree_GetChildAtIndex",2),o._FPDF_StructElement_GetAltText=q("FPDF_StructElement_GetAltText",3),o._FPDF_StructElement_GetActualText=q("FPDF_StructElement_GetActualText",3),o._FPDF_StructElement_GetID=q("FPDF_StructElement_GetID",3),o._FPDF_StructElement_GetLang=q("FPDF_StructElement_GetLang",3),o._FPDF_StructElement_GetAttributeCount=q("FPDF_StructElement_GetAttributeCount",1),o._FPDF_StructElement_GetAttributeAtIndex=q("FPDF_StructElement_GetAttributeAtIndex",2),o._FPDF_StructElement_GetStringAttribute=q("FPDF_StructElement_GetStringAttribute",4),o._FPDF_StructElement_GetMarkedContentID=q("FPDF_StructElement_GetMarkedContentID",1),o._FPDF_StructElement_GetType=q("FPDF_StructElement_GetType",3),o._FPDF_StructElement_GetObjType=q("FPDF_StructElement_GetObjType",3),o._FPDF_StructElement_GetTitle=q("FPDF_StructElement_GetTitle",3),o._FPDF_StructElement_CountChildren=q("FPDF_StructElement_CountChildren",1),o._FPDF_StructElement_GetChildAtIndex=q("FPDF_StructElement_GetChildAtIndex",2),o._FPDF_StructElement_GetChildMarkedContentID=q("FPDF_StructElement_GetChildMarkedContentID",2),o._FPDF_StructElement_GetParent=q("FPDF_StructElement_GetParent",1),o._FPDF_StructElement_Attr_GetCount=q("FPDF_StructElement_Attr_GetCount",1),o._FPDF_StructElement_Attr_GetName=q("FPDF_StructElement_Attr_GetName",5),o._FPDF_StructElement_Attr_GetValue=q("FPDF_StructElement_Attr_GetValue",2),o._FPDF_StructElement_Attr_GetType=q("FPDF_StructElement_Attr_GetType",1),o._FPDF_StructElement_Attr_GetBooleanValue=q("FPDF_StructElement_Attr_GetBooleanValue",2),o._FPDF_StructElement_Attr_GetNumberValue=q("FPDF_StructElement_Attr_GetNumberValue",2),o._FPDF_StructElement_Attr_GetStringValue=q("FPDF_StructElement_Attr_GetStringValue",4),o._FPDF_StructElement_Attr_GetBlobValue=q("FPDF_StructElement_Attr_GetBlobValue",4),o._FPDF_StructElement_Attr_CountChildren=q("FPDF_StructElement_Attr_CountChildren",1),o._FPDF_StructElement_Attr_GetChildAtIndex=q("FPDF_StructElement_Attr_GetChildAtIndex",2),o._FPDF_StructElement_GetMarkedContentIdCount=q("FPDF_StructElement_GetMarkedContentIdCount",1),o._FPDF_StructElement_GetMarkedContentIdAtIndex=q("FPDF_StructElement_GetMarkedContentIdAtIndex",2),o._FPDF_AddInstalledFont=q("FPDF_AddInstalledFont",3),o._FPDF_SetSystemFontInfo=q("FPDF_SetSystemFontInfo",1),o._FPDF_GetDefaultTTFMap=q("FPDF_GetDefaultTTFMap",0),o._FPDF_GetDefaultTTFMapCount=q("FPDF_GetDefaultTTFMapCount",0),o._FPDF_GetDefaultTTFMapEntry=q("FPDF_GetDefaultTTFMapEntry",1),o._FPDF_GetDefaultSystemFontInfo=q("FPDF_GetDefaultSystemFontInfo",0),o._FPDF_FreeDefaultSystemFontInfo=q("FPDF_FreeDefaultSystemFontInfo",1),o._FPDFText_LoadPage=q("FPDFText_LoadPage",1),o._FPDFText_ClosePage=q("FPDFText_ClosePage",1),o._FPDFText_CountChars=q("FPDFText_CountChars",1),o._FPDFText_GetUnicode=q("FPDFText_GetUnicode",2),o._FPDFText_GetTextObject=q("FPDFText_GetTextObject",2),o._FPDFText_IsGenerated=q("FPDFText_IsGenerated",2),o._FPDFText_IsHyphen=q("FPDFText_IsHyphen",2),o._FPDFText_HasUnicodeMapError=q("FPDFText_HasUnicodeMapError",2),o._FPDFText_GetFontSize=q("FPDFText_GetFontSize",2),o._FPDFText_GetFontInfo=q("FPDFText_GetFontInfo",5),o._FPDFText_GetFontWeight=q("FPDFText_GetFontWeight",2),o._FPDFText_GetFillColor=q("FPDFText_GetFillColor",6),o._FPDFText_GetStrokeColor=q("FPDFText_GetStrokeColor",6),o._FPDFText_GetCharAngle=q("FPDFText_GetCharAngle",2),o._FPDFText_GetCharBox=q("FPDFText_GetCharBox",6),o._FPDFText_GetLooseCharBox=q("FPDFText_GetLooseCharBox",3),o._FPDFText_GetMatrix=q("FPDFText_GetMatrix",3),o._FPDFText_GetCharOrigin=q("FPDFText_GetCharOrigin",4),o._FPDFText_GetCharIndexAtPos=q("FPDFText_GetCharIndexAtPos",5),o._FPDFText_GetText=q("FPDFText_GetText",4),o._FPDFText_CountRects=q("FPDFText_CountRects",3),o._FPDFText_GetRect=q("FPDFText_GetRect",6),o._FPDFText_GetBoundedText=q("FPDFText_GetBoundedText",7),o._FPDFText_FindStart=q("FPDFText_FindStart",4),o._FPDFText_FindNext=q("FPDFText_FindNext",1),o._FPDFText_FindPrev=q("FPDFText_FindPrev",1),o._FPDFText_GetSchResultIndex=q("FPDFText_GetSchResultIndex",1),o._FPDFText_GetSchCount=q("FPDFText_GetSchCount",1),o._FPDFText_FindClose=q("FPDFText_FindClose",1),o._FPDFLink_LoadWebLinks=q("FPDFLink_LoadWebLinks",1),o._FPDFLink_CountWebLinks=q("FPDFLink_CountWebLinks",1),o._FPDFLink_GetURL=q("FPDFLink_GetURL",4),o._FPDFLink_CountRects=q("FPDFLink_CountRects",2),o._FPDFLink_GetRect=q("FPDFLink_GetRect",7),o._FPDFLink_GetTextRange=q("FPDFLink_GetTextRange",4),o._FPDFLink_CloseWebLinks=q("FPDFLink_CloseWebLinks",1),o._FPDFPage_GetDecodedThumbnailData=q("FPDFPage_GetDecodedThumbnailData",3),o._FPDFPage_GetRawThumbnailData=q("FPDFPage_GetRawThumbnailData",3),o._FPDFPage_GetThumbnailAsBitmap=q("FPDFPage_GetThumbnailAsBitmap",1),o._FPDFPage_SetMediaBox=q("FPDFPage_SetMediaBox",5),o._FPDFPage_SetCropBox=q("FPDFPage_SetCropBox",5),o._FPDFPage_SetBleedBox=q("FPDFPage_SetBleedBox",5),o._FPDFPage_SetTrimBox=q("FPDFPage_SetTrimBox",5),o._FPDFPage_SetArtBox=q("FPDFPage_SetArtBox",5),o._FPDFPage_GetMediaBox=q("FPDFPage_GetMediaBox",5),o._FPDFPage_GetCropBox=q("FPDFPage_GetCropBox",5),o._FPDFPage_GetBleedBox=q("FPDFPage_GetBleedBox",5),o._FPDFPage_GetTrimBox=q("FPDFPage_GetTrimBox",5),o._FPDFPage_GetArtBox=q("FPDFPage_GetArtBox",5),o._FPDFPage_TransFormWithClip=q("FPDFPage_TransFormWithClip",3),o._FPDFPageObj_TransformClipPath=q("FPDFPageObj_TransformClipPath",7),o._FPDFPageObj_GetClipPath=q("FPDFPageObj_GetClipPath",1),o._FPDFClipPath_CountPaths=q("FPDFClipPath_CountPaths",1),o._FPDFClipPath_CountPathSegments=q("FPDFClipPath_CountPathSegments",2),o._FPDFClipPath_GetPathSegment=q("FPDFClipPath_GetPathSegment",3),o._FPDF_CreateClipPath=q("FPDF_CreateClipPath",4),o._FPDF_DestroyClipPath=q("FPDF_DestroyClipPath",1),o._FPDFPage_InsertClipPath=q("FPDFPage_InsertClipPath",2),o._FPDF_InitLibrary=q("FPDF_InitLibrary",0),o._FPDF_DestroyLibrary=q("FPDF_DestroyLibrary",0),o._FPDF_SetSandBoxPolicy=q("FPDF_SetSandBoxPolicy",2),o._FPDF_LoadDocument=q("FPDF_LoadDocument",2),o._FPDF_GetFormType=q("FPDF_GetFormType",1),o._FPDF_LoadXFA=q("FPDF_LoadXFA",1),o._FPDF_LoadMemDocument=q("FPDF_LoadMemDocument",3),o._FPDF_LoadMemDocument64=q("FPDF_LoadMemDocument64",3),o._FPDF_LoadCustomDocument=q("FPDF_LoadCustomDocument",2),o._FPDF_GetFileVersion=q("FPDF_GetFileVersion",2),o._FPDF_DocumentHasValidCrossReferenceTable=q("FPDF_DocumentHasValidCrossReferenceTable",1),o._FPDF_GetDocPermissions=q("FPDF_GetDocPermissions",1),o._FPDF_GetDocUserPermissions=q("FPDF_GetDocUserPermissions",1),o._FPDF_GetSecurityHandlerRevision=q("FPDF_GetSecurityHandlerRevision",1),o._EPDF_SetEncryption=q("EPDF_SetEncryption",4),o._EPDF_RemoveEncryption=q("EPDF_RemoveEncryption",1),o._EPDF_UnlockOwnerPermissions=q("EPDF_UnlockOwnerPermissions",2),o._EPDF_IsEncrypted=q("EPDF_IsEncrypted",1),o._EPDF_IsOwnerUnlocked=q("EPDF_IsOwnerUnlocked",1),o._FPDF_GetPageCount=q("FPDF_GetPageCount",1),o._FPDF_LoadPage=q("FPDF_LoadPage",2),o._FPDF_GetPageWidthF=q("FPDF_GetPageWidthF",1),o._FPDF_GetPageWidth=q("FPDF_GetPageWidth",1),o._FPDF_GetPageHeightF=q("FPDF_GetPageHeightF",1),o._FPDF_GetPageHeight=q("FPDF_GetPageHeight",1),o._FPDF_GetPageBoundingBox=q("FPDF_GetPageBoundingBox",2),o._FPDF_RenderPageBitmap=q("FPDF_RenderPageBitmap",8),o._FPDF_RenderPageBitmapWithMatrix=q("FPDF_RenderPageBitmapWithMatrix",5),o._EPDF_RenderAnnotBitmap=q("EPDF_RenderAnnotBitmap",6),o._EPDF_RenderAnnotBitmapUnrotated=q("EPDF_RenderAnnotBitmapUnrotated",6),o._FPDF_ClosePage=q("FPDF_ClosePage",1),o._FPDF_CloseDocument=q("FPDF_CloseDocument",1),o._FPDF_GetLastError=q("FPDF_GetLastError",0),o._FPDF_DeviceToPage=q("FPDF_DeviceToPage",10),o._FPDF_PageToDevice=q("FPDF_PageToDevice",10),o._FPDFBitmap_Create=q("FPDFBitmap_Create",3),o._FPDFBitmap_CreateEx=q("FPDFBitmap_CreateEx",5),o._FPDFBitmap_GetFormat=q("FPDFBitmap_GetFormat",1),o._FPDFBitmap_FillRect=q("FPDFBitmap_FillRect",6),o._FPDFBitmap_GetBuffer=q("FPDFBitmap_GetBuffer",1),o._FPDFBitmap_GetWidth=q("FPDFBitmap_GetWidth",1),o._FPDFBitmap_GetHeight=q("FPDFBitmap_GetHeight",1),o._FPDFBitmap_GetStride=q("FPDFBitmap_GetStride",1),o._FPDFBitmap_Destroy=q("FPDFBitmap_Destroy",1),o._FPDF_GetPageSizeByIndexF=q("FPDF_GetPageSizeByIndexF",3),o._EPDF_GetPageRotationByIndex=q("EPDF_GetPageRotationByIndex",2),o._EPDF_GetPageSizeByIndexNormalized=q("EPDF_GetPageSizeByIndexNormalized",3),o._EPDF_LoadPageNormalized=q("EPDF_LoadPageNormalized",3),o._FPDF_GetPageSizeByIndex=q("FPDF_GetPageSizeByIndex",4),o._FPDF_VIEWERREF_GetPrintScaling=q("FPDF_VIEWERREF_GetPrintScaling",1),o._FPDF_VIEWERREF_GetNumCopies=q("FPDF_VIEWERREF_GetNumCopies",1),o._FPDF_VIEWERREF_GetPrintPageRange=q("FPDF_VIEWERREF_GetPrintPageRange",1),o._FPDF_VIEWERREF_GetPrintPageRangeCount=q("FPDF_VIEWERREF_GetPrintPageRangeCount",1),o._FPDF_VIEWERREF_GetPrintPageRangeElement=q("FPDF_VIEWERREF_GetPrintPageRangeElement",2),o._FPDF_VIEWERREF_GetDuplex=q("FPDF_VIEWERREF_GetDuplex",1),o._FPDF_VIEWERREF_GetName=q("FPDF_VIEWERREF_GetName",4),o._FPDF_CountNamedDests=q("FPDF_CountNamedDests",1),o._FPDF_GetNamedDestByName=q("FPDF_GetNamedDestByName",2),o._FPDF_GetNamedDest=q("FPDF_GetNamedDest",4),o._FPDF_GetXFAPacketCount=q("FPDF_GetXFAPacketCount",1),o._FPDF_GetXFAPacketName=q("FPDF_GetXFAPacketName",4),o._FPDF_GetXFAPacketContent=q("FPDF_GetXFAPacketContent",5),o._FPDF_GetTrailerEnds=q("FPDF_GetTrailerEnds",3);var Ze,et,tt=q("fflush",1),nt=q("emscripten_builtin_memalign",2),rt=q("strerror",1),ot=q("setThrew",2),at=()=>(at=Qe.emscripten_stack_init)(),it=()=>(it=Qe.emscripten_stack_get_end)(),st=e=>(st=Qe._emscripten_stack_restore)(e),ut=e=>(ut=Qe._emscripten_stack_alloc)(e),mt=()=>(mt=Qe.emscripten_stack_get_current)();function Ft(){var e;at(),C(!(3&(e=it()))),0==e&&(e+=4),y[e>>2]=34821223,y[e+4>>2]=2310721022,y[0]=1668509029}function lt(){var e;function t(){Ze||(Ze=1,o.calledRun=1,S||(C(!k),k=!0,T(),o.noFSInit||Oe.initialized||Oe.init(),Oe.ignorePermissions=!1,ie(O),n(o),o.onRuntimeInitialized?.(),C(!o._main,'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]'),function(){T();var e=o.postRun;e&&("function"==typeof e&&(e=[e]),e.forEach(I)),ie(R)}()))}B>0||(Ft(),!et&&(et=1,(e=o.preRun)&&("function"==typeof e&&(e=[e]),e.forEach(w)),ie(v),B>0)||(o.setStatus?(o.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>o.setStatus(""),1),t()},1)):t(),T()))}if(o.dynCall_j=q("dynCall_j",1),o.dynCall_ji=q("dynCall_ji",2),o.dynCall_iiij=q("dynCall_iiij",5),o.dynCall_jji=q("dynCall_jji",4),o.dynCall_iji=q("dynCall_iji",4),o.dynCall_viijii=q("dynCall_viijii",7),o.dynCall_jij=q("dynCall_jij",4),o.dynCall_iij=q("dynCall_iij",4),o.dynCall_iiji=q("dynCall_iiji",5),o.dynCall_jiji=q("dynCall_jiji",5),o.dynCall_iiiiij=q("dynCall_iiiiij",7),o.dynCall_iiiiijj=q("dynCall_iiiiijj",9),o.dynCall_iiiiiijj=q("dynCall_iiiiiijj",10),o.dynCall_viji=q("dynCall_viji",5),o.wasmExports=Qe,o.ccall=Je,o.cwrap=(e,t,n,r)=>(...r)=>Je(e,t,n,r),o.addFunction=(e,t)=>{C(void 0!==e);var n=He(e);if(n)return n;var r=(()=>{if(Xe.length)return Xe.pop();try{Ee.grow(1)}catch(e){if(!(e instanceof RangeError))throw e;throw"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."}return Ee.length-1})();try{Ye(r,e)}catch(n){if(!(n instanceof TypeError))throw n;C(void 0!==t,"Missing signature argument to addFunction: "+e);var o=We(e,t);Ye(r,o)}return ye.set(e,r),r},o.removeFunction=e=>{ye.delete(Ue(e)),Ye(e,null),Xe.push(e)},o.setValue=function(e,t,n="i8"){switch(n.endsWith("*")&&(n="*"),n){case"i1":case"i8":b[e]=t;break;case"i16":f[e>>1]=t;break;case"i32":E[e>>2]=t;break;case"i64":W("to do setValue(i64) use WASM_BIGINT");case"float":M[e>>2]=t;break;case"double":G[e>>3]=t;break;case"*":y[e>>2]=t;break;default:W(`invalid type for setValue: ${n}`)}},o.getValue=function(e,t="i8"){switch(t.endsWith("*")&&(t="*"),t){case"i1":case"i8":return b[e];case"i16":return f[e>>1];case"i32":return E[e>>2];case"i64":W("to do getValue(i64) use WASM_BIGINT");case"float":return M[e>>2];case"double":return G[e>>3];case"*":return y[e>>2];default:W(`invalid type for getValue: ${t}`)}},o.UTF8ToString=Pe,o.stringToUTF8=we,o.UTF16ToString=(e,t)=>{C(e%2==0,"Pointer passed to UTF16ToString must be aligned to two bytes!");for(var n=e,r=n>>1,o=r+t/2;!(r>=o)&&A[r];)++r;if((n=r<<1)-e>32&&ze)return ze.decode(p.subarray(e,n));for(var a="",i=0;!(i>=t/2);++i){var s=f[e+2*i>>1];if(0==s)break;a+=String.fromCharCode(s)}return a},o.stringToUTF16=(e,t,n)=>{if(C(t%2==0,"Pointer passed to stringToUTF16 must be aligned to two bytes!"),C("number"==typeof n,"stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!"),n??=2147483647,n<2)return 0;for(var r=t,o=(n-=2)<2*e.length?n/2:e.length,a=0;a>1]=i,t+=2}return f[t>>1]=0,t-r},["writeI53ToI64","writeI53ToI64Clamped","writeI53ToI64Signaling","writeI53ToU64Clamped","writeI53ToU64Signaling","readI53FromI64","readI53FromU64","convertI32PairToI53","convertU32PairToI53","getTempRet0","setTempRet0","exitJS","inetPton4","inetNtop4","inetPton6","inetNtop6","readSockaddr","writeSockaddr","emscriptenLog","readEmAsmArgs","jstoi_q","listenOnce","autoResumeAudioContext","dynCallLegacy","getDynCaller","dynCall","handleException","keepRuntimeAlive","runtimeKeepalivePush","runtimeKeepalivePop","callUserCallback","maybeExit","asmjsMangle","HandleAllocator","getNativeTypeSize","STACK_SIZE","STACK_ALIGN","POINTER_SIZE","ASSERTIONS","reallyNegative","unSign","strLen","reSign","formatString","intArrayToString","AsciiToString","lengthBytesUTF16","UTF32ToString","stringToUTF32","lengthBytesUTF32","stringToNewUTF8","registerKeyEventCallback","maybeCStringToJsString","findEventTarget","getBoundingClientRect","fillMouseEventData","registerMouseEventCallback","registerWheelEventCallback","registerUiEventCallback","registerFocusEventCallback","fillDeviceOrientationEventData","registerDeviceOrientationEventCallback","fillDeviceMotionEventData","registerDeviceMotionEventCallback","screenOrientation","fillOrientationChangeEventData","registerOrientationChangeEventCallback","fillFullscreenChangeEventData","registerFullscreenChangeEventCallback","JSEvents_requestFullscreen","JSEvents_resizeCanvasForFullscreen","registerRestoreOldStyle","hideEverythingExceptGivenElement","restoreHiddenElements","setLetterbox","softFullscreenResizeWebGLRenderTarget","doRequestFullscreen","fillPointerlockChangeEventData","registerPointerlockChangeEventCallback","registerPointerlockErrorEventCallback","requestPointerLock","fillVisibilityChangeEventData","registerVisibilityChangeEventCallback","registerTouchEventCallback","fillGamepadEventData","registerGamepadEventCallback","registerBeforeUnloadEventCallback","fillBatteryEventData","battery","registerBatteryEventCallback","setCanvasElementSize","getCanvasElementSize","jsStackTrace","getCallstack","convertPCtoSourceLocation","checkWasiClock","wasiRightsToMuslOFlags","wasiOFlagsToMuslOFlags","createDyncallWrapper","safeSetTimeout","setImmediateWrapped","clearImmediateWrapped","polyfillSetImmediate","registerPostMainLoop","registerPreMainLoop","getPromise","makePromise","idsToPromises","makePromiseCallback","ExceptionInfo","findMatchingCatch","Browser_asyncPrepareDataCounter","safeRequestAnimationFrame","arraySum","addDays","getSocketFromFD","getSocketAddress","FS_unlink","FS_mkdirTree","_setNetworkCallback","heapObjectForWebGLType","toTypedArrayIndex","webgl_enable_ANGLE_instanced_arrays","webgl_enable_OES_vertex_array_object","webgl_enable_WEBGL_draw_buffers","webgl_enable_WEBGL_multi_draw","webgl_enable_EXT_polygon_offset_clamp","webgl_enable_EXT_clip_control","webgl_enable_WEBGL_polygon_mode","emscriptenWebGLGet","computeUnpackAlignedImageSize","colorChannelsInGlTextureFormat","emscriptenWebGLGetTexPixelData","emscriptenWebGLGetUniform","webglGetUniformLocation","webglPrepareUniformLocationsBeforeFirstUse","webglGetLeftBracePos","emscriptenWebGLGetVertexAttrib","__glGetActiveAttribOrUniform","writeGLArray","registerWebGlEventCallback","runAndAbortIfError","ALLOC_NORMAL","ALLOC_STACK","allocate","writeStringToMemory","writeAsciiToMemory","setErrNo","demangle","stackTrace"].forEach(function(e){re(e,()=>{var t=`\`${e}\` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line`,n=e;n.startsWith("_")||(n="$"+e),t+=` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='${n}')`,ne(e)&&(t+=". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you"),Fe(t)}),ae(e)}),["run","addOnPreRun","addOnInit","addOnPreMain","addOnExit","addOnPostRun","addRunDependency","removeRunDependency","out","err","callMain","abort","wasmMemory","writeStackCookie","checkStackCookie","convertI32PairToI53Checked","stackSave","stackRestore","stackAlloc","ptrToString","zeroMemory","getHeapMax","growMemory","ENV","ERRNO_CODES","strError","DNS","Protocols","Sockets","initRandomFill","randomFill","timers","warnOnce","readEmAsmArgsArray","jstoi_s","getExecutableName","asyncLoad","alignMemory","mmapAlloc","wasmTable","noExitRuntime","getCFunc","uleb128Encode","sigToWasmTypes","generateFuncType","convertJsFunctionToWasm","freeTableIndexes","functionsInTableMap","getEmptyTableSlot","updateTableMap","getFunctionAddress","PATH","PATH_FS","UTF8Decoder","UTF8ArrayToString","stringToUTF8Array","lengthBytesUTF8","intArrayFromString","stringToAscii","UTF16Decoder","stringToUTF8OnStack","writeArrayToMemory","JSEvents","specialHTMLTargets","findCanvasEventTarget","currentFullscreenStrategy","restoreOldWindowedStyle","UNWIND_CACHE","ExitStatus","getEnvStrings","doReadv","doWritev","promiseMap","uncaughtExceptionCount","exceptionLast","exceptionCaught","Browser","getPreloadedImageData__data","wget","MONTH_DAYS_REGULAR","MONTH_DAYS_LEAP","MONTH_DAYS_REGULAR_CUMULATIVE","MONTH_DAYS_LEAP_CUMULATIVE","isLeapYear","ydayFromDate","SYSCALLS","preloadPlugins","FS_createPreloadedFile","FS_modeStringToFlags","FS_getMode","FS_stdin_getChar_buffer","FS_stdin_getChar","FS_createPath","FS_createDevice","FS_readFile","FS","FS_createDataFile","FS_createLazyFile","MEMFS","TTY","PIPEFS","SOCKFS","tempFixedLengthArray","miniTempWebGLFloatBuffers","miniTempWebGLIntBuffers","GL","AL","GLUT","EGL","GLEW","IDBStore","SDL","SDL_gfx","allocateUTF8","allocateUTF8OnStack","print","printErr"].forEach(ae),N=function e(){Ze||lt(),Ze||(N=e)},o.preInit)for("function"==typeof o.preInit&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();lt(),t=a;for(const t of Object.keys(o))t in e||Object.defineProperty(e,t,{configurable:!0,get(){W(`Access to module property ('${t}') is no longer possible via the module constructor argument; Instead, use the result of the module constructor.`)}});return t});const N={EPDF_GetMetaKeyCount:[["number","boolean"],"number"],EPDF_GetMetaKeyName:[["number","number","boolean","number","number"],"number"],EPDF_GetMetaTrapped:[["number"],"number"],EPDF_GetPageRotationByIndex:[["number","number"],"number"],EPDF_GetPageSizeByIndexNormalized:[["number","number","number"],"boolean"],EPDF_HasMetaText:[["number","string"],"boolean"],EPDF_IsEncrypted:[["number"],"boolean"],EPDF_IsOwnerUnlocked:[["number"],"boolean"],EPDF_LoadPageNormalized:[["number","number","number"],"number"],EPDF_PNG_EncodeRGBA:[["number","number","number","number","number","number"],"number"],EPDF_RemoveEncryption:[["number"],"boolean"],EPDF_RenderAnnotBitmap:[["number","number","number","number","number","number"],"boolean"],EPDF_RenderAnnotBitmapUnrotated:[["number","number","number","number","number","number"],"boolean"],EPDF_SetEncryption:[["number","string","string","number"],"boolean"],EPDF_SetMetaText:[["number","string","number"],"boolean"],EPDF_SetMetaTrapped:[["number","number"],"boolean"],EPDF_UnlockOwnerPermissions:[["number","string"],"boolean"],EPDFAction_CreateGoTo:[["number","number"],"number"],EPDFAction_CreateGoToNamed:[["number","string"],"number"],EPDFAction_CreateLaunch:[["number","number"],"number"],EPDFAction_CreateRemoteGoToByName:[["number","number","number"],"number"],EPDFAction_CreateRemoteGoToDest:[["number","number","number"],"number"],EPDFAction_CreateURI:[["number","string"],"number"],EPDFAnnot_ApplyRedaction:[["number","number"],"boolean"],EPDFAnnot_ClearColor:[["number","number"],"boolean"],EPDFAnnot_Flatten:[["number","number"],"boolean"],EPDFAnnot_GenerateAppearance:[["number"],"boolean"],EPDFAnnot_GenerateAppearanceWithBlend:[["number","number"],"boolean"],EPDFAnnot_GetAPMatrix:[["number","number","number"],"boolean"],EPDFAnnot_GetAvailableAppearanceModes:[["number"],"number"],EPDFAnnot_GetBlendMode:[["number"],"number"],EPDFAnnot_GetBorderDashPattern:[["number","number","number"],"boolean"],EPDFAnnot_GetBorderDashPatternCount:[["number"],"number"],EPDFAnnot_GetBorderEffect:[["number","number"],"boolean"],EPDFAnnot_GetBorderStyle:[["number","number"],"number"],EPDFAnnot_GetColor:[["number","number","number","number","number"],"boolean"],EPDFAnnot_GetDefaultAppearance:[["number","number","number","number","number","number"],"boolean"],EPDFAnnot_GetExtendedRotation:[["number","number"],"boolean"],EPDFAnnot_GetIcon:[["number"],"number"],EPDFAnnot_GetIntent:[["number","number","number"],"number"],EPDFAnnot_GetLineEndings:[["number","number","number"],"boolean"],EPDFAnnot_GetOpacity:[["number","number"],"boolean"],EPDFAnnot_GetOverlayText:[["number","number","number"],"number"],EPDFAnnot_GetOverlayTextRepeat:[["number"],"boolean"],EPDFAnnot_GetRect:[["number","number"],"boolean"],EPDFAnnot_GetRectangleDifferences:[["number","number","number","number","number"],"boolean"],EPDFAnnot_GetReplyType:[["number"],"number"],EPDFAnnot_GetRichContent:[["number","number","number"],"number"],EPDFAnnot_GetRotate:[["number","number"],"boolean"],EPDFAnnot_GetTextAlignment:[["number"],"number"],EPDFAnnot_GetUnrotatedRect:[["number","number"],"boolean"],EPDFAnnot_GetVerticalAlignment:[["number"],"number"],EPDFAnnot_SetAction:[["number","number"],"boolean"],EPDFAnnot_SetAPMatrix:[["number","number","number"],"boolean"],EPDFAnnot_SetBorderDashPattern:[["number","number","number"],"boolean"],EPDFAnnot_SetBorderStyle:[["number","number","number"],"boolean"],EPDFAnnot_SetColor:[["number","number","number","number","number"],"boolean"],EPDFAnnot_SetDefaultAppearance:[["number","number","number","number","number","number"],"boolean"],EPDFAnnot_SetExtendedRotation:[["number","number"],"boolean"],EPDFAnnot_SetIcon:[["number","number"],"boolean"],EPDFAnnot_SetIntent:[["number","string"],"boolean"],EPDFAnnot_SetLine:[["number","number","number"],"boolean"],EPDFAnnot_SetLineEndings:[["number","number","number"],"boolean"],EPDFAnnot_SetLinkedAnnot:[["number","string","number"],"boolean"],EPDFAnnot_SetOpacity:[["number","number"],"boolean"],EPDFAnnot_SetOverlayText:[["number","number"],"boolean"],EPDFAnnot_SetOverlayTextRepeat:[["number","boolean"],"boolean"],EPDFAnnot_SetReplyType:[["number","number"],"boolean"],EPDFAnnot_SetRotate:[["number","number"],"boolean"],EPDFAnnot_SetTextAlignment:[["number","number"],"boolean"],EPDFAnnot_SetUnrotatedRect:[["number","number"],"boolean"],EPDFAnnot_SetVerticalAlignment:[["number","number"],"boolean"],EPDFAnnot_SetVertices:[["number","number","number"],"boolean"],EPDFAnnot_UpdateAppearanceToRect:[["number","number"],"boolean"],EPDFAttachment_GetDescription:[["number","number","number"],"number"],EPDFAttachment_GetIntegerValue:[["number","string","number"],"boolean"],EPDFAttachment_SetDescription:[["number","number"],"boolean"],EPDFAttachment_SetSubtype:[["number","string"],"boolean"],EPDFBookmark_AppendChild:[["number","number","number"],"number"],EPDFBookmark_Clear:[["number"],"boolean"],EPDFBookmark_ClearTarget:[["number"],"boolean"],EPDFBookmark_Create:[["number","number"],"number"],EPDFBookmark_Delete:[["number","number"],"boolean"],EPDFBookmark_InsertAfter:[["number","number","number","number"],"number"],EPDFBookmark_SetAction:[["number","number","number"],"boolean"],EPDFBookmark_SetDest:[["number","number","number"],"boolean"],EPDFBookmark_SetTitle:[["number","number"],"boolean"],EPDFCatalog_GetLanguage:[["number","number","number"],"number"],EPDFDest_CreateRemoteView:[["number","number","number","number","number"],"number"],EPDFDest_CreateRemoteXYZ:[["number","number","boolean","number","boolean","number","boolean","number"],"number"],EPDFDest_CreateView:[["number","number","number","number"],"number"],EPDFDest_CreateXYZ:[["number","boolean","number","boolean","number","boolean","number"],"number"],EPDFNamedDest_Remove:[["number","string"],"boolean"],EPDFNamedDest_SetDest:[["number","string","number"],"boolean"],EPDFPage_ApplyRedactions:[["number"],"boolean"],EPDFPage_CreateAnnot:[["number","number"],"number"],EPDFPage_GetAnnotByName:[["number","number"],"number"],EPDFPage_GetAnnotCountRaw:[["number","number"],"number"],EPDFPage_GetAnnotRaw:[["number","number","number"],"number"],EPDFPage_RemoveAnnotByName:[["number","number"],"boolean"],EPDFPage_RemoveAnnotRaw:[["number","number","number"],"boolean"],EPDFText_RedactInQuads:[["number","number","number","boolean","boolean"],"boolean"],EPDFText_RedactInRect:[["number","number","boolean","boolean"],"boolean"],FORM_CanRedo:[["number","number"],"boolean"],FORM_CanUndo:[["number","number"],"boolean"],FORM_DoDocumentAAction:[["number","number"],null],FORM_DoDocumentJSAction:[["number"],null],FORM_DoDocumentOpenAction:[["number"],null],FORM_DoPageAAction:[["number","number","number"],null],FORM_ForceToKillFocus:[["number"],"boolean"],FORM_GetFocusedAnnot:[["number","number","number"],"boolean"],FORM_GetFocusedText:[["number","number","number","number"],"number"],FORM_GetSelectedText:[["number","number","number","number"],"number"],FORM_IsIndexSelected:[["number","number","number"],"boolean"],FORM_OnAfterLoadPage:[["number","number"],null],FORM_OnBeforeClosePage:[["number","number"],null],FORM_OnChar:[["number","number","number","number"],"boolean"],FORM_OnFocus:[["number","number","number","number","number"],"boolean"],FORM_OnKeyDown:[["number","number","number","number"],"boolean"],FORM_OnKeyUp:[["number","number","number","number"],"boolean"],FORM_OnLButtonDoubleClick:[["number","number","number","number","number"],"boolean"],FORM_OnLButtonDown:[["number","number","number","number","number"],"boolean"],FORM_OnLButtonUp:[["number","number","number","number","number"],"boolean"],FORM_OnMouseMove:[["number","number","number","number","number"],"boolean"],FORM_OnMouseWheel:[["number","number","number","number","number","number"],"boolean"],FORM_OnRButtonDown:[["number","number","number","number","number"],"boolean"],FORM_OnRButtonUp:[["number","number","number","number","number"],"boolean"],FORM_Redo:[["number","number"],"boolean"],FORM_ReplaceAndKeepSelection:[["number","number","number"],null],FORM_ReplaceSelection:[["number","number","number"],null],FORM_SelectAllText:[["number","number"],"boolean"],FORM_SetFocusedAnnot:[["number","number"],"boolean"],FORM_SetIndexSelected:[["number","number","number","boolean"],"boolean"],FORM_Undo:[["number","number"],"boolean"],FPDF_AddInstalledFont:[["number","number","number"],null],FPDF_CloseDocument:[["number"],null],FPDF_ClosePage:[["number"],null],FPDF_CloseXObject:[["number"],null],FPDF_CopyViewerPreferences:[["number","number"],"boolean"],FPDF_CountNamedDests:[["number"],"number"],FPDF_CreateClipPath:[["number","number","number","number"],"number"],FPDF_CreateNewDocument:[[],"number"],FPDF_DestroyClipPath:[["number"],null],FPDF_DestroyLibrary:[[],null],FPDF_DeviceToPage:[["number","number","number","number","number","number","number","number","number","number"],"boolean"],FPDF_DocumentHasValidCrossReferenceTable:[["number"],"boolean"],FPDF_FFLDraw:[["number","number","number","number","number","number","number","number","number"],null],FPDF_FreeDefaultSystemFontInfo:[["number"],null],FPDF_GetDefaultSystemFontInfo:[[],"number"],FPDF_GetDefaultTTFMap:[[],"number"],FPDF_GetDefaultTTFMapCount:[[],"number"],FPDF_GetDefaultTTFMapEntry:[["number"],"number"],FPDF_GetDocPermissions:[["number"],"number"],FPDF_GetDocUserPermissions:[["number"],"number"],FPDF_GetFileIdentifier:[["number","number","number","number"],"number"],FPDF_GetFileVersion:[["number","number"],"boolean"],FPDF_GetFormType:[["number"],"number"],FPDF_GetLastError:[[],"number"],FPDF_GetMetaText:[["number","string","number","number"],"number"],FPDF_GetNamedDest:[["number","number","number","number"],"number"],FPDF_GetNamedDestByName:[["number","string"],"number"],FPDF_GetPageAAction:[["number","number"],"number"],FPDF_GetPageBoundingBox:[["number","number"],"boolean"],FPDF_GetPageCount:[["number"],"number"],FPDF_GetPageHeight:[["number"],"number"],FPDF_GetPageHeightF:[["number"],"number"],FPDF_GetPageLabel:[["number","number","number","number"],"number"],FPDF_GetPageSizeByIndex:[["number","number","number","number"],"number"],FPDF_GetPageSizeByIndexF:[["number","number","number"],"boolean"],FPDF_GetPageWidth:[["number"],"number"],FPDF_GetPageWidthF:[["number"],"number"],FPDF_GetSecurityHandlerRevision:[["number"],"number"],FPDF_GetSignatureCount:[["number"],"number"],FPDF_GetSignatureObject:[["number","number"],"number"],FPDF_GetTrailerEnds:[["number","number","number"],"number"],FPDF_GetXFAPacketContent:[["number","number","number","number","number"],"boolean"],FPDF_GetXFAPacketCount:[["number"],"number"],FPDF_GetXFAPacketName:[["number","number","number","number"],"number"],FPDF_ImportNPagesToOne:[["number","number","number","number","number"],"number"],FPDF_ImportPages:[["number","number","string","number"],"boolean"],FPDF_ImportPagesByIndex:[["number","number","number","number","number"],"boolean"],FPDF_InitLibrary:[[],null],FPDF_InitLibraryWithConfig:[["number"],null],FPDF_LoadCustomDocument:[["number","string"],"number"],FPDF_LoadDocument:[["number","string"],"number"],FPDF_LoadMemDocument:[["number","number","string"],"number"],FPDF_LoadMemDocument64:[["number","number","string"],"number"],FPDF_LoadPage:[["number","number"],"number"],FPDF_LoadXFA:[["number"],"boolean"],FPDF_MovePages:[["number","number","number","number"],"boolean"],FPDF_NewFormObjectFromXObject:[["number"],"number"],FPDF_NewXObjectFromPage:[["number","number","number"],"number"],FPDF_PageToDevice:[["number","number","number","number","number","number","number","number","number","number"],"boolean"],FPDF_RemoveFormFieldHighlight:[["number"],null],FPDF_RenderPage_Close:[["number"],null],FPDF_RenderPage_Continue:[["number","number"],"number"],FPDF_RenderPageBitmap:[["number","number","number","number","number","number","number","number"],null],FPDF_RenderPageBitmap_Start:[["number","number","number","number","number","number","number","number","number"],"number"],FPDF_RenderPageBitmapWithColorScheme_Start:[["number","number","number","number","number","number","number","number","number","number"],"number"],FPDF_RenderPageBitmapWithMatrix:[["number","number","number","number","number"],null],FPDF_SaveAsCopy:[["number","number","number"],"boolean"],FPDF_SaveWithVersion:[["number","number","number","number"],"boolean"],FPDF_SetFormFieldHighlightAlpha:[["number","number"],null],FPDF_SetFormFieldHighlightColor:[["number","number","number"],null],FPDF_SetSandBoxPolicy:[["number","boolean"],null],FPDF_SetSystemFontInfo:[["number"],null],FPDF_StructElement_Attr_CountChildren:[["number"],"number"],FPDF_StructElement_Attr_GetBlobValue:[["number","number","number","number"],"boolean"],FPDF_StructElement_Attr_GetBooleanValue:[["number","number"],"boolean"],FPDF_StructElement_Attr_GetChildAtIndex:[["number","number"],"number"],FPDF_StructElement_Attr_GetCount:[["number"],"number"],FPDF_StructElement_Attr_GetName:[["number","number","number","number","number"],"boolean"],FPDF_StructElement_Attr_GetNumberValue:[["number","number"],"boolean"],FPDF_StructElement_Attr_GetStringValue:[["number","number","number","number"],"boolean"],FPDF_StructElement_Attr_GetType:[["number"],"number"],FPDF_StructElement_Attr_GetValue:[["number","string"],"number"],FPDF_StructElement_CountChildren:[["number"],"number"],FPDF_StructElement_GetActualText:[["number","number","number"],"number"],FPDF_StructElement_GetAltText:[["number","number","number"],"number"],FPDF_StructElement_GetAttributeAtIndex:[["number","number"],"number"],FPDF_StructElement_GetAttributeCount:[["number"],"number"],FPDF_StructElement_GetChildAtIndex:[["number","number"],"number"],FPDF_StructElement_GetChildMarkedContentID:[["number","number"],"number"],FPDF_StructElement_GetID:[["number","number","number"],"number"],FPDF_StructElement_GetLang:[["number","number","number"],"number"],FPDF_StructElement_GetMarkedContentID:[["number"],"number"],FPDF_StructElement_GetMarkedContentIdAtIndex:[["number","number"],"number"],FPDF_StructElement_GetMarkedContentIdCount:[["number"],"number"],FPDF_StructElement_GetObjType:[["number","number","number"],"number"],FPDF_StructElement_GetParent:[["number"],"number"],FPDF_StructElement_GetStringAttribute:[["number","string","number","number"],"number"],FPDF_StructElement_GetTitle:[["number","number","number"],"number"],FPDF_StructElement_GetType:[["number","number","number"],"number"],FPDF_StructTree_Close:[["number"],null],FPDF_StructTree_CountChildren:[["number"],"number"],FPDF_StructTree_GetChildAtIndex:[["number","number"],"number"],FPDF_StructTree_GetForPage:[["number"],"number"],FPDF_VIEWERREF_GetDuplex:[["number"],"number"],FPDF_VIEWERREF_GetName:[["number","string","number","number"],"number"],FPDF_VIEWERREF_GetNumCopies:[["number"],"number"],FPDF_VIEWERREF_GetPrintPageRange:[["number"],"number"],FPDF_VIEWERREF_GetPrintPageRangeCount:[["number"],"number"],FPDF_VIEWERREF_GetPrintPageRangeElement:[["number","number"],"number"],FPDF_VIEWERREF_GetPrintScaling:[["number"],"boolean"],FPDFAction_GetDest:[["number","number"],"number"],FPDFAction_GetFilePath:[["number","number","number"],"number"],FPDFAction_GetType:[["number"],"number"],FPDFAction_GetURIPath:[["number","number","number","number"],"number"],FPDFAnnot_AddFileAttachment:[["number","number"],"number"],FPDFAnnot_AddInkStroke:[["number","number","number"],"number"],FPDFAnnot_AppendAttachmentPoints:[["number","number"],"boolean"],FPDFAnnot_AppendObject:[["number","number"],"boolean"],FPDFAnnot_CountAttachmentPoints:[["number"],"number"],FPDFAnnot_GetAP:[["number","number","number","number"],"number"],FPDFAnnot_GetAttachmentPoints:[["number","number","number"],"boolean"],FPDFAnnot_GetBorder:[["number","number","number","number"],"boolean"],FPDFAnnot_GetColor:[["number","number","number","number","number","number"],"boolean"],FPDFAnnot_GetFileAttachment:[["number"],"number"],FPDFAnnot_GetFlags:[["number"],"number"],FPDFAnnot_GetFocusableSubtypes:[["number","number","number"],"boolean"],FPDFAnnot_GetFocusableSubtypesCount:[["number"],"number"],FPDFAnnot_GetFontColor:[["number","number","number","number","number"],"boolean"],FPDFAnnot_GetFontSize:[["number","number","number"],"boolean"],FPDFAnnot_GetFormAdditionalActionJavaScript:[["number","number","number","number","number"],"number"],FPDFAnnot_GetFormControlCount:[["number","number"],"number"],FPDFAnnot_GetFormControlIndex:[["number","number"],"number"],FPDFAnnot_GetFormFieldAlternateName:[["number","number","number","number"],"number"],FPDFAnnot_GetFormFieldAtPoint:[["number","number","number"],"number"],FPDFAnnot_GetFormFieldExportValue:[["number","number","number","number"],"number"],FPDFAnnot_GetFormFieldFlags:[["number","number"],"number"],FPDFAnnot_GetFormFieldName:[["number","number","number","number"],"number"],FPDFAnnot_GetFormFieldType:[["number","number"],"number"],FPDFAnnot_GetFormFieldValue:[["number","number","number","number"],"number"],FPDFAnnot_GetInkListCount:[["number"],"number"],FPDFAnnot_GetInkListPath:[["number","number","number","number"],"number"],FPDFAnnot_GetLine:[["number","number","number"],"boolean"],FPDFAnnot_GetLink:[["number"],"number"],FPDFAnnot_GetLinkedAnnot:[["number","string"],"number"],FPDFAnnot_GetNumberValue:[["number","string","number"],"boolean"],FPDFAnnot_GetObject:[["number","number"],"number"],FPDFAnnot_GetObjectCount:[["number"],"number"],FPDFAnnot_GetOptionCount:[["number","number"],"number"],FPDFAnnot_GetOptionLabel:[["number","number","number","number","number"],"number"],FPDFAnnot_GetRect:[["number","number"],"boolean"],FPDFAnnot_GetStringValue:[["number","string","number","number"],"number"],FPDFAnnot_GetSubtype:[["number"],"number"],FPDFAnnot_GetValueType:[["number","string"],"number"],FPDFAnnot_GetVertices:[["number","number","number"],"number"],FPDFAnnot_HasAttachmentPoints:[["number"],"boolean"],FPDFAnnot_HasKey:[["number","string"],"boolean"],FPDFAnnot_IsChecked:[["number","number"],"boolean"],FPDFAnnot_IsObjectSupportedSubtype:[["number"],"boolean"],FPDFAnnot_IsOptionSelected:[["number","number","number"],"boolean"],FPDFAnnot_IsSupportedSubtype:[["number"],"boolean"],FPDFAnnot_RemoveInkList:[["number"],"boolean"],FPDFAnnot_RemoveObject:[["number","number"],"boolean"],FPDFAnnot_SetAP:[["number","number","number"],"boolean"],FPDFAnnot_SetAttachmentPoints:[["number","number","number"],"boolean"],FPDFAnnot_SetBorder:[["number","number","number","number"],"boolean"],FPDFAnnot_SetColor:[["number","number","number","number","number","number"],"boolean"],FPDFAnnot_SetFlags:[["number","number"],"boolean"],FPDFAnnot_SetFocusableSubtypes:[["number","number","number"],"boolean"],FPDFAnnot_SetFontColor:[["number","number","number","number","number"],"boolean"],FPDFAnnot_SetFormFieldFlags:[["number","number","number"],"boolean"],FPDFAnnot_SetRect:[["number","number"],"boolean"],FPDFAnnot_SetStringValue:[["number","string","number"],"boolean"],FPDFAnnot_SetURI:[["number","number"],"boolean"],FPDFAnnot_UpdateObject:[["number","number"],"boolean"],FPDFAttachment_GetFile:[["number","number","number","number"],"boolean"],FPDFAttachment_GetName:[["number","number","number"],"number"],FPDFAttachment_GetStringValue:[["number","string","number","number"],"number"],FPDFAttachment_GetSubtype:[["number","number","number"],"number"],FPDFAttachment_GetValueType:[["number","string"],"number"],FPDFAttachment_HasKey:[["number","string"],"boolean"],FPDFAttachment_SetFile:[["number","number","number","number"],"boolean"],FPDFAttachment_SetStringValue:[["number","string","number"],"boolean"],FPDFAvail_Create:[["number","number"],"number"],FPDFAvail_Destroy:[["number"],null],FPDFAvail_GetDocument:[["number","string"],"number"],FPDFAvail_GetFirstPageNum:[["number"],"number"],FPDFAvail_IsDocAvail:[["number","number"],"number"],FPDFAvail_IsFormAvail:[["number","number"],"number"],FPDFAvail_IsLinearized:[["number"],"number"],FPDFAvail_IsPageAvail:[["number","number","number"],"number"],FPDFBitmap_Create:[["number","number","number"],"number"],FPDFBitmap_CreateEx:[["number","number","number","number","number"],"number"],FPDFBitmap_Destroy:[["number"],null],FPDFBitmap_FillRect:[["number","number","number","number","number","number"],"boolean"],FPDFBitmap_GetBuffer:[["number"],"number"],FPDFBitmap_GetFormat:[["number"],"number"],FPDFBitmap_GetHeight:[["number"],"number"],FPDFBitmap_GetStride:[["number"],"number"],FPDFBitmap_GetWidth:[["number"],"number"],FPDFBookmark_Find:[["number","number"],"number"],FPDFBookmark_GetAction:[["number"],"number"],FPDFBookmark_GetCount:[["number"],"number"],FPDFBookmark_GetDest:[["number","number"],"number"],FPDFBookmark_GetFirstChild:[["number","number"],"number"],FPDFBookmark_GetNextSibling:[["number","number"],"number"],FPDFBookmark_GetTitle:[["number","number","number"],"number"],FPDFCatalog_GetLanguage:[["number","number","number"],"number"],FPDFCatalog_IsTagged:[["number"],"boolean"],FPDFCatalog_SetLanguage:[["number","number"],"boolean"],FPDFClipPath_CountPaths:[["number"],"number"],FPDFClipPath_CountPathSegments:[["number","number"],"number"],FPDFClipPath_GetPathSegment:[["number","number","number"],"number"],FPDFDest_GetDestPageIndex:[["number","number"],"number"],FPDFDest_GetLocationInPage:[["number","number","number","number","number","number","number"],"boolean"],FPDFDest_GetView:[["number","number","number"],"number"],FPDFDoc_AddAttachment:[["number","number"],"number"],FPDFDoc_CloseJavaScriptAction:[["number"],null],FPDFDoc_DeleteAttachment:[["number","number"],"boolean"],FPDFDOC_ExitFormFillEnvironment:[["number"],null],FPDFDoc_GetAttachment:[["number","number"],"number"],FPDFDoc_GetAttachmentCount:[["number"],"number"],FPDFDoc_GetJavaScriptAction:[["number","number"],"number"],FPDFDoc_GetJavaScriptActionCount:[["number"],"number"],FPDFDoc_GetPageMode:[["number"],"number"],FPDFDOC_InitFormFillEnvironment:[["number","number"],"number"],FPDFFont_Close:[["number"],null],FPDFFont_GetAscent:[["number","number","number"],"boolean"],FPDFFont_GetBaseFontName:[["number","number","number"],"number"],FPDFFont_GetDescent:[["number","number","number"],"boolean"],FPDFFont_GetFamilyName:[["number","number","number"],"number"],FPDFFont_GetFlags:[["number"],"number"],FPDFFont_GetFontData:[["number","number","number","number"],"boolean"],FPDFFont_GetGlyphPath:[["number","number","number"],"number"],FPDFFont_GetGlyphWidth:[["number","number","number","number"],"boolean"],FPDFFont_GetIsEmbedded:[["number"],"number"],FPDFFont_GetItalicAngle:[["number","number"],"boolean"],FPDFFont_GetWeight:[["number"],"number"],FPDFFormObj_CountObjects:[["number"],"number"],FPDFFormObj_GetObject:[["number","number"],"number"],FPDFFormObj_RemoveObject:[["number","number"],"boolean"],FPDFGlyphPath_CountGlyphSegments:[["number"],"number"],FPDFGlyphPath_GetGlyphPathSegment:[["number","number"],"number"],FPDFImageObj_GetBitmap:[["number"],"number"],FPDFImageObj_GetIccProfileDataDecoded:[["number","number","number","number","number"],"boolean"],FPDFImageObj_GetImageDataDecoded:[["number","number","number"],"number"],FPDFImageObj_GetImageDataRaw:[["number","number","number"],"number"],FPDFImageObj_GetImageFilter:[["number","number","number","number"],"number"],FPDFImageObj_GetImageFilterCount:[["number"],"number"],FPDFImageObj_GetImageMetadata:[["number","number","number"],"boolean"],FPDFImageObj_GetImagePixelSize:[["number","number","number"],"boolean"],FPDFImageObj_GetRenderedBitmap:[["number","number","number"],"number"],FPDFImageObj_LoadJpegFile:[["number","number","number","number"],"boolean"],FPDFImageObj_LoadJpegFileInline:[["number","number","number","number"],"boolean"],FPDFImageObj_SetBitmap:[["number","number","number","number"],"boolean"],FPDFImageObj_SetMatrix:[["number","number","number","number","number","number","number"],"boolean"],FPDFJavaScriptAction_GetName:[["number","number","number"],"number"],FPDFJavaScriptAction_GetScript:[["number","number","number"],"number"],FPDFLink_CloseWebLinks:[["number"],null],FPDFLink_CountQuadPoints:[["number"],"number"],FPDFLink_CountRects:[["number","number"],"number"],FPDFLink_CountWebLinks:[["number"],"number"],FPDFLink_Enumerate:[["number","number","number"],"boolean"],FPDFLink_GetAction:[["number"],"number"],FPDFLink_GetAnnot:[["number","number"],"number"],FPDFLink_GetAnnotRect:[["number","number"],"boolean"],FPDFLink_GetDest:[["number","number"],"number"],FPDFLink_GetLinkAtPoint:[["number","number","number"],"number"],FPDFLink_GetLinkZOrderAtPoint:[["number","number","number"],"number"],FPDFLink_GetQuadPoints:[["number","number","number"],"boolean"],FPDFLink_GetRect:[["number","number","number","number","number","number","number"],"boolean"],FPDFLink_GetTextRange:[["number","number","number","number"],"boolean"],FPDFLink_GetURL:[["number","number","number","number"],"number"],FPDFLink_LoadWebLinks:[["number"],"number"],FPDFPage_CloseAnnot:[["number"],null],FPDFPage_CountObjects:[["number"],"number"],FPDFPage_CreateAnnot:[["number","number"],"number"],FPDFPage_Delete:[["number","number"],null],FPDFPage_Flatten:[["number","number"],"number"],FPDFPage_FormFieldZOrderAtPoint:[["number","number","number","number"],"number"],FPDFPage_GenerateContent:[["number"],"boolean"],FPDFPage_GetAnnot:[["number","number"],"number"],FPDFPage_GetAnnotCount:[["number"],"number"],FPDFPage_GetAnnotIndex:[["number","number"],"number"],FPDFPage_GetArtBox:[["number","number","number","number","number"],"boolean"],FPDFPage_GetBleedBox:[["number","number","number","number","number"],"boolean"],FPDFPage_GetCropBox:[["number","number","number","number","number"],"boolean"],FPDFPage_GetDecodedThumbnailData:[["number","number","number"],"number"],FPDFPage_GetMediaBox:[["number","number","number","number","number"],"boolean"],FPDFPage_GetObject:[["number","number"],"number"],FPDFPage_GetRawThumbnailData:[["number","number","number"],"number"],FPDFPage_GetRotation:[["number"],"number"],FPDFPage_GetThumbnailAsBitmap:[["number"],"number"],FPDFPage_GetTrimBox:[["number","number","number","number","number"],"boolean"],FPDFPage_HasFormFieldAtPoint:[["number","number","number","number"],"number"],FPDFPage_HasTransparency:[["number"],"boolean"],FPDFPage_InsertClipPath:[["number","number"],null],FPDFPage_InsertObject:[["number","number"],null],FPDFPage_InsertObjectAtIndex:[["number","number","number"],"boolean"],FPDFPage_New:[["number","number","number","number"],"number"],FPDFPage_RemoveAnnot:[["number","number"],"boolean"],FPDFPage_RemoveObject:[["number","number"],"boolean"],FPDFPage_SetArtBox:[["number","number","number","number","number"],null],FPDFPage_SetBleedBox:[["number","number","number","number","number"],null],FPDFPage_SetCropBox:[["number","number","number","number","number"],null],FPDFPage_SetMediaBox:[["number","number","number","number","number"],null],FPDFPage_SetRotation:[["number","number"],null],FPDFPage_SetTrimBox:[["number","number","number","number","number"],null],FPDFPage_TransformAnnots:[["number","number","number","number","number","number","number"],null],FPDFPage_TransFormWithClip:[["number","number","number"],"boolean"],FPDFPageObj_AddMark:[["number","string"],"number"],FPDFPageObj_CountMarks:[["number"],"number"],FPDFPageObj_CreateNewPath:[["number","number"],"number"],FPDFPageObj_CreateNewRect:[["number","number","number","number"],"number"],FPDFPageObj_CreateTextObj:[["number","number","number"],"number"],FPDFPageObj_Destroy:[["number"],null],FPDFPageObj_GetBounds:[["number","number","number","number","number"],"boolean"],FPDFPageObj_GetClipPath:[["number"],"number"],FPDFPageObj_GetDashArray:[["number","number","number"],"boolean"],FPDFPageObj_GetDashCount:[["number"],"number"],FPDFPageObj_GetDashPhase:[["number","number"],"boolean"],FPDFPageObj_GetFillColor:[["number","number","number","number","number"],"boolean"],FPDFPageObj_GetIsActive:[["number","number"],"boolean"],FPDFPageObj_GetLineCap:[["number"],"number"],FPDFPageObj_GetLineJoin:[["number"],"number"],FPDFPageObj_GetMark:[["number","number"],"number"],FPDFPageObj_GetMarkedContentID:[["number"],"number"],FPDFPageObj_GetMatrix:[["number","number"],"boolean"],FPDFPageObj_GetRotatedBounds:[["number","number"],"boolean"],FPDFPageObj_GetStrokeColor:[["number","number","number","number","number"],"boolean"],FPDFPageObj_GetStrokeWidth:[["number","number"],"boolean"],FPDFPageObj_GetType:[["number"],"number"],FPDFPageObj_HasTransparency:[["number"],"boolean"],FPDFPageObj_NewImageObj:[["number"],"number"],FPDFPageObj_NewTextObj:[["number","string","number"],"number"],FPDFPageObj_RemoveMark:[["number","number"],"boolean"],FPDFPageObj_SetBlendMode:[["number","string"],null],FPDFPageObj_SetDashArray:[["number","number","number","number"],"boolean"],FPDFPageObj_SetDashPhase:[["number","number"],"boolean"],FPDFPageObj_SetFillColor:[["number","number","number","number","number"],"boolean"],FPDFPageObj_SetIsActive:[["number","boolean"],"boolean"],FPDFPageObj_SetLineCap:[["number","number"],"boolean"],FPDFPageObj_SetLineJoin:[["number","number"],"boolean"],FPDFPageObj_SetMatrix:[["number","number"],"boolean"],FPDFPageObj_SetStrokeColor:[["number","number","number","number","number"],"boolean"],FPDFPageObj_SetStrokeWidth:[["number","number"],"boolean"],FPDFPageObj_Transform:[["number","number","number","number","number","number","number"],null],FPDFPageObj_TransformClipPath:[["number","number","number","number","number","number","number"],null],FPDFPageObj_TransformF:[["number","number"],"boolean"],FPDFPageObjMark_CountParams:[["number"],"number"],FPDFPageObjMark_GetName:[["number","number","number","number"],"boolean"],FPDFPageObjMark_GetParamBlobValue:[["number","string","number","number","number"],"boolean"],FPDFPageObjMark_GetParamFloatValue:[["number","string","number"],"boolean"],FPDFPageObjMark_GetParamIntValue:[["number","string","number"],"boolean"],FPDFPageObjMark_GetParamKey:[["number","number","number","number","number"],"boolean"],FPDFPageObjMark_GetParamStringValue:[["number","string","number","number","number"],"boolean"],FPDFPageObjMark_GetParamValueType:[["number","string"],"number"],FPDFPageObjMark_RemoveParam:[["number","number","string"],"boolean"],FPDFPageObjMark_SetBlobParam:[["number","number","number","string","number","number"],"boolean"],FPDFPageObjMark_SetFloatParam:[["number","number","number","string","number"],"boolean"],FPDFPageObjMark_SetIntParam:[["number","number","number","string","number"],"boolean"],FPDFPageObjMark_SetStringParam:[["number","number","number","string","string"],"boolean"],FPDFPath_BezierTo:[["number","number","number","number","number","number","number"],"boolean"],FPDFPath_Close:[["number"],"boolean"],FPDFPath_CountSegments:[["number"],"number"],FPDFPath_GetDrawMode:[["number","number","number"],"boolean"],FPDFPath_GetPathSegment:[["number","number"],"number"],FPDFPath_LineTo:[["number","number","number"],"boolean"],FPDFPath_MoveTo:[["number","number","number"],"boolean"],FPDFPath_SetDrawMode:[["number","number","boolean"],"boolean"],FPDFPathSegment_GetClose:[["number"],"boolean"],FPDFPathSegment_GetPoint:[["number","number","number"],"boolean"],FPDFPathSegment_GetType:[["number"],"number"],FPDFSignatureObj_GetByteRange:[["number","number","number"],"number"],FPDFSignatureObj_GetContents:[["number","number","number"],"number"],FPDFSignatureObj_GetDocMDPPermission:[["number"],"number"],FPDFSignatureObj_GetReason:[["number","number","number"],"number"],FPDFSignatureObj_GetSubFilter:[["number","number","number"],"number"],FPDFSignatureObj_GetTime:[["number","number","number"],"number"],FPDFText_ClosePage:[["number"],null],FPDFText_CountChars:[["number"],"number"],FPDFText_CountRects:[["number","number","number"],"number"],FPDFText_FindClose:[["number"],null],FPDFText_FindNext:[["number"],"boolean"],FPDFText_FindPrev:[["number"],"boolean"],FPDFText_FindStart:[["number","number","number","number"],"number"],FPDFText_GetBoundedText:[["number","number","number","number","number","number","number"],"number"],FPDFText_GetCharAngle:[["number","number"],"number"],FPDFText_GetCharBox:[["number","number","number","number","number","number"],"boolean"],FPDFText_GetCharIndexAtPos:[["number","number","number","number","number"],"number"],FPDFText_GetCharIndexFromTextIndex:[["number","number"],"number"],FPDFText_GetCharOrigin:[["number","number","number","number"],"boolean"],FPDFText_GetFillColor:[["number","number","number","number","number","number"],"boolean"],FPDFText_GetFontInfo:[["number","number","number","number","number"],"number"],FPDFText_GetFontSize:[["number","number"],"number"],FPDFText_GetFontWeight:[["number","number"],"number"],FPDFText_GetLooseCharBox:[["number","number","number"],"boolean"],FPDFText_GetMatrix:[["number","number","number"],"boolean"],FPDFText_GetRect:[["number","number","number","number","number","number"],"boolean"],FPDFText_GetSchCount:[["number"],"number"],FPDFText_GetSchResultIndex:[["number"],"number"],FPDFText_GetStrokeColor:[["number","number","number","number","number","number"],"boolean"],FPDFText_GetText:[["number","number","number","number"],"number"],FPDFText_GetTextIndexFromCharIndex:[["number","number"],"number"],FPDFText_GetTextObject:[["number","number"],"number"],FPDFText_GetUnicode:[["number","number"],"number"],FPDFText_HasUnicodeMapError:[["number","number"],"number"],FPDFText_IsGenerated:[["number","number"],"number"],FPDFText_IsHyphen:[["number","number"],"number"],FPDFText_LoadCidType2Font:[["number","number","number","string","number","number"],"number"],FPDFText_LoadFont:[["number","number","number","number","boolean"],"number"],FPDFText_LoadPage:[["number"],"number"],FPDFText_LoadStandardFont:[["number","string"],"number"],FPDFText_SetCharcodes:[["number","number","number"],"boolean"],FPDFText_SetText:[["number","number"],"boolean"],FPDFTextObj_GetFont:[["number"],"number"],FPDFTextObj_GetFontSize:[["number","number"],"boolean"],FPDFTextObj_GetRenderedBitmap:[["number","number","number","number"],"number"],FPDFTextObj_GetText:[["number","number","number","number"],"number"],FPDFTextObj_GetTextRenderMode:[["number"],"number"],FPDFTextObj_SetTextRenderMode:[["number","number"],"boolean"],PDFiumExt_CloseFileWriter:[["number"],null],PDFiumExt_CloseFormFillInfo:[["number"],null],PDFiumExt_ExitFormFillEnvironment:[["number"],null],PDFiumExt_GetFileWriterData:[["number","number","number"],"number"],PDFiumExt_GetFileWriterSize:[["number"],"number"],PDFiumExt_Init:[[],null],PDFiumExt_InitFormFillEnvironment:[["number","number"],"number"],PDFiumExt_OpenFileWriter:[[],"number"],PDFiumExt_OpenFormFillInfo:[[],"number"],PDFiumExt_SaveAsCopy:[["number","number"],"number"]};async function V(e){return async function(e){const t={pdfium:e};for(const n in N){const r=n,o=N[r][0],a=N[r][1];t[r]=e.cwrap(n,a,o)}return t}(await L(e))}function U(e,t,n,r=100){let o=e.wasmExports.malloc(r);for(let t=0;tr){e.wasmExports.free(o),o=e.wasmExports.malloc(a);for(let t=0;t127)return!1;if($.has(e))return!1;if("/"===e[0])return!1;for(let t=0;t126)return!1}return!0}const H={pageTtl:5e3,maxPagesPerDocument:10,normalizeRotation:!1};class X{constructor(e,t,n={}){this.pdfium=e,this.memoryManager=t,this.docs=new Map,this.config={...H,...n}}setDocument(e,t,n,r=!1){let o=this.docs.get(e);if(!o){const a={...this.config,normalizeRotation:r};o=new Y(t,n,this.pdfium,this.memoryManager,a),this.docs.set(e,o)}}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 e of this.docs.values())e.updateConfig(this.config)}getCacheStats(){const e={};let t=0;for(const[n,r]of this.docs.entries()){const o=r.getCacheSize();e[n]=o,t+=o}return{documents:this.docs.size,totalPages:t,pagesByDocument:e}}}class Y{constructor(e,t,n,r,o){this.filePtr=e,this.docPtr=t,this.memoryManager=r,this.normalizeRotation=o.normalizeRotation,this.pageCache=new K(n,t,o)}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 K{constructor(e,t,n){this.pdf=e,this.docPtr=t,this.cache=new Map,this.accessOrder=[],this.config=n}acquire(e){let t=this.cache.get(e);if(!t){let n;this.evictIfNeeded(),n=this.config.normalizeRotation?this.pdf.EPDF_LoadPageNormalized(this.docPtr,e,0):this.pdf.FPDF_LoadPage(this.docPtr,e),t=new J(this.pdf,this.docPtr,e,n,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 n=this.cache.has(e),r=this.acquire(e);try{return t(r)}finally{n?r.release():r.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 J{constructor(e,t,n,r,o,a){this.pdf=e,this.docPtr=t,this.pageIdx=n,this.pagePtr=r,this.onFinalDispose=a,this.refCount=0,this.disposed=!1,this.ttl=o}bumpRefCount(){if(this.disposed)throw new Error("Context already disposed");this.refCount++}getRefCount(){return this.refCount}clearExpiryTimer(){this.expiryTimer&&(clearTimeout(this.expiryTimer),this.expiryTimer=void 0)}updateTtl(e){this.ttl=e,this.expiryTimer&&0===this.refCount&&(this.clearExpiryTimer(),this.expiryTimer=setTimeout(()=>this.disposeImmediate(),this.ttl))}release(){this.disposed||(this.refCount--,0===this.refCount&&(this.expiryTimer=setTimeout(()=>this.disposeImmediate(),this.ttl)))}disposeImmediate(){this.disposed||(this.disposed=!0,this.clearExpiryTimer(),void 0!==this.textPagePtr&&this.pdf.FPDFText_ClosePage(this.textPagePtr),void 0!==this.formHandle&&(this.pdf.FORM_OnBeforeClosePage(this.pagePtr,this.formHandle),this.pdf.PDFiumExt_ExitFormFillEnvironment(this.formHandle)),void 0!==this.formInfoPtr&&this.pdf.PDFiumExt_CloseFormFillInfo(this.formInfoPtr),this.pdf.FPDF_ClosePage(this.pagePtr),this.onFinalDispose())}getTextPage(){return this.ensureAlive(),void 0===this.textPagePtr&&(this.textPagePtr=this.pdf.FPDFText_LoadPage(this.pagePtr)),this.textPagePtr}getFormHandle(){return this.ensureAlive(),void 0===this.formHandle&&(this.formInfoPtr=this.pdf.PDFiumExt_OpenFormFillInfo(),this.formHandle=this.pdf.PDFiumExt_InitFormFillEnvironment(this.docPtr,this.formInfoPtr),this.pdf.FORM_OnAfterLoadPage(this.pagePtr,this.formHandle)),this.formHandle}withAnnotation(e,t){this.ensureAlive();const n=this.pdf.FPDFPage_GetAnnot(this.pagePtr,e);try{return t(n)}finally{this.pdf.FPDFPage_CloseAnnot(n)}}ensureAlive(){if(this.disposed)throw new Error("PageContext already disposed")}}const q={MAX_TOTAL_MEMORY:2147483648},Q="PDFiumEngine",Z="MemoryManager";class ee{constructor(e,t){this.pdfiumModule=e,this.logger=t,this.allocations=new Map,this.totalAllocated=0}malloc(e){if(this.totalAllocated+e>q.MAX_TOTAL_MEMORY)throw new Error(`Total memory usage would exceed limit: ${this.totalAllocated+e} > ${q.MAX_TOTAL_MEMORY}`);const t=this.pdfiumModule.pdfium.wasmExports.malloc(e);if(!t)throw new Error(`Failed to allocate ${e} bytes`);const n={ptr:t,size:e,timestamp:Date.now(),stack:this.logger.isEnabled("debug")?(new Error).stack:void 0};return this.allocations.set(t,n),this.totalAllocated+=e,t}free(e){const t=this.allocations.get(e);t?(this.totalAllocated-=t.size,this.allocations.delete(e)):this.logger.warn(Q,Z,`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(Q,Z,`Potential memory leak: ${this.allocations.size} unfreed allocations`);for(const[e,t]of this.allocations)this.logger.warn(Q,Z,` - ${e}: ${t.size} bytes`,t.stack)}}}const te="pdfium",ne="font-fallback";class re{constructor(t,n=new e){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=t,this.logger=n}initialize(e){if(this.enabled)return void this.logger.warn(te,ne,"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,n,r,o,a,i,s)=>{const u=i?t.UTF8ToString(i):"",m=this.mapFont(n,r,o,a,u);return s&&t.setValue(s,0,"i32"),m},"iiiiiiii"),this.getFontFnPtr=t.addFunction((e,n)=>{const r=n?t.UTF8ToString(n):"";return this.mapFont(400,0,0,0,r)},"iii"),this.getFontDataFnPtr=t.addFunction((e,t,n,r,o)=>this.getFontData(t,n,r,o),"iiiiii"),this.getFaceNameFnPtr=t.addFunction((e,t,n,r)=>0,"iiiii"),this.getFontCharsetFnPtr=t.addFunction((e,t)=>{const n=this.fontHandles.get(t);return(null==n?void 0:n.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(te,ne,"Font fallback system initialized (pure TypeScript)",Object.keys(this.fontConfig.fonts))}catch(e){throw this.logger.error(te,ne,"Failed to initialize font fallback",e),this.cleanup(),e}else this.logger.error(te,ne,"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(te,ne,"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),n=[...new Set(t)];await Promise.all(n.map(async e=>{if(!this.fontCache.has(e))try{const t=await this.fetchFontAsync(e);t&&(this.fontCache.set(e,t),this.logger.debug(te,ne,`Pre-loaded font: ${e}`))}catch(t){this.logger.warn(te,ne,`Failed to pre-load font: ${e}`,t)}}))}mapFont(e,t,n,r,o){const a=0!==t;this.logger.debug(te,ne,"MapFont called",{weight:e,italic:a,charset:n,pitchFamily:r,face:o});const i=this.findBestFontMatch(n,e,a);if(!i)return this.logger.debug(te,ne,`No font configured for charset ${n}`),0;const s={id:this.nextHandleId++,charset:n,weight:e,italic:a,url:i.url,data:null};return this.fontHandles.set(s.id,s),this.logger.debug(te,ne,`Created font handle ${s.id} for ${i.url} (requested: weight=${e}, italic=${a}, matched: weight=${i.matchedWeight}, italic=${i.matchedItalic})`),s.id}getFontData(e,t,n,r){const o=this.fontHandles.get(e);if(!o)return this.logger.warn(te,ne,`Unknown font handle: ${e}`),0;if(o.data||(this.fontCache.has(o.url)?o.data=this.fontCache.get(o.url):(o.data=this.fetchFontSync(o.url),o.data&&this.fontCache.set(o.url,o.data))),!o.data)return this.logger.warn(te,ne,`Failed to load font: ${o.url}`),0;const a=o.data;if(0!==t)return this.logger.debug(te,ne,`Table ${t} requested - returning 0 to request whole file`),0;if(0===n||r({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,n){if(1===e.length)return e[0];const r=e.filter(e=>(e.italic??!1)===n),o=r.length>0?r:e;let a=o[0],i=Math.abs((a.weight??400)-t);for(const e of o){const n=e.weight??400,r=Math.abs(n-t);if(r=500?n>r&&(a=e):n{this.memoryManager.checkLeaks()},1e4)),this.logger.debug(oe,ae,"initialize"),this.logger.perf(oe,ae,"Initialize","Begin","General"),this.pdfiumModule.PDFiumExt_Init(),this.logger.perf(oe,ae,"Initialize","End","General"),o&&(this.fontFallbackManager=new re(o,this.logger),this.fontFallbackManager.initialize(this.pdfiumModule),this.logger.info(oe,ae,"Font fallback system enabled"))}destroy(){return this.logger.debug(oe,ae,"destroy"),this.logger.perf(oe,ae,"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(oe,ae,"Destroy","End","General"),t.resolve(!0)}getFontFallbackManager(){return this.fontFallbackManager}withWString(e,t){const n=2*(e.length+1),r=this.memoryManager.malloc(n);try{return this.pdfiumModule.pdfium.stringToUTF16(e,r,n),t(r)}finally{this.memoryManager.free(r)}}withFloatArray(e,t){const n=e??[],r=4*n.length,o=r?this.memoryManager.malloc(r):0;try{if(r)for(let e=0;e{const n=r[e];if(void 0===n)return;if(null===n)return void(this.setMetaText(o.docPtr,t,null)||(i=!1));const a=p(n);this.setMetaText(o.docPtr,t,a)||(i=!1)};if(s("creationDate","CreationDate"),s("modificationDate","ModDate"),void 0!==r.trapped&&(this.setMetaTrapped(o.docPtr,r.trapped??null)||(i=!1)),void 0!==r.custom)for(const[e,t]of Object.entries(r.custom))W(e)?this.setMetaText(o.docPtr,e,t??null)||(i=!1):this.logger.warn(oe,ae,"Invalid custom metadata key skipped",e);return this.logger.perf(oe,ae,"SetMetadata","End",e.id),i?t.resolve(!0):t.reject({code:n.Unknown,message:"one or more metadata fields could not be written"})}getDocPermissions(e){this.logger.debug(oe,ae,"getDocPermissions",e),this.logger.perf(oe,ae,"getDocPermissions","Begin",e.id);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(oe,ae,"getDocPermissions","End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});const o=this.pdfiumModule.FPDF_GetDocPermissions(r.docPtr);return t.resolve(o)}getDocUserPermissions(e){this.logger.debug(oe,ae,"getDocUserPermissions",e),this.logger.perf(oe,ae,"getDocUserPermissions","Begin",e.id);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(oe,ae,"getDocUserPermissions","End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});const o=this.pdfiumModule.FPDF_GetDocUserPermissions(r.docPtr);return t.resolve(o)}getSignatures(e){this.logger.debug(oe,ae,"getSignatures",e),this.logger.perf(oe,ae,"GetSignatures","Begin",e.id);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(oe,ae,"GetSignatures","End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});const o=[],a=this.pdfiumModule.FPDF_GetSignatureCount(r.docPtr);for(let e=0;ethis.pdfiumModule.FPDFSignatureObj_GetContents(t,e,n)),a=z(this.pdfiumModule.pdfium,(e,n)=>4*this.pdfiumModule.FPDFSignatureObj_GetByteRange(t,e,n)),i=z(this.pdfiumModule.pdfium,(e,n)=>this.pdfiumModule.FPDFSignatureObj_GetSubFilter(t,e,n)),s=U(this.pdfiumModule.pdfium,(e,n)=>this.pdfiumModule.FPDFSignatureObj_GetReason(t,e,n),this.pdfiumModule.pdfium.UTF16ToString),u=U(this.pdfiumModule.pdfium,(e,n)=>this.pdfiumModule.FPDFSignatureObj_GetTime(t,e,n),this.pdfiumModule.pdfium.UTF8ToString),m=this.pdfiumModule.FPDFSignatureObj_GetDocMDPPermission(t);o.push({contents:n,byteRange:a,subFilter:i,reason:s,time:u,docMDP:m})}return this.logger.perf(oe,ae,"GetSignatures","End",e.id),t.resolve(o)}getBookmarks(e){this.logger.debug(oe,ae,"getBookmarks",e),this.logger.perf(oe,ae,"GetBookmarks","Begin",e.id);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(oe,ae,"getBookmarks","End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});const o=this.readPdfBookmarks(r.docPtr,0);return this.logger.perf(oe,ae,"GetBookmarks","End",e.id),t.resolve({bookmarks:o})}setBookmarks(e,r){this.logger.debug(oe,ae,"setBookmarks",e,r),this.logger.perf(oe,ae,"SetBookmarks","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(oe,ae,"SetBookmarks","End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});if(!this.pdfiumModule.EPDFBookmark_Clear(o.docPtr))return this.logger.perf(oe,ae,"SetBookmarks","End",e.id),t.reject({code:n.Unknown,message:"failed to clear existing bookmarks"});const a=(e,t)=>{var n;for(const r of t){const t=this.withWString(r.title??"",t=>this.pdfiumModule.EPDFBookmark_AppendChild(o.docPtr,e,t));if(!t)return!1;if(r.target){if(!this.applyBookmarkTarget(o.docPtr,t,r.target))return!1}if(null==(n=r.children)?void 0:n.length){if(!a(t,r.children))return!1}}return!0},i=a(0,r);return this.logger.perf(oe,ae,"SetBookmarks","End",e.id),i?t.resolve(!0):t.reject({code:n.Unknown,message:"failed to build bookmark tree"})}deleteBookmarks(e){this.logger.debug(oe,ae,"deleteBookmarks",e),this.logger.perf(oe,ae,"DeleteBookmarks","Begin",e.id);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(oe,ae,"DeleteBookmarks","End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});const o=this.pdfiumModule.EPDFBookmark_Clear(r.docPtr);return this.logger.perf(oe,ae,"DeleteBookmarks","End",e.id),o?t.resolve(!0):t.reject({code:n.Unknown,message:"failed to clear bookmarks"})}renderPageRaw(e,t,n){this.logger.debug(oe,ae,"renderPage",e,t,n),this.logger.perf(oe,ae,"RenderPage","Begin",`${e.id}-${t.index}`);const r={origin:{x:0,y:0},size:t.size},o=this.renderRectEncoded(e,t,r,n);return this.logger.perf(oe,ae,"RenderPage","End",`${e.id}-${t.index}`),o}renderPageRect(e,t,n,r){this.logger.debug(oe,ae,"renderPageRect",e,t,n,r),this.logger.perf(oe,ae,"RenderPageRect","Begin",`${e.id}-${t.index}`);const o=this.renderRectEncoded(e,t,n,r);return this.logger.perf(oe,ae,"RenderPageRect","End",`${e.id}-${t.index}`),o}getPageAnnotations(e,r){this.logger.debug(oe,ae,"getPageAnnotations",e,r),this.logger.perf(oe,ae,"GetPageAnnotations","Begin",`${e.id}-${r.index}`);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(oe,ae,"GetPageAnnotations","End",`${e.id}-${r.index}`),t.reject({code:n.DocNotOpen,message:"document does not open"});const a=this.readPageAnnotations(e,o,r);return this.logger.perf(oe,ae,"GetPageAnnotations","End",`${e.id}-${r.index}`),this.logger.debug(oe,ae,"GetPageAnnotations",`${e.id}-${r.index}`,a),t.resolve(a)}createPageAnnotation(e,r,s,u){this.logger.debug(oe,ae,"createPageAnnotation",e,r,s),this.logger.perf(oe,ae,"CreatePageAnnotation","Begin",`${e.id}-${r.index}`);const m=this.cache.getContext(e.id);if(!m)return this.logger.perf(oe,ae,"CreatePageAnnotation","End",`${e.id}-${r.index}`),t.reject({code:n.DocNotOpen,message:"document does not open"});const F=m.acquirePage(r.index),l=this.pdfiumModule.EPDFPage_CreateAnnot(F.pagePtr,s.type);if(!l)return this.logger.perf(oe,ae,"CreatePageAnnotation","End",`${e.id}-${r.index}`),F.release(),t.reject({code:n.CantCreateAnnot,message:"can not create annotation with specified type"});if(o(s.id)||(s.id=a()),!this.setAnnotString(l,"NM",s.id))return this.pdfiumModule.FPDFPage_CloseAnnot(l),F.release(),t.reject({code:n.CantSetAnnotString,message:"can not set the name of the annotation"});if(!this.setPageAnnoRect(e,r,l,s.rect))return this.pdfiumModule.FPDFPage_CloseAnnot(l),F.release(),this.logger.perf(oe,ae,"CreatePageAnnotation","End",`${e.id}-${r.index}`),t.reject({code:n.CantSetAnnotRect,message:"can not set the rect of the annotation"});const d=this.prepareAnnotationForSave(s);let P=!1;switch(d.type){case i.INK:P=this.addInkStroke(e,r,F.pagePtr,l,d);break;case i.STAMP:P=this.addStampContent(e,m.docPtr,r,F.pagePtr,l,d,null==u?void 0:u.imageData);break;case i.TEXT:P=this.addTextContent(e,r,F.pagePtr,l,d);break;case i.FREETEXT:P=this.addFreeTextContent(e,r,F.pagePtr,l,d);break;case i.LINE:P=this.addLineContent(e,r,F.pagePtr,l,d);break;case i.POLYLINE:case i.POLYGON:P=this.addPolyContent(e,r,F.pagePtr,l,d);break;case i.CIRCLE:case i.SQUARE:P=this.addShapeContent(e,r,F.pagePtr,l,d);break;case i.UNDERLINE:case i.STRIKEOUT:case i.SQUIGGLY:case i.HIGHLIGHT:P=this.addTextMarkupContent(e,r,F.pagePtr,l,d);break;case i.LINK:P=this.addLinkContent(e,r,m.docPtr,F.pagePtr,l,d);break;case i.REDACT:P=this.addRedactContent(e,r,F.pagePtr,l,d)}return P?(void 0!==s.blendMode?this.pdfiumModule.EPDFAnnot_GenerateAppearanceWithBlend(l,s.blendMode):this.pdfiumModule.EPDFAnnot_GenerateAppearance(l),this.pdfiumModule.FPDFPage_GenerateContent(F.pagePtr),this.pdfiumModule.FPDFPage_CloseAnnot(l),F.release(),this.logger.perf(oe,ae,"CreatePageAnnotation","End",`${e.id}-${r.index}`),t.resolve(s.id)):(this.pdfiumModule.FPDFPage_RemoveAnnot(F.pagePtr,l),F.release(),this.logger.perf(oe,ae,"CreatePageAnnotation","End",`${e.id}-${r.index}`),t.reject({code:n.CantSetAnnotContent,message:"can not add content of the annotation"}))}updatePageAnnotation(e,r,o){this.logger.debug(oe,ae,"updatePageAnnotation",e,r,o),this.logger.perf(oe,ae,"UpdatePageAnnotation","Begin",`${e.id}-${r.index}`);const a=this.cache.getContext(e.id);if(!a)return this.logger.perf(oe,ae,"UpdatePageAnnotation","End",`${e.id}-${r.index}`),t.reject({code:n.DocNotOpen,message:"document does not open"});const s=a.acquirePage(r.index),u=this.getAnnotationByName(s.pagePtr,o.id);if(!u)return s.release(),this.logger.perf(oe,ae,"UpdatePageAnnotation","End",`${e.id}-${r.index}`),t.reject({code:n.NotFound,message:"annotation not found"});if(!this.setPageAnnoRect(e,r,u,o.rect))return this.pdfiumModule.FPDFPage_CloseAnnot(u),s.release(),this.logger.perf(oe,ae,"UpdatePageAnnotation","End",`${e.id}-${r.index}`),t.reject({code:n.CantSetAnnotRect,message:"failed to move annotation"});const m=this.prepareAnnotationForSave(o);let F=!1;switch(m.type){case i.INK:if(!this.pdfiumModule.FPDFAnnot_RemoveInkList(u))break;F=this.addInkStroke(e,r,s.pagePtr,u,m);break;case i.STAMP:F=this.addStampContent(e,a.docPtr,r,s.pagePtr,u,m);break;case i.TEXT:F=this.addTextContent(e,r,s.pagePtr,u,m);break;case i.FREETEXT:F=this.addFreeTextContent(e,r,s.pagePtr,u,m);break;case i.CIRCLE:case i.SQUARE:F=this.addShapeContent(e,r,s.pagePtr,u,m);break;case i.LINE:F=this.addLineContent(e,r,s.pagePtr,u,m);break;case i.POLYGON:case i.POLYLINE:F=this.addPolyContent(e,r,s.pagePtr,u,m);break;case i.HIGHLIGHT:case i.UNDERLINE:case i.STRIKEOUT:case i.SQUIGGLY:F=this.addTextMarkupContent(e,r,s.pagePtr,u,m);break;case i.LINK:F=this.addLinkContent(e,r,a.docPtr,s.pagePtr,u,m);break;case i.REDACT:F=this.addRedactContent(e,r,s.pagePtr,u,m);break;default:F=!1}return F&&(void 0!==o.blendMode?this.pdfiumModule.EPDFAnnot_GenerateAppearanceWithBlend(u,o.blendMode):this.pdfiumModule.EPDFAnnot_GenerateAppearance(u),this.pdfiumModule.FPDFPage_GenerateContent(s.pagePtr)),this.pdfiumModule.FPDFPage_CloseAnnot(u),s.release(),this.logger.perf(oe,ae,"UpdatePageAnnotation","End",`${e.id}-${r.index}`),F?t.resolve(!0):t.reject({code:n.CantSetAnnotContent,message:"failed to update annotation"})}removePageAnnotation(e,r,o){this.logger.debug(oe,ae,"removePageAnnotation",e,r,o),this.logger.perf(oe,ae,"RemovePageAnnotation","Begin",`${e.id}-${r.index}`);const a=this.cache.getContext(e.id);if(!a)return this.logger.perf(oe,ae,"RemovePageAnnotation","End",`${e.id}-${r.index}`),t.reject({code:n.DocNotOpen,message:"document does not open"});const i=a.acquirePage(r.index);let s=!1;return s=this.removeAnnotationByName(i.pagePtr,o.id),s?(s=this.pdfiumModule.FPDFPage_GenerateContent(i.pagePtr),s||this.logger.error(oe,ae,"FPDFPage_GenerateContent Failed",`${e.id}-${r.index}`)):this.logger.error(oe,ae,"FPDFPage_RemoveAnnot Failed",`${e.id}-${r.index}`),i.release(),this.logger.perf(oe,ae,"RemovePageAnnotation","End",`${e.id}-${r.index}`),t.resolve(s)}getPageTextRects(e,r){this.logger.debug(oe,ae,"getPageTextRects",e,r),this.logger.perf(oe,ae,"GetPageTextRects","Begin",`${e.id}-${r.index}`);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(oe,ae,"GetPageTextRects","End",`${e.id}-${r.index}`),t.reject({code:n.DocNotOpen,message:"document does not open"});const a=o.acquirePage(r.index),i=this.pdfiumModule.FPDFText_LoadPage(a.pagePtr),s=this.readPageTextRects(r,a.docPtr,a.pagePtr,i);return this.pdfiumModule.FPDFText_ClosePage(i),a.release(),this.logger.perf(oe,ae,"GetPageTextRects","End",`${e.id}-${r.index}`),t.resolve(s)}renderThumbnailRaw(e,r,o){const{scaleFactor:a=1,...i}=o??{};this.logger.debug(oe,ae,"renderThumbnail",e,r,o),this.logger.perf(oe,ae,"RenderThumbnail","Begin",`${e.id}-${r.index}`);if(!this.cache.getContext(e.id))return this.logger.perf(oe,ae,"RenderThumbnail","End",`${e.id}-${r.index}`),t.reject({code:n.DocNotOpen,message:"document does not open"});const s=this.renderPageRaw(e,r,{scaleFactor:Math.max(a,.5),...i});return this.logger.perf(oe,ae,"RenderThumbnail","End",`${e.id}-${r.index}`),s}getAttachments(e){this.logger.debug(oe,ae,"getAttachments",e),this.logger.perf(oe,ae,"GetAttachments","Begin",e.id);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(oe,ae,"GetAttachments","End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});const o=[],a=this.pdfiumModule.FPDFDoc_GetAttachmentCount(r.docPtr);for(let e=0;ethis.pdfiumModule.FPDFDoc_AddAttachment(o.docPtr,e));if(!m)return this.logger.perf(oe,ae,"AddAttachment","End",e.id),t.reject({code:n.Unknown,message:`An attachment named "${a}" already exists`});this.withWString(i,e=>this.pdfiumModule.EPDFAttachment_SetDescription(m,e)),this.pdfiumModule.EPDFAttachment_SetSubtype(m,s);const F=u instanceof Uint8Array?u:new Uint8Array(u),l=F.byteLength,d=this.memoryManager.malloc(l);try{this.pdfiumModule.pdfium.HEAPU8.set(F,d);if(!this.pdfiumModule.FPDFAttachment_SetFile(m,o.docPtr,d,l))return this.logger.perf(oe,ae,"AddAttachment","End",e.id),t.reject({code:n.Unknown,message:"failed to write attachment bytes"})}finally{this.memoryManager.free(d)}return this.logger.perf(oe,ae,"AddAttachment","End",e.id),t.resolve(!0)}removeAttachment(e,r){this.logger.debug(oe,ae,"deleteAttachment",e,r),this.logger.perf(oe,ae,"DeleteAttachment","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(oe,ae,"DeleteAttachment","End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});const a=this.pdfiumModule.FPDFDoc_GetAttachmentCount(o.docPtr);if(r.index<0||r.index>=a)return this.logger.perf(oe,ae,"DeleteAttachment","End",e.id),t.reject({code:n.Unknown,message:`attachment index ${r.index} out of range`});const i=this.pdfiumModule.FPDFDoc_DeleteAttachment(o.docPtr,r.index);return this.logger.perf(oe,ae,"DeleteAttachment","End",e.id),i?t.resolve(!0):t.reject({code:n.Unknown,message:"failed to delete attachment"})}readAttachmentContent(e,r){this.logger.debug(oe,ae,"readAttachmentContent",e,r),this.logger.perf(oe,ae,"ReadAttachmentContent","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(oe,ae,"ReadAttachmentContent","End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});const a=this.pdfiumModule.FPDFDoc_GetAttachment(o.docPtr,r.index),i=this.memoryManager.malloc(4);if(!this.pdfiumModule.FPDFAttachment_GetFile(a,0,0,i))return this.memoryManager.free(i),this.logger.perf(oe,ae,"ReadAttachmentContent","End",e.id),t.reject({code:n.CantReadAttachmentSize,message:"can not read attachment size"});const s=this.pdfiumModule.pdfium.getValue(i,"i32")>>>0,u=this.memoryManager.malloc(s);if(!this.pdfiumModule.FPDFAttachment_GetFile(a,u,s,i))return this.memoryManager.free(i),this.memoryManager.free(u),this.logger.perf(oe,ae,"ReadAttachmentContent","End",e.id),t.reject({code:n.CantReadAttachmentContent,message:"can not read attachment content"});const m=new ArrayBuffer(s),F=new DataView(m);for(let e=0;e{(a.get(e.pageIndex)??a.set(e.pageIndex,[]).get(e.pageIndex)).push({slice:e,pos:t})});for(const[e,t]of a){const r=o.acquirePage(e),a=r.getTextPage();for(const{slice:e,pos:r}of t){const t=this.memoryManager.malloc(2*(e.charCount+1));this.pdfiumModule.FPDFText_GetText(a,e.charIndex,e.charCount,t),n[r]=u(this.pdfiumModule.pdfium.UTF16ToString(t)),this.memoryManager.free(t)}r.release()}return this.logger.perf(oe,ae,"GetTextSlices","End",e.id),t.resolve(n)}catch(r){return this.logger.error(oe,ae,"getTextSlices error",r),this.logger.perf(oe,ae,"GetTextSlices","End",e.id),t.reject({code:n.Unknown,message:String(r)})}}merge(e){this.logger.debug(oe,ae,"merge",e);const r=e.map(e=>e.id).join(".");this.logger.perf(oe,ae,"Merge","Begin",r);const o=this.pdfiumModule.FPDF_CreateNewDocument();if(!o)return this.logger.perf(oe,ae,"Merge","End",r),t.reject({code:n.CantCreateNewDoc,message:"can not create new document"});const a=[];for(const i of e.reverse()){const e=new Uint8Array(i.content),s=e.length,u=this.memoryManager.malloc(s);this.pdfiumModule.pdfium.HEAPU8.set(e,u);const m=this.pdfiumModule.FPDF_LoadMemDocument(u,s,"");if(!m){const e=this.pdfiumModule.FPDF_GetLastError();this.logger.error(oe,ae,`FPDF_LoadMemDocument failed with ${e}`),this.memoryManager.free(u);for(const e of a)this.pdfiumModule.FPDF_CloseDocument(e.docPtr),this.memoryManager.free(e.filePtr);return this.logger.perf(oe,ae,"Merge","End",r),t.reject({code:e,message:"FPDF_LoadMemDocument failed"})}if(a.push({filePtr:u,docPtr:m}),!this.pdfiumModule.FPDF_ImportPages(o,m,"",0)){this.pdfiumModule.FPDF_CloseDocument(o);for(const e of a)this.pdfiumModule.FPDF_CloseDocument(e.docPtr),this.memoryManager.free(e.filePtr);return this.logger.perf(oe,ae,"Merge","End",r),t.reject({code:n.CantImportPages,message:"can not import pages to new document"})}}const i=this.saveDocument(o);this.pdfiumModule.FPDF_CloseDocument(o);for(const e of a)this.pdfiumModule.FPDF_CloseDocument(e.docPtr),this.memoryManager.free(e.filePtr);const s={id:`${Math.random()}`,content:i};return this.logger.perf(oe,ae,"Merge","End",r),t.resolve(s)}mergePages(e){const r=e.map(e=>`${e.docId}:${e.pageIndices.join(",")}`).join("|");this.logger.debug(oe,ae,"mergePages",e),this.logger.perf(oe,ae,"MergePages","Begin",r);const o=this.pdfiumModule.FPDF_CreateNewDocument();if(!o)return this.logger.perf(oe,ae,"MergePages","End",r),t.reject({code:n.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(oe,ae,`Document ${t.docId} is not open, skipping`);continue}const n=this.pdfiumModule.FPDF_GetPageCount(e.docPtr),r=t.pageIndices.filter(e=>e>=0&&ee+1).join(",");try{if(!this.pdfiumModule.FPDF_ImportPages(o,e.docPtr,a,0))throw new Error(`Failed to import pages ${a} from document ${t.docId}`)}finally{}}const n=this.saveDocument(o),a={id:`${Math.random()}`,content:n};return this.logger.perf(oe,ae,"MergePages","End",r),t.resolve(a)}catch(e){return this.logger.error(oe,ae,"mergePages failed",e),this.logger.perf(oe,ae,"MergePages","End",r),t.reject({code:n.CantImportPages,message:e instanceof Error?e.message:"Failed to merge pages"})}finally{o&&this.pdfiumModule.FPDF_CloseDocument(o)}}setDocumentEncryption(e,r,o,a){this.logger.debug(oe,ae,"setDocumentEncryption",e,a);const i=this.cache.getContext(e.id);if(!i)return t.reject({code:n.DocNotOpen,message:"document does not open"});const s=this.pdfiumModule.EPDF_SetEncryption(i.docPtr,r,o,a);return t.resolve(s)}removeEncryption(e){this.logger.debug(oe,ae,"removeEncryption",e);const r=this.cache.getContext(e.id);if(!r)return t.reject({code:n.DocNotOpen,message:"document does not open"});const o=this.pdfiumModule.EPDF_RemoveEncryption(r.docPtr);return t.resolve(o)}unlockOwnerPermissions(e,r){this.logger.debug(oe,ae,"unlockOwnerPermissions",e.id);const o=this.cache.getContext(e.id);if(!o)return t.reject({code:n.DocNotOpen,message:"document does not open"});const a=this.pdfiumModule.EPDF_UnlockOwnerPermissions(o.docPtr,r);return t.resolve(a)}isEncrypted(e){this.logger.debug(oe,ae,"isEncrypted",e.id);const r=this.cache.getContext(e.id);if(!r)return t.reject({code:n.DocNotOpen,message:"document does not open"});const o=this.pdfiumModule.EPDF_IsEncrypted(r.docPtr);return t.resolve(o)}isOwnerUnlocked(e){this.logger.debug(oe,ae,"isOwnerUnlocked",e.id);const r=this.cache.getContext(e.id);if(!r)return t.reject({code:n.DocNotOpen,message:"document does not open"});const o=this.pdfiumModule.EPDF_IsOwnerUnlocked(r.docPtr);return t.resolve(o)}saveAsCopy(e){this.logger.debug(oe,ae,"saveAsCopy",e),this.logger.perf(oe,ae,"SaveAsCopy","Begin",e.id);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(oe,ae,"SaveAsCopy","End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});const o=this.saveDocument(r.docPtr);return this.logger.perf(oe,ae,"SaveAsCopy","End",e.id),t.resolve(o)}closeDocument(e){this.logger.debug(oe,ae,"closeDocument",e),this.logger.perf(oe,ae,"CloseDocument","Begin",e.id);const n=this.cache.getContext(e.id);return n?(n.dispose(),this.logger.perf(oe,ae,"CloseDocument","End",e.id),t.resolve(!0)):t.resolve(!0)}closeAllDocuments(){return this.logger.debug(oe,ae,"closeAllDocuments"),this.logger.perf(oe,ae,"CloseAllDocuments","Begin"),this.cache.closeAllDocuments(),this.logger.perf(oe,ae,"CloseAllDocuments","End"),t.resolve(!0)}addTextContent(e,t,n,r,o){return!!this.setAnnotationIcon(r,o.icon||m.Comment)&&(!(o.state&&!this.setAnnotString(r,"State",o.state))&&(!(o.stateModel&&!this.setAnnotString(r,"StateModel",o.stateModel))&&(!(!o.flags&&!this.setAnnotationFlags(r,["print","noZoom","noRotate"]))&&this.applyBaseAnnotationProperties(e,t,n,r,o))))}addFreeTextContent(e,t,n,r,o){if(!this.setBorderStyle(r,F.SOLID,0))return!1;if(!this.setAnnotationOpacity(r,o.opacity??1))return!1;if(!this.setAnnotationTextAlignment(r,o.textAlign))return!1;if(!this.setAnnotationVerticalAlignment(r,o.verticalAlign))return!1;if(!this.setAnnotationDefaultAppearance(r,o.fontFamily,o.fontSize,o.fontColor))return!1;if(o.intent&&!this.setAnnotIntent(r,o.intent))return!1;const a=o.color??o.backgroundColor;if(a&&"transparent"!==a){if(!this.setAnnotationColor(r,a??"#FFFFFF",l.Color))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(r,l.Color))return!1;return this.applyBaseAnnotationProperties(e,t,n,r,o)}addInkStroke(e,t,n,r,o){if(!this.setBorderStyle(r,F.SOLID,o.strokeWidth))return!1;if(!this.setInkList(e,t,r,o.inkList))return!1;if(!this.setAnnotationOpacity(r,o.opacity??1))return!1;const a=o.strokeColor??o.color??"#FFFF00";return!!this.setAnnotationColor(r,a,l.Color)&&this.applyBaseAnnotationProperties(e,t,n,r,o)}addLineContent(e,t,n,r,o){var a,i;if(!this.setLinePoints(e,t,r,o.linePoints.start,o.linePoints.end))return!1;if(!this.setLineEndings(r,(null==(a=o.lineEndings)?void 0:a.start)??d.None,(null==(i=o.lineEndings)?void 0:i.end)??d.None))return!1;if(!this.setBorderStyle(r,o.strokeStyle,o.strokeWidth))return!1;if(!this.setBorderDashPattern(r,o.strokeDashArray??[]))return!1;if(o.intent&&!this.setAnnotIntent(r,o.intent))return!1;if(o.color&&"transparent"!==o.color){if(!this.setAnnotationColor(r,o.color??"#FFFF00",l.InteriorColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(r,l.InteriorColor))return!1;return!!this.setAnnotationOpacity(r,o.opacity??1)&&(!!this.setAnnotationColor(r,o.strokeColor??"#FFFF00",l.Color)&&this.applyBaseAnnotationProperties(e,t,n,r,o))}addPolyContent(e,t,n,r,o){var a,s;if(o.type===i.POLYLINE&&!this.setLineEndings(r,(null==(a=o.lineEndings)?void 0:a.start)??d.None,(null==(s=o.lineEndings)?void 0:s.end)??d.None))return!1;if(!this.setPdfAnnoVertices(e,t,r,o.vertices))return!1;if(!this.setBorderStyle(r,o.strokeStyle,o.strokeWidth))return!1;if(!this.setBorderDashPattern(r,o.strokeDashArray??[]))return!1;if(o.intent&&!this.setAnnotIntent(r,o.intent))return!1;if(o.color&&"transparent"!==o.color){if(!this.setAnnotationColor(r,o.color??"#FFFF00",l.InteriorColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(r,l.InteriorColor))return!1;return!!this.setAnnotationOpacity(r,o.opacity??1)&&(!!this.setAnnotationColor(r,o.strokeColor??"#FFFF00",l.Color)&&this.applyBaseAnnotationProperties(e,t,n,r,o))}addLinkContent(e,t,n,r,o,a){const i=a.strokeStyle??F.UNDERLINE,s=a.strokeWidth??2;return!!this.setBorderStyle(o,i,s)&&(!(a.strokeDashArray&&!this.setBorderDashPattern(o,a.strokeDashArray))&&(!(a.strokeColor&&!this.setAnnotationColor(o,a.strokeColor,l.Color))&&(!(a.target&&!this.applyLinkTarget(n,o,a.target))&&this.applyBaseAnnotationProperties(e,t,r,o,a))))}addShapeContent(e,t,n,r,o){if(!this.setBorderStyle(r,o.strokeStyle,o.strokeWidth))return!1;if(!this.setBorderDashPattern(r,o.strokeDashArray??[]))return!1;if(o.color&&"transparent"!==o.color){if(!this.setAnnotationColor(r,o.color??"#FFFF00",l.InteriorColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(r,l.InteriorColor))return!1;return!!this.setAnnotationOpacity(r,o.opacity??1)&&(!!this.setAnnotationColor(r,o.strokeColor??"#FFFF00",l.Color)&&this.applyBaseAnnotationProperties(e,t,n,r,o))}addTextMarkupContent(e,t,n,r,o){if(!this.syncQuadPointsAnno(e,t,r,o.segmentRects))return!1;if(!this.setAnnotationOpacity(r,o.opacity??1))return!1;const a=o.strokeColor??o.color??"#FFFF00";return!!this.setAnnotationColor(r,a,l.Color)&&this.applyBaseAnnotationProperties(e,t,n,r,o)}addRedactContent(e,t,n,r,o){if(!this.syncQuadPointsAnno(e,t,r,o.segmentRects))return!1;if(!this.setAnnotationOpacity(r,o.opacity??1))return!1;if(o.color&&"transparent"!==o.color){if(!this.setAnnotationColor(r,o.color,l.InteriorColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(r,l.InteriorColor))return!1;if(o.overlayColor&&"transparent"!==o.overlayColor){if(!this.setAnnotationColor(r,o.overlayColor,l.OverlayColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(r,l.OverlayColor))return!1;if(o.strokeColor&&"transparent"!==o.strokeColor){if(!this.setAnnotationColor(r,o.strokeColor,l.Color))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(r,l.Color))return!1;return!!this.setOverlayText(r,o.overlayText)&&(!(void 0!==o.overlayTextRepeat&&!this.setOverlayTextRepeat(r,o.overlayTextRepeat))&&(!!(void 0===o.fontFamily&&void 0===o.fontSize||this.setAnnotationDefaultAppearance(r,o.fontFamily??P.Helvetica,o.fontSize??12,o.fontColor??"#000000"))&&(!(void 0!==o.textAlign&&!this.setAnnotationTextAlignment(r,o.textAlign))&&this.applyBaseAnnotationProperties(e,t,n,r,o))))}addStampContent(e,t,n,r,o,a,i){if(a.icon&&!this.setAnnotationIcon(o,a.icon))return!1;if(a.subject&&!this.setAnnotString(o,"Subj",a.subject))return!1;if(i){for(let e=this.pdfiumModule.FPDFAnnot_GetObjectCount(o)-1;e>=0;e--)this.pdfiumModule.FPDFAnnot_RemoveObject(o,e);if(!this.addImageObject(e,t,n,r,o,a.rect,i))return!1}return!!this.applyBaseAnnotationProperties(e,n,r,o,a)&&!!this.pdfiumModule.EPDFAnnot_UpdateAppearanceToRect(o,_.Cover)}addImageObject(e,t,n,r,o,a,i){const s=i.width*i.height,u=this.memoryManager.malloc(4*s);if(!u)return!1;for(let e=0;e>>0;return 0===t?null:2===t?"":U(this.pdfiumModule.pdfium,(t,n)=>this.pdfiumModule.EPDFCatalog_GetLanguage(e,t,n),this.pdfiumModule.pdfium.UTF16ToString,t)}readMetaText(e,t){if(!!!this.pdfiumModule.EPDF_HasMetaText(e,t))return null;const n=this.pdfiumModule.FPDF_GetMetaText(e,t,0,0);return 2===n?"":U(this.pdfiumModule.pdfium,(n,r)=>this.pdfiumModule.FPDF_GetMetaText(e,t,n,r),this.pdfiumModule.pdfium.UTF16ToString,n)}setMetaText(e,t,n){if(null==n||0===n.length){return!!this.pdfiumModule.EPDF_SetMetaText(e,t,0)}const r=2*(n.length+1),o=this.memoryManager.malloc(r);try{this.pdfiumModule.pdfium.stringToUTF16(n,o,r);return!!this.pdfiumModule.EPDF_SetMetaText(e,t,o)}finally{this.memoryManager.free(o)}}getMetaTrapped(e){const t=Number(this.pdfiumModule.EPDF_GetMetaTrapped(e));switch(t){case c.NotSet:case c.True:case c.False:case c.Unknown:return t;default:return c.Unknown}}setMetaTrapped(e,t){const n=null==t||void 0===t?c.NotSet:t;return!(n!==c.NotSet&&n!==c.True&&n!==c.False&&n!==c.Unknown)&&!!this.pdfiumModule.EPDF_SetMetaTrapped(e,n)}getMetaKeyCount(e,t){return 0|Number(this.pdfiumModule.EPDF_GetMetaKeyCount(e,t))}getMetaKeyName(e,t,n){const r=this.pdfiumModule.EPDF_GetMetaKeyName(e,t,n,0,0);return r?U(this.pdfiumModule.pdfium,(r,o)=>this.pdfiumModule.EPDF_GetMetaKeyName(e,t,n,r,o),this.pdfiumModule.pdfium.UTF8ToString,r):null}readAllMeta(e,t=!0){const n=this.getMetaKeyCount(e,t),r={};for(let o=0;othis.pdfiumModule.FPDFBookmark_GetTitle(t,e,n),this.pdfiumModule.pdfium.UTF16ToString),r=this.readPdfBookmarks(e,t);return{title:n,target:this.readPdfBookmarkTarget(e,()=>this.pdfiumModule.FPDFBookmark_GetAction(t),()=>this.pdfiumModule.FPDFBookmark_GetDest(e,t)),children:r}}readPageTextRects(e,t,n,r){const o=this.pdfiumModule.FPDFText_CountRects(r,0,-1),a=[];for(let t=0;t=0){y=this.pdfiumModule.FPDFText_GetFontSize(r,A);const e=this.pdfiumModule.FPDFText_GetFontInfo(r,A,0,0,0)+1,t=this.memoryManager.malloc(e),n=this.memoryManager.malloc(4);this.pdfiumModule.FPDFText_GetFontInfo(r,A,t,e,n),E=this.pdfiumModule.pdfium.UTF8ToString(t),this.memoryManager.free(t),this.memoryManager.free(n)}const M={content:f,rect:h,font:{family:E,size:y}};a.push(M)}return a}getPageGeometry(e,r){const o="getPageGeometry";this.logger.perf(oe,ae,o,"Begin",e.id);const a=this.cache.getContext(e.id);if(!a)return this.logger.perf(oe,ae,o,"End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});const i=a.acquirePage(r.index),s=i.getTextPage(),u=this.pdfiumModule.FPDFText_CountChars(s),m=[];for(let e=0;e{if(null===d||null===P||null===c||null===g)return;const t=e-l;if(t<=0)return;const n=this.memoryManager.malloc(2*(t+1));this.pdfiumModule.FPDFText_GetText(s,l,t,n);const r=u(this.pdfiumModule.pdfium.UTF16ToString(n));this.memoryManager.free(n),F.push({text:r,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:P,fontSize:_,color:c,charIndex:l,charCount:t})},D=this.memoryManager.malloc(4),b=this.memoryManager.malloc(4),p=this.memoryManager.malloc(4),f=this.memoryManager.malloc(4),A=this.memoryManager.malloc(16),E=this.memoryManager.malloc(4),y=this.memoryManager.malloc(4),M=this.memoryManager.malloc(4),G=this.memoryManager.malloc(4),S=this.memoryManager.malloc(4);for(let e=0;e.01||a!==c.red||u!==c.green||m!==c.blue)&&(h(e),d=n,P=C,_=o,c={red:a,green:u,blue:m,alpha:F},l=e,g=null),this.pdfiumModule.FPDFText_GetLooseCharBox(s,e,A)){const e=this.pdfiumModule.pdfium.getValue(A,"float"),t=this.pdfiumModule.pdfium.getValue(A+4,"float"),n=this.pdfiumModule.pdfium.getValue(A+8,"float"),o=this.pdfiumModule.pdfium.getValue(A+12,"float");if(e!==n&&t!==o){this.pdfiumModule.FPDF_PageToDevice(i.pagePtr,0,0,r.size.width,r.size.height,0,e,t,E,y),this.pdfiumModule.FPDF_PageToDevice(i.pagePtr,0,0,r.size.width,r.size.height,0,n,o,M,G);const a=this.pdfiumModule.pdfium.getValue(E,"i32"),s=this.pdfiumModule.pdfium.getValue(y,"i32"),u=this.pdfiumModule.pdfium.getValue(M,"i32"),m=this.pdfiumModule.pdfium.getValue(G,"i32"),F=Math.min(a,u),l=Math.min(s,m),d=Math.abs(u-a),P=Math.abs(m-s);null===g?g={minX:F,minY:l,maxX:F+d,maxY:l+P}:(g.minX=Math.min(g.minX,F),g.minY=Math.min(g.minY,l),g.maxX=Math.max(g.maxX,F+d),g.maxY=Math.max(g.maxY,l+P))}}}return h(m),[D,b,p,f,A,E,y,M,G,S].forEach(e=>this.memoryManager.free(e)),i.release(),this.logger.perf(oe,ae,o,"End",e.id),t.resolve({runs:F})}readFontInfoFromTextObject(e,t){const n=this.pdfiumModule.FPDFTextObj_GetFont(e);let r="",o="",a=400,i=!1,s=!1,u=!1;if(n){const e=this.pdfiumModule.FPDFFont_GetBaseFontName(n,0,0);if(e>0){const t=this.memoryManager.malloc(e+1);this.pdfiumModule.FPDFFont_GetBaseFontName(n,t,e+1),r=this.pdfiumModule.pdfium.UTF8ToString(t),this.memoryManager.free(t)}const m=this.pdfiumModule.FPDFFont_GetFamilyName(n,0,0);if(m>0){const e=this.memoryManager.malloc(m+1);this.pdfiumModule.FPDFFont_GetFamilyName(n,e,m+1),o=this.pdfiumModule.pdfium.UTF8ToString(e),this.memoryManager.free(e)}if(a=this.pdfiumModule.FPDFFont_GetWeight(n),u=0!==this.pdfiumModule.FPDFFont_GetIsEmbedded(n),this.pdfiumModule.FPDFFont_GetItalicAngle(n,t)){i=0!==this.pdfiumModule.pdfium.getValue(t,"i32")}s=!!(1&this.pdfiumModule.FPDFFont_GetFlags(n))}return{name:r,familyName:o,weight:a,italic:i,monospaced:s,embedded:u}}readGlyphInfo(e,t,n,r){const o=this.memoryManager.malloc(4),a=this.memoryManager.malloc(4),i=this.memoryManager.malloc(4),s=this.memoryManager.malloc(4),u=this.memoryManager.malloc(16),m=this.memoryManager.malloc(8),F=this.memoryManager.malloc(8),l=this.memoryManager.malloc(8),d=this.memoryManager.malloc(8),P=[u,o,a,i,s,m,F,l,d];let _,c,g=0,h=0,D=0,b=0,p=!1;if(this.pdfiumModule.FPDFText_GetLooseCharBox(n,r,u)){const f=this.pdfiumModule.pdfium.getValue(u,"float"),A=this.pdfiumModule.pdfium.getValue(u+4,"float"),E=this.pdfiumModule.pdfium.getValue(u+8,"float"),y=this.pdfiumModule.pdfium.getValue(u+12,"float");if(f===E||A===y)return P.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,f,A,o,a),this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,E,y,i,s);const M=this.pdfiumModule.pdfium.getValue(o,"i32"),G=this.pdfiumModule.pdfium.getValue(a,"i32"),S=this.pdfiumModule.pdfium.getValue(i,"i32"),C=this.pdfiumModule.pdfium.getValue(s,"i32");if(g=Math.min(M,S),h=Math.min(G,C),D=Math.max(1,Math.abs(S-M)),b=Math.max(1,Math.abs(C-G)),this.pdfiumModule.FPDFText_GetCharBox(n,r,m,F,l,d)){const n=this.pdfiumModule.pdfium.getValue(m,"double"),r=this.pdfiumModule.pdfium.getValue(F,"double"),u=this.pdfiumModule.pdfium.getValue(l,"double"),P=this.pdfiumModule.pdfium.getValue(d,"double");this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,n,P,o,a),this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,r,u,i,s);const g=this.pdfiumModule.pdfium.getValue(o,"i32"),h=this.pdfiumModule.pdfium.getValue(a,"i32"),D=this.pdfiumModule.pdfium.getValue(i,"i32"),b=this.pdfiumModule.pdfium.getValue(s,"i32");_={x:Math.min(g,D),y:Math.min(h,b)},c={width:Math.max(1,Math.abs(D-g)),height:Math.max(1,Math.abs(b-h))}}p=32===this.pdfiumModule.FPDFText_GetUnicode(n,r)}return P.forEach(e=>this.memoryManager.free(e)),{origin:{x:g,y:h},size:{width:D,height:b},..._&&{tightOrigin:_},...c&&{tightSize:c},...p&&{isSpace:p}}}getPageGlyphs(e,r){this.logger.debug(oe,ae,"getPageGlyphs",e,r),this.logger.perf(oe,ae,"getPageGlyphs","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(oe,ae,"getPageGlyphs","End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});const a=o.acquirePage(r.index),i=a.getTextPage(),s=this.pdfiumModule.FPDFText_CountChars(i),u=new Array(s);for(let e=0;e{const o=this.pdfiumModule.FPDFPage_GetAnnotCount(r.pagePtr),a=[];for(let i=0;i{const i=this.readPageAnnotation(e,t.docPtr,n,o,r);i&&a.push(i)});return a})}readPageAnnotationsRaw(e,t,n){const r=this.pdfiumModule.EPDFPage_GetAnnotCountRaw(t.docPtr,n.index);if(r<=0)return[];const o=[];for(let a=0;a({points:e.points.map(e=>this.rotatePointForSave(e,r,-t))}));return{...n,inkList:o}}case i.LINE:{const n=e;return{...n,linePoints:{start:this.rotatePointForSave(n.linePoints.start,r,-t),end:this.rotatePointForSave(n.linePoints.end,r,-t)}}}case i.POLYGON:{const n=e;return{...n,vertices:n.vertices.map(e=>this.rotatePointForSave(e,r,-t))}}case i.POLYLINE:{const n=e;return{...n,vertices:n.vertices.map(e=>this.rotatePointForSave(e,r,-t))}}default:return e}}readAnnotationColor(e,t=l.Color){const n=this.memoryManager.malloc(4),r=this.memoryManager.malloc(4),o=this.memoryManager.malloc(4);let a;return this.pdfiumModule.EPDFAnnot_GetColor(e,t,n,r,o)&&(a={red:255&this.pdfiumModule.pdfium.getValue(n,"i32"),green:255&this.pdfiumModule.pdfium.getValue(r,"i32"),blue:255&this.pdfiumModule.pdfium.getValue(o,"i32")}),this.memoryManager.free(n),this.memoryManager.free(r),this.memoryManager.free(o),a}getAnnotationColor(e,t=l.Color){const n=this.readAnnotationColor(e,t);return n?g(n):void 0}setAnnotationColor(e,t,n=l.Color){const r=h(t);return this.pdfiumModule.EPDFAnnot_SetColor(e,n,255&r.red,255&r.green,255&r.blue)}getAnnotationOpacity(e){const t=this.memoryManager.malloc(4),n=this.pdfiumModule.EPDFAnnot_GetOpacity(e,t)?this.pdfiumModule.pdfium.getValue(t,"i32"):255;return this.memoryManager.free(t),D(n)}setAnnotationOpacity(e,t){const n=w(t);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 n=this.pdfiumModule.pdfium.getValue(t,"float");return this.memoryManager.free(t),n}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 n=this.pdfiumModule.pdfium.getValue(t,"float");return this.memoryManager.free(t),n}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 n=this.pdfiumModule.pdfium.getValue(t,"float"),r=this.pdfiumModule.pdfium.getValue(t+4,"float"),o=this.pdfiumModule.pdfium.getValue(t+8,"float"),a=this.pdfiumModule.pdfium.getValue(t+12,"float");return this.memoryManager.free(t),0===n&&0===r&&0===o&&0===a?null:{left:n,top:r,right:o,bottom:a}}setAnnotUnrotatedRect(e,t,n,r){const o=Math.floor(r.origin.x),a=Math.floor(r.origin.y),i=Math.floor(r.origin.x+r.size.width),s=Math.floor(r.origin.y+r.size.height),u=this.convertDevicePointToPagePoint(e,t,{x:o,y:a}),m=this.convertDevicePointToPagePoint(e,t,{x:i,y:a}),F=this.convertDevicePointToPagePoint(e,t,{x:i,y:s}),l=this.convertDevicePointToPagePoint(e,t,{x:o,y:s});let d=Math.min(u.x,m.x,F.x,l.x),P=Math.max(u.x,m.x,F.x,l.x),_=Math.min(u.y,m.y,F.y,l.y),c=Math.max(u.y,m.y,F.y,l.y);d>P&&([d,P]=[P,d]),_>c&&([_,c]=[c,_]);const g=this.memoryManager.malloc(16),h=this.pdfiumModule.pdfium;h.setValue(g+0,d,"float"),h.setValue(g+4,c,"float"),h.setValue(g+8,P,"float"),h.setValue(g+12,_,"float");const D=this.pdfiumModule.EPDFAnnot_SetUnrotatedRect(n,g);return this.memoryManager.free(g),!!D}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 n=2*(t+1),r=this.memoryManager.malloc(n);this.pdfiumModule.EPDFAnnot_GetOverlayText(e,r,n);const o=this.pdfiumModule.pdfium.UTF16ToString(r);return this.memoryManager.free(r),o||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 t=this.memoryManager.malloc(4),n=this.memoryManager.malloc(4),r=this.memoryManager.malloc(4),o=this.memoryManager.malloc(4),a=this.memoryManager.malloc(4);if(!!!this.pdfiumModule.EPDFAnnot_GetDefaultAppearance(e,t,n,r,o,a))return void[t,n,r,o,a].forEach(e=>this.memoryManager.free(e));const i=this.pdfiumModule.pdfium,s=i.getValue(t,"i32"),u=i.getValue(n,"float"),m=255&i.getValue(r,"i32"),F=255&i.getValue(o,"i32"),l=255&i.getValue(a,"i32");return[t,n,r,o,a].forEach(e=>this.memoryManager.free(e)),{fontFamily:s,fontSize:u,fontColor:g({red:m,green:F,blue:l})}}setAnnotationDefaultAppearance(e,t,n,r){const o=t===P.Unknown?P.Helvetica:t,{red:a,green:i,blue:s}=h(r);return!!this.pdfiumModule.EPDFAnnot_SetDefaultAppearance(e,o,n,255&a,255&i,255&s)}getBorderStyle(e){const t=this.memoryManager.malloc(4);let n=0,r=F.UNKNOWN,o=!1;return r=this.pdfiumModule.EPDFAnnot_GetBorderStyle(e,t),n=this.pdfiumModule.pdfium.getValue(t,"float"),o=r!==F.UNKNOWN,this.memoryManager.free(t),{ok:o,style:r,width:n}}setBorderStyle(e,t,n){return this.pdfiumModule.EPDFAnnot_SetBorderStyle(e,t,n)}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,t){return this.pdfiumModule.EPDFAnnot_SetReplyType(e,t??b.Unknown)}getBorderEffect(e){const t=this.memoryManager.malloc(4),n=!!this.pdfiumModule.EPDFAnnot_GetBorderEffect(e,t),r=n?this.pdfiumModule.pdfium.getValue(t,"float"):0;return this.memoryManager.free(t),{ok:n,intensity:r}}getRectangleDifferences(e){const t=this.memoryManager.malloc(4),n=this.memoryManager.malloc(4),r=this.memoryManager.malloc(4),o=this.memoryManager.malloc(4),a=!!this.pdfiumModule.EPDFAnnot_GetRectangleDifferences(e,t,n,r,o),i=this.pdfiumModule.pdfium,s=i.getValue(t,"float"),u=i.getValue(n,"float"),m=i.getValue(r,"float"),F=i.getValue(o,"float");return this.memoryManager.free(t),this.memoryManager.free(n),this.memoryManager.free(r),this.memoryManager.free(o),{ok:a,left:s,top:u,right:m,bottom:F}}getAnnotationDate(e,t){const n=this.getAnnotString(e,t);return n?r(n):void 0}setAnnotationDate(e,t,n){const r=p(n);return this.setAnnotString(e,t,r)}getAttachmentDate(e,t){const n=this.getAttachmentString(e,t);return n?r(n):void 0}setAttachmentDate(e,t,n){const r=p(n);return this.setAttachmentString(e,t,r)}getBorderDashPattern(e){const t=this.pdfiumModule.EPDFAnnot_GetBorderDashPatternCount(e);if(0===t)return{ok:!1,pattern:[]};const n=this.memoryManager.malloc(4*t),r=!!this.pdfiumModule.EPDFAnnot_GetBorderDashPattern(e,n,t),o=[];if(r){const e=this.pdfiumModule.pdfium;for(let r=0;rNumber.isFinite(e)&&e>0?e:0).filter(e=>e>0);if(0===n.length)return this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(e,0,0);const r=4*n.length,o=this.memoryManager.malloc(r);for(let e=0;e{const r=A(n),a=this.convertDevicePointToPagePoint(e,t,r.p1),s=this.convertDevicePointToPagePoint(e,t,r.p2),u=this.convertDevicePointToPagePoint(e,t,r.p3),m=this.convertDevicePointToPagePoint(e,t,r.p4);o.setValue(i+0,a.x,"float"),o.setValue(i+4,a.y,"float"),o.setValue(i+8,s.x,"float"),o.setValue(i+12,s.y,"float"),o.setValue(i+16,m.x,"float"),o.setValue(i+20,m.y,"float"),o.setValue(i+24,u.x,"float"),o.setValue(i+28,u.y,"float")},u=Math.min(a,r.length);for(let e=0;e{var t,n,r,o;return e&&Number.isFinite(null==(t=e.origin)?void 0:t.x)&&Number.isFinite(null==(n=e.origin)?void 0:n.y)&&Number.isFinite(null==(r=e.size)?void 0:r.width)&&Number.isFinite(null==(o=e.size)?void 0:o.height)&&e.size.width>0&&e.size.height>0});if(0===F.length)return this.logger.perf("PDFiumEngine","Engine",u,"End",`${e.id}-${r.index}`),t.resolve(!1);const l=m.acquirePage(r.index),{ptr:d,count:P}=this.allocFSQuadsBufferFromRects(e,r,F);let _=!1;try{_=!!this.pdfiumModule.EPDFText_RedactInQuads(l.pagePtr,d,P,!!i,!1)}finally{this.memoryManager.free(d)}return _&&(_=!!this.pdfiumModule.FPDFPage_GenerateContent(l.pagePtr)),l.disposeImmediate(),this.logger.perf("PDFiumEngine","Engine",u,"End",`${e.id}-${r.index}`),t.resolve(!!_)}applyRedaction(e,r,o){this.logger.debug(oe,ae,"applyRedaction",e.id,r.index,o.id);const a="ApplyRedaction";this.logger.perf(oe,ae,a,"Begin",`${e.id}-${r.index}`);const i=this.cache.getContext(e.id);if(!i)return this.logger.perf(oe,ae,a,"End",`${e.id}-${r.index}`),t.reject({code:n.DocNotOpen,message:"document does not open"});const s=i.acquirePage(r.index),u=this.getAnnotationByName(s.pagePtr,o.id);if(!u)return s.release(),this.logger.perf(oe,ae,a,"End",`${e.id}-${r.index}`),t.reject({code:n.NotFound,message:"annotation not found"});const m=this.pdfiumModule.EPDFAnnot_ApplyRedaction(s.pagePtr,u);return this.pdfiumModule.FPDFPage_CloseAnnot(u),m&&this.pdfiumModule.FPDFPage_GenerateContent(s.pagePtr),s.disposeImmediate(),this.logger.perf(oe,ae,a,"End",`${e.id}-${r.index}`),t.resolve(!!m)}applyAllRedactions(e,r){this.logger.debug(oe,ae,"applyAllRedactions",e.id,r.index);const o="ApplyAllRedactions";this.logger.perf(oe,ae,o,"Begin",`${e.id}-${r.index}`);const a=this.cache.getContext(e.id);if(!a)return this.logger.perf(oe,ae,o,"End",`${e.id}-${r.index}`),t.reject({code:n.DocNotOpen,message:"document does not open"});const i=a.acquirePage(r.index),s=this.pdfiumModule.EPDFPage_ApplyRedactions(i.pagePtr);return s&&this.pdfiumModule.FPDFPage_GenerateContent(i.pagePtr),i.disposeImmediate(),this.logger.perf(oe,ae,o,"End",`${e.id}-${r.index}`),t.resolve(!!s)}flattenAnnotation(e,r,o){this.logger.debug(oe,ae,"flattenAnnotation",e.id,r.index,o.id);const a="FlattenAnnotation";this.logger.perf(oe,ae,a,"Begin",`${e.id}-${r.index}`);const i=this.cache.getContext(e.id);if(!i)return this.logger.perf(oe,ae,a,"End",`${e.id}-${r.index}`),t.reject({code:n.DocNotOpen,message:"document does not open"});const s=i.acquirePage(r.index),u=this.getAnnotationByName(s.pagePtr,o.id);if(!u)return s.release(),this.logger.perf(oe,ae,a,"End",`${e.id}-${r.index}`),t.reject({code:n.NotFound,message:"annotation not found"});const m=this.pdfiumModule.EPDFAnnot_Flatten(s.pagePtr,u);return this.pdfiumModule.FPDFPage_CloseAnnot(u),m&&this.pdfiumModule.FPDFPage_GenerateContent(s.pagePtr),s.disposeImmediate(),this.logger.perf(oe,ae,a,"End",`${e.id}-${r.index}`),t.resolve(!!m)}allocFSQuadsBufferFromRects(e,t,n){const r=n.length,o=this.memoryManager.malloc(32*r),a=this.pdfiumModule.pdfium;for(let i=0;i0){const r=this.memoryManager.malloc(8*s);this.pdfiumModule.FPDFAnnot_GetInkListPath(n,i,r,s);for(let n=0;nthis.pdfiumModule.FPDFLink_GetAction(a),()=>this.pdfiumModule.FPDFLink_GetDest(n,a));return{pageIndex:t.index,id:o,type:i.LINK,rect:u,target:c,strokeColor:P,strokeWidth:d,strokeStyle:m,strokeDashArray:_,...this.readBaseAnnotationProperties(e,t,r)}}readPdfWidgetAnno(e,t,n,r,o){const a=this.readPageAnnoRect(n),s=this.convertPageRectToDeviceRect(e,t,a),u=this.readPdfWidgetAnnoField(r,n);return{pageIndex:t.index,id:o,type:i.WIDGET,rect:s,field:u,...this.readBaseAnnotationProperties(e,t,n)}}readPdfFileAttachmentAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o);return{pageIndex:t.index,id:r,type:i.FILEATTACHMENT,rect:a,...this.readBaseAnnotationProperties(e,t,n)}}readPdfInkAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o),s=this.getAnnotationColor(n)??"#FF0000",u=this.getAnnotationOpacity(n),{width:m}=this.getBorderStyle(n),F=this.getInkList(e,t,n),l=this.pdfiumModule.EPDFAnnot_GetBlendMode(n),d=this.getAnnotIntent(n);return{pageIndex:t.index,id:r,type:i.INK,rect:a,...d&&{intent:d},blendMode:l,strokeColor:s,color:s,opacity:u,strokeWidth:0===m?1:m,inkList:F,...this.readBaseAnnotationProperties(e,t,n)}}readPdfPolygonAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o),s=this.readPdfAnnoVertices(e,t,n),u=this.getAnnotationColor(n),m=this.getAnnotationColor(n,l.InteriorColor),d=this.getAnnotationOpacity(n),{style:P,width:_}=this.getBorderStyle(n);let c;if(P===F.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(n);e&&(c=t)}if(s.length>1){const e=s[0],t=s[s.length-1];e.x===t.x&&e.y===t.y&&s.pop()}return{pageIndex:t.index,id:r,type:i.POLYGON,rect:a,strokeColor:u??"#FF0000",color:m??"transparent",opacity:d,strokeWidth:0===_?1:_,strokeStyle:P,strokeDashArray:c,vertices:s,...this.readBaseAnnotationProperties(e,t,n)}}readPdfPolylineAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o),s=this.readPdfAnnoVertices(e,t,n),u=this.getAnnotationColor(n),m=this.getAnnotationColor(n,l.InteriorColor),d=this.getAnnotationOpacity(n),{style:P,width:_}=this.getBorderStyle(n);let c;if(P===F.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(n);e&&(c=t)}const g=this.getLineEndings(n);return{pageIndex:t.index,id:r,type:i.POLYLINE,rect:a,strokeColor:u??"#FF0000",color:m??"transparent",opacity:d,strokeWidth:0===_?1:_,strokeStyle:P,strokeDashArray:c,lineEndings:g,vertices:s,...this.readBaseAnnotationProperties(e,t,n)}}readPdfLineAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o),s=this.getLinePoints(e,t,n),u=this.getLineEndings(n),m=this.getAnnotationColor(n),P=this.getAnnotationColor(n,l.InteriorColor),_=this.getAnnotationOpacity(n),{style:c,width:g}=this.getBorderStyle(n);let h;if(c===F.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(n);e&&(h=t)}return{pageIndex:t.index,id:r,type:i.LINE,rect:a,strokeWidth:0===g?1:g,strokeStyle:c,strokeDashArray:h,strokeColor:m??"#FF0000",color:P??"transparent",opacity:_,linePoints:s||{start:{x:0,y:0},end:{x:0,y:0}},lineEndings:u||{start:d.None,end:d.None},...this.readBaseAnnotationProperties(e,t,n)}}readPdfHighlightAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o),s=this.getQuadPointsAnno(e,t,n),u=this.getAnnotationColor(n)??"#FFFF00",m=this.getAnnotationOpacity(n),F=this.pdfiumModule.EPDFAnnot_GetBlendMode(n);return{pageIndex:t.index,id:r,type:i.HIGHLIGHT,rect:a,blendMode:F,segmentRects:s,strokeColor:u,color:u,opacity:m,...this.readBaseAnnotationProperties(e,t,n)}}readPdfUnderlineAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o),s=this.getQuadPointsAnno(e,t,n),u=this.getAnnotationColor(n)??"#FF0000",m=this.getAnnotationOpacity(n),F=this.pdfiumModule.EPDFAnnot_GetBlendMode(n);return{pageIndex:t.index,id:r,type:i.UNDERLINE,rect:a,blendMode:F,segmentRects:s,strokeColor:u,color:u,opacity:m,...this.readBaseAnnotationProperties(e,t,n)}}readPdfStrikeOutAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o),s=this.getQuadPointsAnno(e,t,n),u=this.getAnnotationColor(n)??"#FF0000",m=this.getAnnotationOpacity(n),F=this.pdfiumModule.EPDFAnnot_GetBlendMode(n);return{pageIndex:t.index,id:r,type:i.STRIKEOUT,rect:a,blendMode:F,segmentRects:s,strokeColor:u,color:u,opacity:m,...this.readBaseAnnotationProperties(e,t,n)}}readPdfSquigglyAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o),s=this.getQuadPointsAnno(e,t,n),u=this.getAnnotationColor(n)??"#FF0000",m=this.getAnnotationOpacity(n),F=this.pdfiumModule.EPDFAnnot_GetBlendMode(n);return{pageIndex:t.index,id:r,type:i.SQUIGGLY,rect:a,blendMode:F,segmentRects:s,strokeColor:u,color:u,opacity:m,...this.readBaseAnnotationProperties(e,t,n)}}readPdfCaretAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o);return{pageIndex:t.index,id:r,type:i.CARET,rect:a,...this.readBaseAnnotationProperties(e,t,n)}}readPdfRedactAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o),s=this.getQuadPointsAnno(e,t,n),u=this.getAnnotationColor(n,l.InteriorColor),m=this.getAnnotationColor(n,l.OverlayColor),F=this.getAnnotationColor(n,l.Color),d=this.getAnnotationOpacity(n),P=this.getOverlayText(n),_=this.getOverlayTextRepeat(n),c=this.getAnnotationDefaultAppearance(n),g=this.getAnnotationTextAlignment(n);return{pageIndex:t.index,id:r,type:i.REDACT,rect:a,segmentRects:s,color:u,overlayColor:m,strokeColor:F,opacity:d,overlayText:P,overlayTextRepeat:_,fontFamily:null==c?void 0:c.fontFamily,fontSize:null==c?void 0:c.fontSize,fontColor:null==c?void 0:c.fontColor,textAlign:g,...this.readBaseAnnotationProperties(e,t,n)}}readPdfStampAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o);return{pageIndex:t.index,id:r,type:i.STAMP,rect:a,...this.readBaseAnnotationProperties(e,t,n)}}readPdfPageObject(e){switch(this.pdfiumModule.FPDFPageObj_GetType(e)){case E.PATH:return this.readPathObject(e);case E.IMAGE:return this.readImageObject(e);case E.FORM:return this.readFormObject(e)}}readPathObject(e){const t=this.pdfiumModule.FPDFPath_CountSegments(e),n=this.memoryManager.malloc(4),r=this.memoryManager.malloc(4),o=this.memoryManager.malloc(4),a=this.memoryManager.malloc(4);this.pdfiumModule.FPDFPageObj_GetBounds(e,n,r,o,a);const i={left:this.pdfiumModule.pdfium.getValue(n,"float"),bottom:this.pdfiumModule.pdfium.getValue(r,"float"),right:this.pdfiumModule.pdfium.getValue(o,"float"),top:this.pdfiumModule.pdfium.getValue(a,"float")};this.memoryManager.free(n),this.memoryManager.free(r),this.memoryManager.free(o),this.memoryManager.free(a);const s=[];for(let n=0;n({points:e.points.map(e=>this.rotatePointForSave(e,r,t))}));return{...n,inkList:o}}case i.LINE:{const n=e;return{...n,linePoints:{start:this.rotatePointForSave(n.linePoints.start,r,t),end:this.rotatePointForSave(n.linePoints.end,r,t)}}}case i.POLYGON:{const n=e;return{...n,vertices:n.vertices.map(e=>this.rotatePointForSave(e,r,t))}}case i.POLYLINE:{const n=e;return{...n,vertices:n.vertices.map(e=>this.rotatePointForSave(e,r,t))}}default:return e}}applyBaseAnnotationProperties(e,t,n,r,o){if(!this.setAnnotString(r,"T",o.author||""))return!1;if(!this.setAnnotString(r,"Contents",o.contents??""))return!1;if(o.modified&&!this.setAnnotationDate(r,"M",o.modified))return!1;if(o.created&&!this.setAnnotationDate(r,"CreationDate",o.created))return!1;if(o.flags&&!this.setAnnotationFlags(r,o.flags))return!1;const a=this.getAnnotCustom(r)??{},i={...a,...o.custom??{}};delete i.unrotatedRect,delete i.rotation;if(Object.keys(i).length>0){if(!this.setAnnotCustom(r,i))return!1}else if(Object.keys(a).length>0&&!this.setAnnotCustom(r,null))return!1;if(void 0!==o.rotation){const e=o.rotation?(360-o.rotation)%360:0;this.setAnnotExtendedRotation(r,e)}return o.unrotatedRect?this.setAnnotUnrotatedRect(e,t,r,o.unrotatedRect):o.rotation&&0!==o.rotation&&this.setAnnotUnrotatedRect(e,t,r,o.rect),!!this.setInReplyToId(n,r,o.inReplyToId)&&!!this.setReplyType(r,o.replyType)}readBaseAnnotationProperties(e,t,n){const r=this.getAnnotString(n,"T"),o=this.getAnnotString(n,"Contents")||"",a=this.getAnnotationDate(n,"M"),i=this.getAnnotationDate(n,"CreationDate"),s=this.getAnnotationFlags(n),u=this.getAnnotCustom(n),m=this.getInReplyToId(n),F=this.getReplyType(n),l=this.getAnnotExtendedRotation(n),d=0!==l?(360-l)%360:0,P=this.readAnnotUnrotatedRect(n),_=P?this.convertPageRectToDeviceRect(e,t,P):void 0;return{author:r,contents:o,modified:a,created:i,flags:s,custom:u,...m&&{inReplyToId:m},...F&&F!==b.Reply&&{replyType:F},...0!==d&&{rotation:d},...void 0!==_&&{unrotatedRect:_}}}getAnnotString(e,t){const n=this.pdfiumModule.FPDFAnnot_GetStringValue(e,t,0,0);if(0===n)return;const r=2*(n+1),o=this.memoryManager.malloc(r);this.pdfiumModule.FPDFAnnot_GetStringValue(e,t,o,r);const a=this.pdfiumModule.pdfium.UTF16ToString(o);return this.memoryManager.free(o),a||void 0}getAttachmentString(e,t){const n=this.pdfiumModule.FPDFAttachment_GetStringValue(e,t,0,0);if(0===n)return;const r=2*(n+1),o=this.memoryManager.malloc(r);this.pdfiumModule.FPDFAttachment_GetStringValue(e,t,o,r);const a=this.pdfiumModule.pdfium.UTF16ToString(o);return this.memoryManager.free(o),a||void 0}getAttachmentNumber(e,t){const n=this.memoryManager.malloc(4);try{if(!this.pdfiumModule.EPDFAttachment_GetIntegerValue(e,t,n))return;return this.pdfiumModule.pdfium.getValue(n,"i32")>>>0}finally{this.memoryManager.free(n)}}getAnnotCustom(e){const t=this.getAnnotString(e,"EPDFCustom");if(t)try{return JSON.parse(t)}catch(e){return console.warn("Failed to parse annotation custom data as JSON:",e),void console.warn("Invalid JSON string:",t)}}setAnnotCustom(e,t){if(null==t)return this.setAnnotString(e,"EPDFCustom","");try{const n=JSON.stringify(t);return this.setAnnotString(e,"EPDFCustom",n)}catch(e){return console.warn("Failed to stringify annotation custom data as JSON:",e),console.warn("Invalid data object:",t),!1}}getAnnotIntent(e){const t=this.pdfiumModule.EPDFAnnot_GetIntent(e,0,0);if(0===t)return;const n=2*(t+1),r=this.memoryManager.malloc(n);this.pdfiumModule.EPDFAnnot_GetIntent(e,r,n);const o=this.pdfiumModule.pdfium.UTF16ToString(r);return this.memoryManager.free(r),o&&"undefined"!==o?o: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 n=2*(t+1),r=this.memoryManager.malloc(n);this.pdfiumModule.EPDFAnnot_GetRichContent(e,r,n);const o=this.pdfiumModule.pdfium.UTF16ToString(r);return this.memoryManager.free(r),o||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,n){return this.withWString(n,n=>this.pdfiumModule.FPDFAnnot_SetStringValue(e,t,n))}setAttachmentString(e,t,n){return this.withWString(n,n=>this.pdfiumModule.FPDFAttachment_SetStringValue(e,t,n))}readPdfAnnoVertices(e,t,n){const r=[],o=this.pdfiumModule.FPDFAnnot_GetVertices(n,0,0),a=this.memoryManager.malloc(8*o);this.pdfiumModule.FPDFAnnot_GetVertices(n,a,o);for(let n=0;n{const i=this.convertDevicePointToPagePoint(e,t,n);o.setValue(a+8*r+0,i.x,"float"),o.setValue(a+8*r+4,i.y,"float")});const i=this.pdfiumModule.EPDFAnnot_SetVertices(n,a,r.length);return this.memoryManager.free(a),i}readPdfBookmarkTarget(e,t,n){const r=t();if(r){return{type:"action",action:this.readPdfAction(e,r)}}{const t=n();if(t){return{type:"destination",destination:this.readPdfDestination(e,t)}}}}readPdfWidgetAnnoField(e,t){const n=this.pdfiumModule.FPDFAnnot_GetFormFieldFlags(e,t),r=this.pdfiumModule.FPDFAnnot_GetFormFieldType(e,t),o=U(this.pdfiumModule.pdfium,(n,r)=>this.pdfiumModule.FPDFAnnot_GetFormFieldName(e,t,n,r),this.pdfiumModule.pdfium.UTF16ToString),a=U(this.pdfiumModule.pdfium,(n,r)=>this.pdfiumModule.FPDFAnnot_GetFormFieldAlternateName(e,t,n,r),this.pdfiumModule.pdfium.UTF16ToString),i=U(this.pdfiumModule.pdfium,(n,r)=>this.pdfiumModule.FPDFAnnot_GetFormFieldValue(e,t,n,r),this.pdfiumModule.pdfium.UTF16ToString),s=[];if(r===G.COMBOBOX||r===G.LISTBOX){const n=this.pdfiumModule.FPDFAnnot_GetOptionCount(e,t);for(let r=0;rthis.pdfiumModule.FPDFAnnot_GetOptionLabel(e,t,r,n,o),this.pdfiumModule.pdfium.UTF16ToString),o=this.pdfiumModule.FPDFAnnot_IsOptionSelected(e,t,r);s.push({label:n,isSelected:o})}}let u=!1;return r!==G.CHECKBOX&&r!==G.RADIOBUTTON||(u=this.pdfiumModule.FPDFAnnot_IsChecked(e,t)),{flag:n,type:r,name:o,alternateName:a,value:i,isChecked:u,options:s}}renderPageAnnotationRaw(e,r,o,a){const{scaleFactor:i=1,rotation:s=C.Degree0,dpr:u=1,mode:m=S.Normal}=a??{};this.logger.debug(oe,ae,"renderPageAnnotation",e,r,o,a),this.logger.perf(oe,ae,"RenderPageAnnotation","Begin",`${e.id}-${r.index}-${o.id}`);const F=new O,l=this.cache.getContext(e.id);if(!l)return this.logger.perf(oe,ae,"RenderPageAnnotation","End",`${e.id}-${r.index}-${o.id}`),t.reject({code:n.DocNotOpen,message:"document does not open"});const d=l.acquirePage(r.index),P=this.getAnnotationByName(d.pagePtr,o.id);if(!P)return this.logger.perf(oe,ae,"RenderPageAnnotation","End",`${e.id}-${r.index}-${o.id}`),d.release(),t.reject({code:n.NotFound,message:"annotation not found"});const _=Math.max(.01,i*u),c=!!(null==a?void 0:a.unrotated)&&!!o.unrotatedRect,g=c?o.unrotatedRect:o.rect,h=x(g),D=x(T(r.size,h,s,_)),b=Math.max(1,D.size.width),p=Math.max(1,D.size.height),f=4*b,A=f*p,E=this.memoryManager.malloc(A),y=this.pdfiumModule.FPDFBitmap_CreateEx(b,p,4,E,f);this.pdfiumModule.FPDFBitmap_FillRect(y,0,0,b,p,0);const M=v(h,s,b,p),G=this.memoryManager.malloc(24);new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer,G,6).set([M.a,M.b,M.c,M.d,M.e,M.f]);let R=!1;try{R=c?!!this.pdfiumModule.EPDF_RenderAnnotBitmapUnrotated(y,d.pagePtr,P,m,G,16):!!this.pdfiumModule.EPDF_RenderAnnotBitmap(y,d.pagePtr,P,m,G,16)}finally{this.memoryManager.free(G),this.pdfiumModule.FPDFBitmap_Destroy(y),this.pdfiumModule.FPDFPage_CloseAnnot(P),d.release()}if(!R)return this.memoryManager.free(E),this.logger.perf(oe,ae,"RenderPageAnnotation","End",`${e.id}-${r.index}-${o.id}`),t.reject({code:n.Unknown,message:"EPDF_RenderAnnotBitmap failed"});const k=this.pdfiumModule.pdfium.HEAPU8.subarray(E,E+A),w={data:new Uint8ClampedArray(k),width:b,height:p};return F.resolve(w),this.memoryManager.free(E),F}renderRectEncoded(e,r,o,a){const i=new O,s=(null==a?void 0:a.rotation)??C.Degree0,u=this.cache.getContext(e.id);if(!u)return t.reject({code:n.DocNotOpen,message:"document does not open"});const m=Math.max(.01,(null==a?void 0:a.scaleFactor)??1)*Math.max(1,(null==a?void 0:a.dpr)??1),F=o.size.width,l=o.size.height,d=!(1&~s),P=Math.max(1,Math.round((d?l:F)*m)),_=Math.max(1,Math.round((d?F:l)*m)),c=4*P,g=c*_,h=u.acquirePage(r.index),D=(null==a?void 0:a.withForms)??!1?h.getFormHandle():void 0,b=this.memoryManager.malloc(g),p=this.pdfiumModule.FPDFBitmap_CreateEx(P,_,4,b,c);this.pdfiumModule.FPDFBitmap_FillRect(p,0,0,P,_,4294967295);const f=v(o,s,P,_),A=this.memoryManager.malloc(24);new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer,A,6).set([f.a,f.b,f.c,f.d,f.e,f.f]);const E=this.memoryManager.malloc(16);new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer,E,4).set([0,0,P,_]);let y=16;(null==a?void 0:a.withAnnotations)&&(y|=1);try{if(this.pdfiumModule.FPDF_RenderPageBitmapWithMatrix(p,h.pagePtr,A,E,y),void 0!==D){const e=function(e,t,n,r){const o=t.origin.x,a=t.origin.y,i=o+t.size.width,s=a+t.size.height,u=n.width,m=n.height,F=Math.hypot(e.a,e.b),l=Math.hypot(e.c,e.d),d=!(1&~r),P=d?Math.max(1,Math.round(m*F)):Math.max(1,Math.round(u*F)),_=d?Math.max(1,Math.round(u*l)):Math.max(1,Math.round(m*l));let c,g;switch(r){case C.Degree0:c=-Math.round(o*F),g=-Math.round(a*l);break;case C.Degree90:c=Math.round((s-m)*F),g=-Math.round(o*l);break;case C.Degree180:c=Math.round((i-u)*F),g=Math.round((s-m)*l);break;case C.Degree270:c=-Math.round(a*F),g=Math.round((i-u)*l);break;default:c=-Math.round(o*F),g=-Math.round(a*l)}return{startX:c,startY:g,formsWidth:P,formsHeight:_,scaleX:F,scaleY:l}}(f,o,r.size,s),{startX:t,startY:n,formsWidth:a,formsHeight:i,scaleX:u,scaleY:m}=e;this.pdfiumModule.FPDF_FFLDraw(D,p,h.pagePtr,t,n,a,i,s,y)}}finally{h.release(),this.memoryManager.free(A),this.memoryManager.free(E)}this.logger.perf(oe,ae,"RenderRectEncodedData","Begin",`${e.id}-${r.index}`);const M=this.pdfiumModule.pdfium.HEAPU8.subarray(b,b+g);this.logger.perf(oe,ae,"RenderRectEncodedData","End",`${e.id}-${r.index}`),this.logger.perf(oe,ae,"RenderRectEncodedImageData","Begin",`${e.id}-${r.index}`);const G={data:new Uint8ClampedArray(M),width:P,height:_};return this.logger.perf(oe,ae,"RenderRectEncodedImageData","End",`${e.id}-${r.index}`),i.resolve(G),this.pdfiumModule.FPDFBitmap_Destroy(p),this.memoryManager.free(b),i}readPdfLinkAnnoTarget(e,t,n){const r=n();if(r){return{type:"destination",destination:this.readPdfDestination(e,r)}}{const n=t();if(n){return{type:"action",action:this.readPdfAction(e,n)}}}}createLocalDestPtr(e,t){var n,r;const o=this.pdfiumModule.FPDF_LoadPage(e,t.pageIndex);if(!o)return 0;try{if(t.zoom.mode===R.XYZ){const{x:e,y:n,zoom:r}=t.zoom.params;return this.pdfiumModule.EPDFDest_CreateXYZ(o,!0,e,!0,n,!0,r)}let e,a=[];switch(t.zoom.mode){case R.FitPage:e=R.FitPage;break;case R.FitHorizontal:e=R.FitHorizontal,a=[(null==(n=t.view)?void 0:n[0])??0];break;case R.FitVertical:e=R.FitVertical,a=[(null==(r=t.view)?void 0:r[0])??0];break;case R.FitRectangle:{const n=t.view??[];a=[n[0]??0,n[1]??0,n[2]??0,n[3]??0],e=R.FitRectangle}break;case R.Unknown:default:return 0}return this.withFloatArray(a,(t,n)=>this.pdfiumModule.EPDFDest_CreateView(o,e,t,n))}finally{this.pdfiumModule.FPDF_ClosePage(o)}}applyBookmarkTarget(e,t,n){if("destination"===n.type){const r=this.createLocalDestPtr(e,n.destination);if(!r)return!1;return!!this.pdfiumModule.EPDFBookmark_SetDest(e,t,r)}const r=n.action;switch(r.type){case k.Goto:{const n=this.createLocalDestPtr(e,r.destination);if(!n)return!1;const o=this.pdfiumModule.EPDFAction_CreateGoTo(e,n);return!!o&&!!this.pdfiumModule.EPDFBookmark_SetAction(e,t,o)}case k.URI:{const n=this.pdfiumModule.EPDFAction_CreateURI(e,r.uri);return!!n&&!!this.pdfiumModule.EPDFBookmark_SetAction(e,t,n)}case k.LaunchAppOrOpenFile:{const n=this.withWString(r.path,t=>this.pdfiumModule.EPDFAction_CreateLaunch(e,t));return!!n&&!!this.pdfiumModule.EPDFBookmark_SetAction(e,t,n)}case k.RemoteGoto:case k.Unsupported:default:return!1}}applyLinkTarget(e,t,n){if("destination"===n.type){const r=this.createLocalDestPtr(e,n.destination);if(!r)return!1;const o=this.pdfiumModule.EPDFAction_CreateGoTo(e,r);return!!o&&!!this.pdfiumModule.EPDFAnnot_SetAction(t,o)}const r=n.action;switch(r.type){case k.Goto:{const n=this.createLocalDestPtr(e,r.destination);if(!n)return!1;const o=this.pdfiumModule.EPDFAction_CreateGoTo(e,n);return!!o&&!!this.pdfiumModule.EPDFAnnot_SetAction(t,o)}case k.URI:{const n=this.pdfiumModule.EPDFAction_CreateURI(e,r.uri);return!!n&&!!this.pdfiumModule.EPDFAnnot_SetAction(t,n)}case k.LaunchAppOrOpenFile:{const n=this.withWString(r.path,t=>this.pdfiumModule.EPDFAction_CreateLaunch(e,t));return!!n&&!!this.pdfiumModule.EPDFAnnot_SetAction(t,n)}case k.RemoteGoto:case k.Unsupported:default:return!1}}readPdfAction(e,t){let n;switch(this.pdfiumModule.FPDFAction_GetType(t)){case k.Unsupported:n={type:k.Unsupported};break;case k.Goto:{const r=this.pdfiumModule.FPDFAction_GetDest(e,t);if(r){const t=this.readPdfDestination(e,r);n={type:k.Goto,destination:t}}else n={type:k.Unsupported}}break;case k.RemoteGoto:n={type:k.Unsupported};break;case k.URI:{const r=U(this.pdfiumModule.pdfium,(n,r)=>this.pdfiumModule.FPDFAction_GetURIPath(e,t,n,r),this.pdfiumModule.pdfium.UTF8ToString);n={type:k.URI,uri:r}}break;case k.LaunchAppOrOpenFile:{const e=U(this.pdfiumModule.pdfium,(e,n)=>this.pdfiumModule.FPDFAction_GetFilePath(t,e,n),this.pdfiumModule.pdfium.UTF8ToString);n={type:k.LaunchAppOrOpenFile,path:e}}}return n}readPdfDestination(e,t){const n=this.pdfiumModule.FPDFDest_GetDestPageIndex(e,t),r=this.memoryManager.malloc(4),o=this.memoryManager.malloc(16),a=this.pdfiumModule.FPDFDest_GetView(t,r,o),i=this.pdfiumModule.pdfium.getValue(r,"i32"),s=[];for(let e=0;ethis.pdfiumModule.FPDFAttachment_GetName(n,e,t),this.pdfiumModule.pdfium.UTF16ToString),o=U(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.EPDFAttachment_GetDescription(n,e,t),this.pdfiumModule.pdfium.UTF16ToString),a=U(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFAttachment_GetSubtype(n,e,t),this.pdfiumModule.pdfium.UTF16ToString),i=this.getAttachmentDate(n,"CreationDate"),s=U(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFAttachment_GetStringValue(n,"Checksum",e,t),this.pdfiumModule.pdfium.UTF16ToString);return{index:t,name:r,description:o,mimeType:a,size:this.getAttachmentNumber(n,"Size"),creationDate:i,checksum:s}}convertDevicePointToPagePoint(e,t,n){const r=t.size.width,o=t.size.height,a=e.normalizedRotation?0:3&t.rotation;return 0===a?{x:n.x,y:o-n.y}:1===a?{x:n.y,y:n.x}:2===a?{x:r-n.x,y:n.y}:{x:o-n.y,y:r-n.x}}convertPagePointToDevicePoint(e,t,n){const r=t.size.width,o=t.size.height,a=e.normalizedRotation?0:3&t.rotation;return 0===a?{x:n.x,y:o-n.y}:1===a?{x:n.y,y:n.x}:2===a?{x:r-n.x,y:n.y}:{x:r-n.y,y:o-n.x}}convertPageRectToDeviceRect(e,t,n){const{x:r,y:o}=this.convertPagePointToDevicePoint(e,t,{x:n.left,y:n.top});return{origin:{x:r,y:o},size:{width:Math.abs(n.right-n.left),height:Math.abs(n.top-n.bottom)}}}readPageAnnoAppearanceStreams(e){return{normal:this.readPageAnnoAppearanceStream(e,S.Normal),rollover:this.readPageAnnoAppearanceStream(e,S.Rollover),down:this.readPageAnnoAppearanceStream(e,S.Down)}}readPageAnnoAppearanceStream(e,t=S.Normal){const n=2*(this.pdfiumModule.FPDFAnnot_GetAP(e,t,0,0)+1),r=this.memoryManager.malloc(n);this.pdfiumModule.FPDFAnnot_GetAP(e,t,r,n);const o=this.pdfiumModule.pdfium.UTF16ToString(r);return this.memoryManager.free(r),o}setPageAnnoAppearanceStream(e,t=S.Normal,n){const r=2*(n.length+1),o=this.memoryManager.malloc(r);try{this.pdfiumModule.pdfium.stringToUTF16(n,o,r);return!!this.pdfiumModule.FPDFAnnot_SetAP(e,t,o)}finally{this.memoryManager.free(o)}}setPageAnnoRect(e,t,n,r){const o=Math.floor(r.origin.x),a=Math.floor(r.origin.y),i=Math.floor(r.origin.x+r.size.width),s=Math.floor(r.origin.y+r.size.height),u=this.convertDevicePointToPagePoint(e,t,{x:o,y:a}),m=this.convertDevicePointToPagePoint(e,t,{x:i,y:a}),F=this.convertDevicePointToPagePoint(e,t,{x:i,y:s}),l=this.convertDevicePointToPagePoint(e,t,{x:o,y:s});let d=Math.min(u.x,m.x,F.x,l.x),P=Math.max(u.x,m.x,F.x,l.x),_=Math.min(u.y,m.y,F.y,l.y),c=Math.max(u.y,m.y,F.y,l.y);d>P&&([d,P]=[P,d]),_>c&&([_,c]=[c,_]);const g=this.memoryManager.malloc(16),h=this.pdfiumModule.pdfium;h.setValue(g+0,d,"float"),h.setValue(g+4,c,"float"),h.setValue(g+8,P,"float"),h.setValue(g+12,_,"float");const D=this.pdfiumModule.FPDFAnnot_SetRect(n,g);return this.memoryManager.free(g),!!D}readPageAnnoRect(e){const t=this.memoryManager.malloc(16),n={left:0,top:0,right:0,bottom:0};return this.pdfiumModule.EPDFAnnot_GetRect(e,t)&&(n.left=this.pdfiumModule.pdfium.getValue(t,"float"),n.top=this.pdfiumModule.pdfium.getValue(t+4,"float"),n.right=this.pdfiumModule.pdfium.getValue(t+8,"float"),n.bottom=this.pdfiumModule.pdfium.getValue(t+12,"float")),this.memoryManager.free(t),n}getHighlightRects(e,t,n,r,o){const a=this.pdfiumModule.FPDFText_CountRects(n,r,o),i=[],s=this.memoryManager.malloc(8),u=this.memoryManager.malloc(8),m=this.memoryManager.malloc(8),F=this.memoryManager.malloc(8);for(let r=0;r{this.logger.perf(oe,ae,"GetAnnotationsBatch","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return void r.reject({code:n.DocNotOpen,message:"Document is not open"});const a={},i=t.length;for(let n=0;n{this.logger.perf(oe,ae,"SearchBatch","Begin",e.id);const i=this.cache.getContext(e.id);if(!i)return void a.reject({code:n.DocNotOpen,message:"Document is not open"});const s=2*(r.length+1),u=this.memoryManager.malloc(s);this.pdfiumModule.pdfium.stringToUTF16(r,u,s);try{const n={},r=t.length;for(let s=0;s/\\\-"'`"”\u2013\u2014]/;let a=t;for(;a>0&&o.test(e[a-1]);)a--;let i=0;for(;a>0&&i{for(;t>0&&!o.test(e[t-1]);)t--;return t})(a);let s=t+n;for(;s{for(;t0,truncatedRight:s{const a=t.getTextPage(),i=this.pdfiumModule.FPDFText_CountChars(a),s=this.memoryManager.malloc(2*(i+1));this.pdfiumModule.FPDFText_GetText(a,0,i,s);const u=this.pdfiumModule.pdfium.UTF16ToString(s);this.memoryManager.free(s);const m=[],F=this.pdfiumModule.FPDFText_FindStart(a,r,o,0);for(;this.pdfiumModule.FPDFText_FindNext(F);){const t=this.pdfiumModule.FPDFText_GetSchResultIndex(F),r=this.pdfiumModule.FPDFText_GetSchCount(F),o=this.getHighlightRects(e,n,a,t,r),i=this.buildContext(u,t,r);m.push({pageIndex:n.index,charIndex:t,charCount:r,rects:o,context:i})}return this.pdfiumModule.FPDFText_FindClose(F),m})}preparePrintDocument(e,r){const{includeAnnotations:o=!0,pageRange:a=null}=r??{};this.logger.debug(oe,ae,"preparePrintDocument",e,r),this.logger.perf(oe,ae,"PreparePrintDocument","Begin",e.id);const i=this.cache.getContext(e.id);if(!i)return this.logger.perf(oe,ae,"PreparePrintDocument","End",e.id),t.reject({code:n.DocNotOpen,message:"Document is not open"});const s=this.pdfiumModule.FPDF_CreateNewDocument();if(!s)return this.logger.perf(oe,ae,"PreparePrintDocument","End",e.id),t.reject({code:n.CantCreateNewDoc,message:"Cannot create print document"});try{const r=this.sanitizePageRange(a,e.pageCount);if(!this.pdfiumModule.FPDF_ImportPages(s,i.docPtr,r??"",0))return this.pdfiumModule.FPDF_CloseDocument(s),this.logger.error(oe,ae,"Failed to import pages for printing"),this.logger.perf(oe,ae,"PreparePrintDocument","End",e.id),t.reject({code:n.CantImportPages,message:"Failed to import pages for printing"});if(!o){const r=this.removeAnnotationsFromPrintDocument(s);if(!r.success)return this.pdfiumModule.FPDF_CloseDocument(s),this.logger.error(oe,ae,`Failed to remove annotations: ${r.error}`),this.logger.perf(oe,ae,"PreparePrintDocument","End",e.id),t.reject({code:n.Unknown,message:`Failed to prepare print document: ${r.error}`});this.logger.debug(oe,ae,`Removed ${r.annotationsRemoved} annotations from ${r.pagesProcessed} pages`)}const u=this.saveDocument(s);return this.pdfiumModule.FPDF_CloseDocument(s),this.logger.perf(oe,ae,"PreparePrintDocument","End",e.id),t.resolve(u)}catch(r){return s&&this.pdfiumModule.FPDF_CloseDocument(s),this.logger.error(oe,ae,"preparePrintDocument failed",r),this.logger.perf(oe,ae,"PreparePrintDocument","End",e.id),t.reject({code:n.Unknown,message:r instanceof Error?r.message:"Failed to prepare print document"})}}removeAnnotationsFromPrintDocument(e){let t=0,n=0;try{const r=this.pdfiumModule.FPDF_GetPageCount(e);for(let o=0;o=0;n--){this.pdfiumModule.EPDFPage_RemoveAnnotRaw(e,o,n)?(a++,t++):this.logger.warn(oe,ae,`Failed to remove annotation ${n} from page ${o}`)}if(a>0){const t=this.pdfiumModule.FPDF_LoadPage(e,o);t&&(this.pdfiumModule.FPDFPage_GenerateContent(t),this.pdfiumModule.FPDF_ClosePage(t))}n++}return{success:!0,annotationsRemoved:t,pagesProcessed:n}}catch(e){return{success:!1,annotationsRemoved:t,pagesProcessed:n,error:e instanceof Error?e.message:"Unknown error during annotation removal"}}}sanitizePageRange(e,t){if(!e||""===e.trim())return null;try{const n=[],r=e.split(",");for(const e of r){const r=e.trim();if(r.includes("-")){const[e,o]=r.split("-").map(e=>e.trim()),a=parseInt(e,10),i=parseInt(o,10);if(isNaN(a)||isNaN(i)){this.logger.warn(oe,ae,`Invalid range: ${r}`);continue}const s=Math.max(1,Math.min(a,t)),u=Math.max(1,Math.min(i,t));for(let e=s;e<=u;e++)n.includes(e)||n.push(e)}else{const e=parseInt(r,10);if(isNaN(e)){this.logger.warn(oe,ae,`Invalid page number: ${r}`);continue}const o=Math.max(1,Math.min(e,t));n.includes(o)||n.push(o)}}if(0===n.length)return this.logger.warn(oe,ae,"No valid pages in range, using all pages"),null;n.sort((e,t)=>e-t);const o=[];let a=n[0],i=n[0];for(let e=1;e "${s}"`),s}catch(e){return this.logger.error(oe,ae,`Error sanitizing page range: ${e}`),null}}}async function se(e,t){const n=await fetch(e),r=await n.arrayBuffer(),o=await V({wasmBinary:r}),a=new ie(o,{logger:null==t?void 0:t.logger,fontFallback:null==t?void 0:t.fontFallback});return new I(a,{imageConverter:B,logger:null==t?void 0:t.logger})}export{se as createPdfiumEngine}; diff --git a/src/components/BootstrapBlazor.EmbedPDF/wwwroot/direct-engine-Bd0KtghI.js b/src/components/BootstrapBlazor.EmbedPDF/wwwroot/direct-engine-Bd0KtghI.js new file mode 100644 index 00000000..074cbdf8 --- /dev/null +++ b/src/components/BootstrapBlazor.EmbedPDF/wwwroot/direct-engine-Bd0KtghI.js @@ -0,0 +1 @@ +import{N as e,a as t,P as n,p as r,i as o,u as a,b as i,c as s,d as u,e as m,f as F,g as l,h as d,j as c,k as P,l as _,m as g,w as h,n as D,o as b,q as p,r as f,t as A,v as E,x as y,y as M,z as G,A as S,R as C,B as x,C as T,D as v,T as O,E as R,F as k,G as w,H as I,I as B,J as j}from"./embedpdf-xgzA9lZs.js";import{P as L,b as N}from"./browser-BISJ9naB-D71PyCCt.js";var V,U=(V=import.meta.url,async function(e={}){var t,n,r,o=e,a=new Promise((e,t)=>{n=e,r=t});["_EPDF_GetMetaKeyCount","_EPDF_GetMetaKeyName","_EPDF_GetMetaTrapped","_EPDF_GetPageRotationByIndex","_EPDF_GetPageSizeByIndexNormalized","_EPDF_HasMetaText","_EPDF_IsEncrypted","_EPDF_IsOwnerUnlocked","_EPDF_LoadPageNormalized","_EPDF_PNG_EncodeRGBA","_EPDF_RemoveEncryption","_EPDF_RenderAnnotBitmap","_EPDF_RenderAnnotBitmapUnrotated","_EPDF_SetEncryption","_EPDF_SetMetaText","_EPDF_SetMetaTrapped","_EPDF_UnlockOwnerPermissions","_EPDFAction_CreateGoTo","_EPDFAction_CreateGoToNamed","_EPDFAction_CreateLaunch","_EPDFAction_CreateRemoteGoToByName","_EPDFAction_CreateRemoteGoToDest","_EPDFAction_CreateURI","_EPDFAnnot_ApplyRedaction","_EPDFAnnot_ClearColor","_EPDFAnnot_ClearRectangleDifferences","_EPDFAnnot_Flatten","_EPDFAnnot_GenerateAppearance","_EPDFAnnot_GenerateAppearanceWithBlend","_EPDFAnnot_GetAPMatrix","_EPDFAnnot_GetAvailableAppearanceModes","_EPDFAnnot_GetBlendMode","_EPDFAnnot_GetBorderDashPattern","_EPDFAnnot_GetBorderDashPatternCount","_EPDFAnnot_GetBorderEffect","_EPDFAnnot_GetBorderStyle","_EPDFAnnot_GetColor","_EPDFAnnot_GetDefaultAppearance","_EPDFAnnot_GetExtendedRotation","_EPDFAnnot_GetIcon","_EPDFAnnot_GetIntent","_EPDFAnnot_GetLineEndings","_EPDFAnnot_GetOpacity","_EPDFAnnot_GetOverlayText","_EPDFAnnot_GetOverlayTextRepeat","_EPDFAnnot_GetRect","_EPDFAnnot_GetRectangleDifferences","_EPDFAnnot_GetReplyType","_EPDFAnnot_GetRichContent","_EPDFAnnot_GetRotate","_EPDFAnnot_GetTextAlignment","_EPDFAnnot_GetUnrotatedRect","_EPDFAnnot_GetVerticalAlignment","_EPDFAnnot_HasAppearanceStream","_EPDFAnnot_SetAction","_EPDFAnnot_SetAPMatrix","_EPDFAnnot_SetBorderDashPattern","_EPDFAnnot_SetBorderStyle","_EPDFAnnot_SetColor","_EPDFAnnot_SetDefaultAppearance","_EPDFAnnot_SetExtendedRotation","_EPDFAnnot_SetIcon","_EPDFAnnot_SetIntent","_EPDFAnnot_SetLine","_EPDFAnnot_SetLineEndings","_EPDFAnnot_SetLinkedAnnot","_EPDFAnnot_SetOpacity","_EPDFAnnot_SetOverlayText","_EPDFAnnot_SetOverlayTextRepeat","_EPDFAnnot_SetRectangleDifferences","_EPDFAnnot_SetReplyType","_EPDFAnnot_SetRotate","_EPDFAnnot_SetTextAlignment","_EPDFAnnot_SetUnrotatedRect","_EPDFAnnot_SetVerticalAlignment","_EPDFAnnot_SetVertices","_EPDFAnnot_UpdateAppearanceToRect","_EPDFAttachment_GetDescription","_EPDFAttachment_GetIntegerValue","_EPDFAttachment_SetDescription","_EPDFAttachment_SetSubtype","_EPDFBookmark_AppendChild","_EPDFBookmark_Clear","_EPDFBookmark_ClearTarget","_EPDFBookmark_Create","_EPDFBookmark_Delete","_EPDFBookmark_InsertAfter","_EPDFBookmark_SetAction","_EPDFBookmark_SetDest","_EPDFBookmark_SetTitle","_EPDFCatalog_GetLanguage","_EPDFDest_CreateRemoteView","_EPDFDest_CreateRemoteXYZ","_EPDFDest_CreateView","_EPDFDest_CreateXYZ","_EPDFNamedDest_Remove","_EPDFNamedDest_SetDest","_EPDFPage_ApplyRedactions","_EPDFPage_CreateAnnot","_EPDFPage_GetAnnotByName","_EPDFPage_GetAnnotCountRaw","_EPDFPage_GetAnnotRaw","_EPDFPage_RemoveAnnotByName","_EPDFPage_RemoveAnnotRaw","_EPDFText_RedactInQuads","_EPDFText_RedactInRect","_FORM_CanRedo","_FORM_CanUndo","_FORM_DoDocumentAAction","_FORM_DoDocumentJSAction","_FORM_DoDocumentOpenAction","_FORM_DoPageAAction","_FORM_ForceToKillFocus","_FORM_GetFocusedAnnot","_FORM_GetFocusedText","_FORM_GetSelectedText","_FORM_IsIndexSelected","_FORM_OnAfterLoadPage","_FORM_OnBeforeClosePage","_FORM_OnChar","_FORM_OnFocus","_FORM_OnKeyDown","_FORM_OnKeyUp","_FORM_OnLButtonDoubleClick","_FORM_OnLButtonDown","_FORM_OnLButtonUp","_FORM_OnMouseMove","_FORM_OnMouseWheel","_FORM_OnRButtonDown","_FORM_OnRButtonUp","_FORM_Redo","_FORM_ReplaceAndKeepSelection","_FORM_ReplaceSelection","_FORM_SelectAllText","_FORM_SetFocusedAnnot","_FORM_SetIndexSelected","_FORM_Undo","_FPDF_AddInstalledFont","_FPDF_CloseDocument","_FPDF_ClosePage","_FPDF_CloseXObject","_FPDF_CopyViewerPreferences","_FPDF_CountNamedDests","_FPDF_CreateClipPath","_FPDF_CreateNewDocument","_FPDF_DestroyClipPath","_FPDF_DestroyLibrary","_FPDF_DeviceToPage","_FPDF_DocumentHasValidCrossReferenceTable","_FPDF_FFLDraw","_FPDF_FreeDefaultSystemFontInfo","_FPDF_GetDefaultSystemFontInfo","_FPDF_GetDefaultTTFMap","_FPDF_GetDefaultTTFMapCount","_FPDF_GetDefaultTTFMapEntry","_FPDF_GetDocPermissions","_FPDF_GetDocUserPermissions","_FPDF_GetFileIdentifier","_FPDF_GetFileVersion","_FPDF_GetFormType","_FPDF_GetLastError","_FPDF_GetMetaText","_FPDF_GetNamedDest","_FPDF_GetNamedDestByName","_FPDF_GetPageAAction","_FPDF_GetPageBoundingBox","_FPDF_GetPageCount","_FPDF_GetPageHeight","_FPDF_GetPageHeightF","_FPDF_GetPageLabel","_FPDF_GetPageSizeByIndex","_FPDF_GetPageSizeByIndexF","_FPDF_GetPageWidth","_FPDF_GetPageWidthF","_FPDF_GetSecurityHandlerRevision","_FPDF_GetSignatureCount","_FPDF_GetSignatureObject","_FPDF_GetTrailerEnds","_FPDF_GetXFAPacketContent","_FPDF_GetXFAPacketCount","_FPDF_GetXFAPacketName","_FPDF_ImportNPagesToOne","_FPDF_ImportPages","_FPDF_ImportPagesByIndex","_FPDF_InitLibrary","_FPDF_InitLibraryWithConfig","_FPDF_LoadCustomDocument","_FPDF_LoadDocument","_FPDF_LoadMemDocument","_FPDF_LoadMemDocument64","_FPDF_LoadPage","_FPDF_LoadXFA","_FPDF_MovePages","_FPDF_NewFormObjectFromXObject","_FPDF_NewXObjectFromPage","_FPDF_PageToDevice","_FPDF_RemoveFormFieldHighlight","_FPDF_RenderPage_Close","_FPDF_RenderPage_Continue","_FPDF_RenderPageBitmap","_FPDF_RenderPageBitmap_Start","_FPDF_RenderPageBitmapWithColorScheme_Start","_FPDF_RenderPageBitmapWithMatrix","_FPDF_SaveAsCopy","_FPDF_SaveWithVersion","_FPDF_SetFormFieldHighlightAlpha","_FPDF_SetFormFieldHighlightColor","_FPDF_SetSandBoxPolicy","_FPDF_SetSystemFontInfo","_FPDF_StructElement_Attr_CountChildren","_FPDF_StructElement_Attr_GetBlobValue","_FPDF_StructElement_Attr_GetBooleanValue","_FPDF_StructElement_Attr_GetChildAtIndex","_FPDF_StructElement_Attr_GetCount","_FPDF_StructElement_Attr_GetName","_FPDF_StructElement_Attr_GetNumberValue","_FPDF_StructElement_Attr_GetStringValue","_FPDF_StructElement_Attr_GetType","_FPDF_StructElement_Attr_GetValue","_FPDF_StructElement_CountChildren","_FPDF_StructElement_GetActualText","_FPDF_StructElement_GetAltText","_FPDF_StructElement_GetAttributeAtIndex","_FPDF_StructElement_GetAttributeCount","_FPDF_StructElement_GetChildAtIndex","_FPDF_StructElement_GetChildMarkedContentID","_FPDF_StructElement_GetID","_FPDF_StructElement_GetLang","_FPDF_StructElement_GetMarkedContentID","_FPDF_StructElement_GetMarkedContentIdAtIndex","_FPDF_StructElement_GetMarkedContentIdCount","_FPDF_StructElement_GetObjType","_FPDF_StructElement_GetParent","_FPDF_StructElement_GetStringAttribute","_FPDF_StructElement_GetTitle","_FPDF_StructElement_GetType","_FPDF_StructTree_Close","_FPDF_StructTree_CountChildren","_FPDF_StructTree_GetChildAtIndex","_FPDF_StructTree_GetForPage","_FPDF_VIEWERREF_GetDuplex","_FPDF_VIEWERREF_GetName","_FPDF_VIEWERREF_GetNumCopies","_FPDF_VIEWERREF_GetPrintPageRange","_FPDF_VIEWERREF_GetPrintPageRangeCount","_FPDF_VIEWERREF_GetPrintPageRangeElement","_FPDF_VIEWERREF_GetPrintScaling","_FPDFAction_GetDest","_FPDFAction_GetFilePath","_FPDFAction_GetType","_FPDFAction_GetURIPath","_FPDFAnnot_AddFileAttachment","_FPDFAnnot_AddInkStroke","_FPDFAnnot_AppendAttachmentPoints","_FPDFAnnot_AppendObject","_FPDFAnnot_CountAttachmentPoints","_FPDFAnnot_GetAP","_FPDFAnnot_GetAttachmentPoints","_FPDFAnnot_GetBorder","_FPDFAnnot_GetColor","_FPDFAnnot_GetFileAttachment","_FPDFAnnot_GetFlags","_FPDFAnnot_GetFocusableSubtypes","_FPDFAnnot_GetFocusableSubtypesCount","_FPDFAnnot_GetFontColor","_FPDFAnnot_GetFontSize","_FPDFAnnot_GetFormAdditionalActionJavaScript","_FPDFAnnot_GetFormControlCount","_FPDFAnnot_GetFormControlIndex","_FPDFAnnot_GetFormFieldAlternateName","_FPDFAnnot_GetFormFieldAtPoint","_FPDFAnnot_GetFormFieldExportValue","_FPDFAnnot_GetFormFieldFlags","_FPDFAnnot_GetFormFieldName","_FPDFAnnot_GetFormFieldType","_FPDFAnnot_GetFormFieldValue","_FPDFAnnot_GetInkListCount","_FPDFAnnot_GetInkListPath","_FPDFAnnot_GetLine","_FPDFAnnot_GetLink","_FPDFAnnot_GetLinkedAnnot","_FPDFAnnot_GetNumberValue","_FPDFAnnot_GetObject","_FPDFAnnot_GetObjectCount","_FPDFAnnot_GetOptionCount","_FPDFAnnot_GetOptionLabel","_FPDFAnnot_GetRect","_FPDFAnnot_GetStringValue","_FPDFAnnot_GetSubtype","_FPDFAnnot_GetValueType","_FPDFAnnot_GetVertices","_FPDFAnnot_HasAttachmentPoints","_FPDFAnnot_HasKey","_FPDFAnnot_IsChecked","_FPDFAnnot_IsObjectSupportedSubtype","_FPDFAnnot_IsOptionSelected","_FPDFAnnot_IsSupportedSubtype","_FPDFAnnot_RemoveInkList","_FPDFAnnot_RemoveObject","_FPDFAnnot_SetAP","_FPDFAnnot_SetAttachmentPoints","_FPDFAnnot_SetBorder","_FPDFAnnot_SetColor","_FPDFAnnot_SetFlags","_FPDFAnnot_SetFocusableSubtypes","_FPDFAnnot_SetFontColor","_FPDFAnnot_SetFormFieldFlags","_FPDFAnnot_SetRect","_FPDFAnnot_SetStringValue","_FPDFAnnot_SetURI","_FPDFAnnot_UpdateObject","_FPDFAttachment_GetFile","_FPDFAttachment_GetName","_FPDFAttachment_GetStringValue","_FPDFAttachment_GetSubtype","_FPDFAttachment_GetValueType","_FPDFAttachment_HasKey","_FPDFAttachment_SetFile","_FPDFAttachment_SetStringValue","_FPDFAvail_Create","_FPDFAvail_Destroy","_FPDFAvail_GetDocument","_FPDFAvail_GetFirstPageNum","_FPDFAvail_IsDocAvail","_FPDFAvail_IsFormAvail","_FPDFAvail_IsLinearized","_FPDFAvail_IsPageAvail","_FPDFBitmap_Create","_FPDFBitmap_CreateEx","_FPDFBitmap_Destroy","_FPDFBitmap_FillRect","_FPDFBitmap_GetBuffer","_FPDFBitmap_GetFormat","_FPDFBitmap_GetHeight","_FPDFBitmap_GetStride","_FPDFBitmap_GetWidth","_FPDFBookmark_Find","_FPDFBookmark_GetAction","_FPDFBookmark_GetCount","_FPDFBookmark_GetDest","_FPDFBookmark_GetFirstChild","_FPDFBookmark_GetNextSibling","_FPDFBookmark_GetTitle","_FPDFCatalog_GetLanguage","_FPDFCatalog_IsTagged","_FPDFCatalog_SetLanguage","_FPDFClipPath_CountPaths","_FPDFClipPath_CountPathSegments","_FPDFClipPath_GetPathSegment","_FPDFDest_GetDestPageIndex","_FPDFDest_GetLocationInPage","_FPDFDest_GetView","_FPDFDoc_AddAttachment","_FPDFDoc_CloseJavaScriptAction","_FPDFDoc_DeleteAttachment","_FPDFDOC_ExitFormFillEnvironment","_FPDFDoc_GetAttachment","_FPDFDoc_GetAttachmentCount","_FPDFDoc_GetJavaScriptAction","_FPDFDoc_GetJavaScriptActionCount","_FPDFDoc_GetPageMode","_FPDFDOC_InitFormFillEnvironment","_FPDFFont_Close","_FPDFFont_GetAscent","_FPDFFont_GetBaseFontName","_FPDFFont_GetDescent","_FPDFFont_GetFamilyName","_FPDFFont_GetFlags","_FPDFFont_GetFontData","_FPDFFont_GetGlyphPath","_FPDFFont_GetGlyphWidth","_FPDFFont_GetIsEmbedded","_FPDFFont_GetItalicAngle","_FPDFFont_GetWeight","_FPDFFormObj_CountObjects","_FPDFFormObj_GetObject","_FPDFFormObj_RemoveObject","_FPDFGlyphPath_CountGlyphSegments","_FPDFGlyphPath_GetGlyphPathSegment","_FPDFImageObj_GetBitmap","_FPDFImageObj_GetIccProfileDataDecoded","_FPDFImageObj_GetImageDataDecoded","_FPDFImageObj_GetImageDataRaw","_FPDFImageObj_GetImageFilter","_FPDFImageObj_GetImageFilterCount","_FPDFImageObj_GetImageMetadata","_FPDFImageObj_GetImagePixelSize","_FPDFImageObj_GetRenderedBitmap","_FPDFImageObj_LoadJpegFile","_FPDFImageObj_LoadJpegFileInline","_FPDFImageObj_SetBitmap","_FPDFImageObj_SetMatrix","_FPDFJavaScriptAction_GetName","_FPDFJavaScriptAction_GetScript","_FPDFLink_CloseWebLinks","_FPDFLink_CountQuadPoints","_FPDFLink_CountRects","_FPDFLink_CountWebLinks","_FPDFLink_Enumerate","_FPDFLink_GetAction","_FPDFLink_GetAnnot","_FPDFLink_GetAnnotRect","_FPDFLink_GetDest","_FPDFLink_GetLinkAtPoint","_FPDFLink_GetLinkZOrderAtPoint","_FPDFLink_GetQuadPoints","_FPDFLink_GetRect","_FPDFLink_GetTextRange","_FPDFLink_GetURL","_FPDFLink_LoadWebLinks","_FPDFPage_CloseAnnot","_FPDFPage_CountObjects","_FPDFPage_CreateAnnot","_FPDFPage_Delete","_FPDFPage_Flatten","_FPDFPage_FormFieldZOrderAtPoint","_FPDFPage_GenerateContent","_FPDFPage_GetAnnot","_FPDFPage_GetAnnotCount","_FPDFPage_GetAnnotIndex","_FPDFPage_GetArtBox","_FPDFPage_GetBleedBox","_FPDFPage_GetCropBox","_FPDFPage_GetDecodedThumbnailData","_FPDFPage_GetMediaBox","_FPDFPage_GetObject","_FPDFPage_GetRawThumbnailData","_FPDFPage_GetRotation","_FPDFPage_GetThumbnailAsBitmap","_FPDFPage_GetTrimBox","_FPDFPage_HasFormFieldAtPoint","_FPDFPage_HasTransparency","_FPDFPage_InsertClipPath","_FPDFPage_InsertObject","_FPDFPage_InsertObjectAtIndex","_FPDFPage_New","_FPDFPage_RemoveAnnot","_FPDFPage_RemoveObject","_FPDFPage_SetArtBox","_FPDFPage_SetBleedBox","_FPDFPage_SetCropBox","_FPDFPage_SetMediaBox","_FPDFPage_SetRotation","_FPDFPage_SetTrimBox","_FPDFPage_TransformAnnots","_FPDFPage_TransFormWithClip","_FPDFPageObj_AddMark","_FPDFPageObj_CountMarks","_FPDFPageObj_CreateNewPath","_FPDFPageObj_CreateNewRect","_FPDFPageObj_CreateTextObj","_FPDFPageObj_Destroy","_FPDFPageObj_GetBounds","_FPDFPageObj_GetClipPath","_FPDFPageObj_GetDashArray","_FPDFPageObj_GetDashCount","_FPDFPageObj_GetDashPhase","_FPDFPageObj_GetFillColor","_FPDFPageObj_GetIsActive","_FPDFPageObj_GetLineCap","_FPDFPageObj_GetLineJoin","_FPDFPageObj_GetMark","_FPDFPageObj_GetMarkedContentID","_FPDFPageObj_GetMatrix","_FPDFPageObj_GetRotatedBounds","_FPDFPageObj_GetStrokeColor","_FPDFPageObj_GetStrokeWidth","_FPDFPageObj_GetType","_FPDFPageObj_HasTransparency","_FPDFPageObj_NewImageObj","_FPDFPageObj_NewTextObj","_FPDFPageObj_RemoveMark","_FPDFPageObj_SetBlendMode","_FPDFPageObj_SetDashArray","_FPDFPageObj_SetDashPhase","_FPDFPageObj_SetFillColor","_FPDFPageObj_SetIsActive","_FPDFPageObj_SetLineCap","_FPDFPageObj_SetLineJoin","_FPDFPageObj_SetMatrix","_FPDFPageObj_SetStrokeColor","_FPDFPageObj_SetStrokeWidth","_FPDFPageObj_Transform","_FPDFPageObj_TransformClipPath","_FPDFPageObj_TransformF","_FPDFPageObjMark_CountParams","_FPDFPageObjMark_GetName","_FPDFPageObjMark_GetParamBlobValue","_FPDFPageObjMark_GetParamFloatValue","_FPDFPageObjMark_GetParamIntValue","_FPDFPageObjMark_GetParamKey","_FPDFPageObjMark_GetParamStringValue","_FPDFPageObjMark_GetParamValueType","_FPDFPageObjMark_RemoveParam","_FPDFPageObjMark_SetBlobParam","_FPDFPageObjMark_SetFloatParam","_FPDFPageObjMark_SetIntParam","_FPDFPageObjMark_SetStringParam","_FPDFPath_BezierTo","_FPDFPath_Close","_FPDFPath_CountSegments","_FPDFPath_GetDrawMode","_FPDFPath_GetPathSegment","_FPDFPath_LineTo","_FPDFPath_MoveTo","_FPDFPath_SetDrawMode","_FPDFPathSegment_GetClose","_FPDFPathSegment_GetPoint","_FPDFPathSegment_GetType","_FPDFSignatureObj_GetByteRange","_FPDFSignatureObj_GetContents","_FPDFSignatureObj_GetDocMDPPermission","_FPDFSignatureObj_GetReason","_FPDFSignatureObj_GetSubFilter","_FPDFSignatureObj_GetTime","_FPDFText_ClosePage","_FPDFText_CountChars","_FPDFText_CountRects","_FPDFText_FindClose","_FPDFText_FindNext","_FPDFText_FindPrev","_FPDFText_FindStart","_FPDFText_GetBoundedText","_FPDFText_GetCharAngle","_FPDFText_GetCharBox","_FPDFText_GetCharIndexAtPos","_FPDFText_GetCharIndexFromTextIndex","_FPDFText_GetCharOrigin","_FPDFText_GetFillColor","_FPDFText_GetFontInfo","_FPDFText_GetFontSize","_FPDFText_GetFontWeight","_FPDFText_GetLooseCharBox","_FPDFText_GetMatrix","_FPDFText_GetRect","_FPDFText_GetSchCount","_FPDFText_GetSchResultIndex","_FPDFText_GetStrokeColor","_FPDFText_GetText","_FPDFText_GetTextIndexFromCharIndex","_FPDFText_GetTextObject","_FPDFText_GetUnicode","_FPDFText_HasUnicodeMapError","_FPDFText_IsGenerated","_FPDFText_IsHyphen","_FPDFText_LoadCidType2Font","_FPDFText_LoadFont","_FPDFText_LoadPage","_FPDFText_LoadStandardFont","_FPDFText_SetCharcodes","_FPDFText_SetText","_FPDFTextObj_GetFont","_FPDFTextObj_GetFontSize","_FPDFTextObj_GetRenderedBitmap","_FPDFTextObj_GetText","_FPDFTextObj_GetTextRenderMode","_FPDFTextObj_SetTextRenderMode","_PDFiumExt_CloseFileWriter","_PDFiumExt_CloseFormFillInfo","_PDFiumExt_ExitFormFillEnvironment","_PDFiumExt_GetFileWriterData","_PDFiumExt_GetFileWriterSize","_PDFiumExt_Init","_PDFiumExt_InitFormFillEnvironment","_PDFiumExt_OpenFileWriter","_PDFiumExt_OpenFormFillInfo","_PDFiumExt_SaveAsCopy","_malloc","_free","_memory","___indirect_function_table","onRuntimeInitialized"].forEach(e=>{Object.getOwnPropertyDescriptor(a,e)||Object.defineProperty(a,e,{get:()=>W("You are getting "+e+" on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js"),set:()=>W("You are setting "+e+" on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js")})});var i="object"==typeof window,s="function"==typeof importScripts;"object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node&&process.type;var u,m,F=!i&&!s,l=Object.assign({},o),d="./this.program",c="";if(F){if("object"==typeof window||"function"==typeof importScripts)throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");m=e=>{if("function"==typeof readbuffer)return new Uint8Array(readbuffer(e));let t=read(e,"binary");return C("object"==typeof t),t},u=e=>new Promise((t,n)=>{setTimeout(()=>t(m(e)))}),globalThis.clearTimeout??=e=>{},globalThis.setTimeout??=e=>"function"==typeof e?e():W(),"undefined"!=typeof print&&(globalThis.console??={},console.log=print,console.warn=console.error=globalThis.printErr??print)}else{if(!i&&!s)throw new Error("environment detection error");if(s?c=self.location.href:"undefined"!=typeof document&&document.currentScript&&(c=document.currentScript.src),V&&(c=V),c=c.startsWith("blob:")?"":c.substr(0,c.replace(/[?#].*/,"").lastIndexOf("/")+1),"object"!=typeof window&&"function"!=typeof importScripts)throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");s&&(m=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),u=e=>(C(!J(e),"readAsync does not work with file:// URLs"),fetch(e,{credentials:"same-origin"}).then(e=>e.ok?e.arrayBuffer():Promise.reject(new Error(e.status+" : "+e.url))))}var P,_=o.print||console.log.bind(console),g=o.printErr||console.error.bind(console);Object.assign(o,l),l=null,P="fetchSettings",Object.getOwnPropertyDescriptor(o,P)&&W(`\`Module.${P}\` was supplied but \`${P}\` not included in INCOMING_MODULE_JS_API`),o.arguments&&o.arguments,te("arguments","arguments_"),o.thisProgram&&(d=o.thisProgram),te("thisProgram","thisProgram"),C(void 0===o.memoryInitializerPrefixURL,"Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead"),C(void 0===o.pthreadMainPrefixURL,"Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead"),C(void 0===o.cdInitializerPrefixURL,"Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead"),C(void 0===o.filePackagePrefixURL,"Module.filePackagePrefixURL option was removed, use Module.locateFile instead"),C(void 0===o.read,"Module.read option was removed"),C(void 0===o.readAsync,"Module.readAsync option was removed (modify readAsync in JS)"),C(void 0===o.readBinary,"Module.readBinary option was removed (modify readBinary in JS)"),C(void 0===o.setWindowTitle,"Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)"),C(void 0===o.TOTAL_MEMORY,"Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY"),te("asm","wasmExports"),te("readAsync","readAsync"),te("readBinary","readBinary"),te("setWindowTitle","setWindowTitle");var h,D=o.wasmBinary;te("wasmBinary","wasmBinary"),"object"!=typeof WebAssembly&&g("no native wasm support detected");var b,p,f,A,E,y,M,G,S=!1;function C(e,t){e||W("Assertion failed"+(t?": "+t:""))}function x(){var e=h.buffer;o.HEAP8=b=new Int8Array(e),o.HEAP16=f=new Int16Array(e),o.HEAPU8=p=new Uint8Array(e),o.HEAPU16=A=new Uint16Array(e),o.HEAP32=E=new Int32Array(e),o.HEAPU32=y=new Uint32Array(e),o.HEAPF32=M=new Float32Array(e),o.HEAPF64=G=new Float64Array(e)}function T(){if(!S){var e=it();0==e&&(e+=4);var t=y[e>>2],n=y[e+4>>2];34821223==t&&2310721022==n||W(`Stack overflow! Stack cookie has been overwritten at ${se(e)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${se(n)} ${se(t)}`),1668509029!=y[0]&&W("Runtime error: The application has corrupted its heap memory area (address zero)!")}}C(!o.STACK_SIZE,"STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time"),C("undefined"!=typeof Int32Array&&"undefined"!=typeof Float64Array&&null!=Int32Array.prototype.subarray&&null!=Int32Array.prototype.set,"JS engine does not provide full typed array support"),C(!o.wasmMemory,"Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally"),C(!o.INITIAL_MEMORY,"Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically");var v=[],O=[],R=[],k=!1;function w(e){v.unshift(e)}function I(e){R.unshift(e)}C(Math.imul,"This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"),C(Math.fround,"This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"),C(Math.clz32,"This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"),C(Math.trunc,"This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill");var B=0,j=null,L=null,N={};function U(e){for(var t=e;;){if(!N[e])return e;e=t+Math.random()}}function z(e){B++,o.monitorRunDependencies?.(B),e?(C(!N[e]),N[e]=1,null===j&&"undefined"!=typeof setInterval&&(j=setInterval(()=>{if(S)return clearInterval(j),void(j=null);var e=!1;for(var t in N)e||(e=!0,g("still waiting on run dependencies:")),g(`dependency: ${t}`);e&&g("(end of list)")},1e4))):g("warning: run dependency added without ID")}function $(e){if(B--,o.monitorRunDependencies?.(B),e?(C(N[e]),delete N[e]):g("warning: run dependency removed without ID"),0==B&&(null!==j&&(clearInterval(j),j=null),L)){var t=L;L=null,t()}}function W(e){o.onAbort?.(e),g(e="Aborted("+e+")"),S=!0;var t=new WebAssembly.RuntimeError(e);throw r(t),t}var H,Y,X,K=e=>e.startsWith("data:application/octet-stream;base64,"),J=e=>e.startsWith("file://");function q(e,t){return(...n)=>{C(k,`native function \`${e}\` called before runtime initialization`);var r=Qe[e];return C(r,`exported native function \`${e}\` not found`),C(n.length<=t,`native function \`${e}\` called with ${n.length} args but expects ${t}`),r(...n)}}function Q(){if(o.locateFile){var e="pdfium.wasm";return K(e)?e:(t=e,o.locateFile?o.locateFile(t,c):c+t)}var t;return F?"pdfium.wasm":new URL("pdfium.wasm",import.meta.url).href}function Z(e){if(e==H&&D)return new Uint8Array(D);if(m)return m(e);throw"both async and sync fetching of the wasm failed"}function ee(e,t,n){return function(e){return D?Promise.resolve().then(()=>Z(e)):u(e).then(e=>new Uint8Array(e),()=>Z(e))}(e).then(e=>WebAssembly.instantiate(e,t)).then(n,e=>{g(`failed to asynchronously prepare wasm: ${e}`),J(H)&&g(`warning: Loading from a file URI (${H}) is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing`),W(e)})}if((()=>{var e=new Int16Array(1),t=new Int8Array(e.buffer);if(e[0]=25459,115!==t[0]||99!==t[1])throw"Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)"})(),o.ENVIRONMENT)throw new Error("Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)");function te(e,t,n=!0){Object.getOwnPropertyDescriptor(o,e)||Object.defineProperty(o,e,{configurable:!0,get(){W(`\`Module.${e}\` has been replaced by \`${t}\``+(n?" (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)":""))}})}function ne(e){return"FS_createPath"===e||"FS_createDataFile"===e||"FS_createPreloadedFile"===e||"FS_unlink"===e||"addRunDependency"===e||"FS_createLazyFile"===e||"FS_createDevice"===e||"removeRunDependency"===e}function re(e,t){"undefined"==typeof globalThis||Object.getOwnPropertyDescriptor(globalThis,e)||Object.defineProperty(globalThis,e,{configurable:!0,get(){t()}})}function oe(e,t){re(e,()=>{Fe(`\`${e}\` is not longer defined by emscripten. ${t}`)})}function ae(e){Object.getOwnPropertyDescriptor(o,e)||Object.defineProperty(o,e,{configurable:!0,get(){var t=`'${e}' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)`;ne(e)&&(t+=". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you"),W(t)}})}oe("buffer","Please use HEAP8.buffer or wasmMemory.buffer"),oe("asm","Please use wasmExports instead");var ie=e=>{e.forEach(e=>e(o))};o.noExitRuntime;var se=e=>(C("number"==typeof e),"0x"+(e>>>=0).toString(16).padStart(8,"0")),ue=e=>st(e),me=()=>mt(),Fe=e=>{Fe.shown||={},Fe.shown[e]||(Fe.shown[e]=1,g(e))},le="undefined"!=typeof TextDecoder?new TextDecoder:void 0,de=(e,t=0,n=NaN)=>{for(var r=t+n,o=t;e[o]&&!(o>=r);)++o;if(o-t>16&&e.buffer&&le)return le.decode(e.subarray(t,o));for(var a="";t>10,56320|1023&m)}}else a+=String.fromCharCode((31&i)<<6|s)}else a+=String.fromCharCode(i)}return a},ce=(e,t)=>(C("number"==typeof e,`UTF8ToString expects a number (got ${typeof e})`),e?de(p,e,t):"");function Pe(){C(null!=Re.varargs);var e=E[+Re.varargs>>2];return Re.varargs+=4,e}var _e=Pe,ge={isAbs:e=>"/"===e.charAt(0),splitPath:e=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1),normalizeArray:(e,t)=>{for(var n=0,r=e.length-1;r>=0;r--){var o=e[r];"."===o?e.splice(r,1):".."===o?(e.splice(r,1),n++):n&&(e.splice(r,1),n--)}if(t)for(;n;n--)e.unshift("..");return e},normalize:e=>{var t=ge.isAbs(e),n="/"===e.substr(-1);return(e=ge.normalizeArray(e.split("/").filter(e=>!!e),!t).join("/"))||t||(e="."),e&&n&&(e+="/"),(t?"/":"")+e},dirname:e=>{var t=ge.splitPath(e),n=t[0],r=t[1];return n||r?(r&&(r=r.substr(0,r.length-1)),n+r):"."},basename:e=>{if("/"===e)return"/";var t=(e=(e=ge.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)},join:(...e)=>ge.normalize(e.join("/")),join2:(e,t)=>ge.normalize(e+"/"+t)},he=e=>(he=(()=>{if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues)return e=>crypto.getRandomValues(e);W("no cryptographic support found for randomDevice. consider polyfilling it if you want to use something insecure like Math.random(), e.g. put this in a --pre-js: var crypto = { getRandomValues: (array) => { for (var i = 0; i < array.length; i++) array[i] = (Math.random()*256)|0 } };")})())(e),De={resolve:(...e)=>{for(var t="",n=!1,r=e.length-1;r>=-1&&!n;r--){var o=r>=0?e[r]:Oe.cwd();if("string"!=typeof o)throw new TypeError("Arguments to path.resolve must be strings");if(!o)return"";t=o+"/"+t,n=ge.isAbs(o)}return(n?"/":"")+(t=ge.normalizeArray(t.split("/").filter(e=>!!e),!n).join("/"))||"."},relative:(e,t)=>{function n(e){for(var t=0;t=0&&""===e[n];n--);return t>n?[]:e.slice(t,n-t+1)}e=De.resolve(e).substr(1),t=De.resolve(t).substr(1);for(var r=n(e.split("/")),o=n(t.split("/")),a=Math.min(r.length,o.length),i=a,s=0;s{for(var t=0,n=0;n=55296&&r<=57343?(t+=4,++n):t+=3}return t},fe=(e,t,n,r)=>{if(C("string"==typeof e,`stringToUTF8Array expects a string (got ${typeof e})`),!(r>0))return 0;for(var o=n,a=n+r-1,i=0;i=55296&&s<=57343&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++i)),s<=127){if(n>=a)break;t[n++]=s}else if(s<=2047){if(n+1>=a)break;t[n++]=192|s>>6,t[n++]=128|63&s}else if(s<=65535){if(n+2>=a)break;t[n++]=224|s>>12,t[n++]=128|s>>6&63,t[n++]=128|63&s}else{if(n+3>=a)break;s>1114111&&Fe("Invalid Unicode code point "+se(s)+" encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF)."),t[n++]=240|s>>18,t[n++]=128|s>>12&63,t[n++]=128|s>>6&63,t[n++]=128|63&s}}return t[n]=0,n-o};function Ae(e,t,n){var r=pe(e)+1,o=new Array(r),a=fe(e,o,0,o.length);return o.length=a,o}var Ee,ye,Me={ttys:[],init(){},shutdown(){},register(e,t){Me.ttys[e]={input:[],output:[],ops:t},Oe.registerDevice(e,Me.stream_ops)},stream_ops:{open(e){var t=Me.ttys[e.node.rdev];if(!t)throw new Oe.ErrnoError(43);e.tty=t,e.seekable=!1},close(e){e.tty.ops.fsync(e.tty)},fsync(e){e.tty.ops.fsync(e.tty)},read(e,t,n,r,o){if(!e.tty||!e.tty.ops.get_char)throw new Oe.ErrnoError(60);for(var a=0,i=0;i(()=>{if(!be.length){var e=null;if("undefined"!=typeof window&&"function"==typeof window.prompt?null!==(e=window.prompt("Input: "))&&(e+="\n"):"function"==typeof readline&&(e=readline())&&(e+="\n"),!e)return null;be=Ae(e)}return be.shift()})(),put_char(e,t){null===t||10===t?(_(de(e.output)),e.output=[]):0!=t&&e.output.push(t)},fsync(e){e.output&&e.output.length>0&&(_(de(e.output)),e.output=[])},ioctl_tcgets:e=>({c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}),ioctl_tcsets:(e,t,n)=>0,ioctl_tiocgwinsz:e=>[24,80]},default_tty1_ops:{put_char(e,t){null===t||10===t?(g(de(e.output)),e.output=[]):0!=t&&e.output.push(t)},fsync(e){e.output&&e.output.length>0&&(g(de(e.output)),e.output=[])}}},Ge=(e,t)=>(C(t,"alignment argument is required"),Math.ceil(e/t)*t),Se=e=>{e=Ge(e,65536);var t=nt(65536,e);return t&&((e,t)=>{p.fill(0,e,e+t)})(t,e),t},Ce={ops_table:null,mount:e=>Ce.createNode(null,"/",16895,0),createNode(e,t,n,r){if(Oe.isBlkdev(n)||Oe.isFIFO(n))throw new Oe.ErrnoError(63);Ce.ops_table||={dir:{node:{getattr:Ce.node_ops.getattr,setattr:Ce.node_ops.setattr,lookup:Ce.node_ops.lookup,mknod:Ce.node_ops.mknod,rename:Ce.node_ops.rename,unlink:Ce.node_ops.unlink,rmdir:Ce.node_ops.rmdir,readdir:Ce.node_ops.readdir,symlink:Ce.node_ops.symlink},stream:{llseek:Ce.stream_ops.llseek}},file:{node:{getattr:Ce.node_ops.getattr,setattr:Ce.node_ops.setattr},stream:{llseek:Ce.stream_ops.llseek,read:Ce.stream_ops.read,write:Ce.stream_ops.write,allocate:Ce.stream_ops.allocate,mmap:Ce.stream_ops.mmap,msync:Ce.stream_ops.msync}},link:{node:{getattr:Ce.node_ops.getattr,setattr:Ce.node_ops.setattr,readlink:Ce.node_ops.readlink},stream:{}},chrdev:{node:{getattr:Ce.node_ops.getattr,setattr:Ce.node_ops.setattr},stream:Oe.chrdev_stream_ops}};var o=Oe.createNode(e,t,n,r);return Oe.isDir(o.mode)?(o.node_ops=Ce.ops_table.dir.node,o.stream_ops=Ce.ops_table.dir.stream,o.contents={}):Oe.isFile(o.mode)?(o.node_ops=Ce.ops_table.file.node,o.stream_ops=Ce.ops_table.file.stream,o.usedBytes=0,o.contents=null):Oe.isLink(o.mode)?(o.node_ops=Ce.ops_table.link.node,o.stream_ops=Ce.ops_table.link.stream):Oe.isChrdev(o.mode)&&(o.node_ops=Ce.ops_table.chrdev.node,o.stream_ops=Ce.ops_table.chrdev.stream),o.timestamp=Date.now(),e&&(e.contents[t]=o,e.timestamp=o.timestamp),o},getFileDataAsTypedArray:e=>e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0),expandFileStorage(e,t){var n=e.contents?e.contents.length:0;if(!(n>=t)){t=Math.max(t,n*(n<1048576?2:1.125)>>>0),0!=n&&(t=Math.max(t,256));var r=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(r.subarray(0,e.usedBytes),0)}},resizeFileStorage(e,t){if(e.usedBytes!=t)if(0==t)e.contents=null,e.usedBytes=0;else{var n=e.contents;e.contents=new Uint8Array(t),n&&e.contents.set(n.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}},node_ops:{getattr(e){var t={};return t.dev=Oe.isChrdev(e.mode)?e.id:1,t.ino=e.id,t.mode=e.mode,t.nlink=1,t.uid=0,t.gid=0,t.rdev=e.rdev,Oe.isDir(e.mode)?t.size=4096:Oe.isFile(e.mode)?t.size=e.usedBytes:Oe.isLink(e.mode)?t.size=e.link.length:t.size=0,t.atime=new Date(e.timestamp),t.mtime=new Date(e.timestamp),t.ctime=new Date(e.timestamp),t.blksize=4096,t.blocks=Math.ceil(t.size/t.blksize),t},setattr(e,t){void 0!==t.mode&&(e.mode=t.mode),void 0!==t.timestamp&&(e.timestamp=t.timestamp),void 0!==t.size&&Ce.resizeFileStorage(e,t.size)},lookup(e,t){throw Oe.genericErrors[44]},mknod:(e,t,n,r)=>Ce.createNode(e,t,n,r),rename(e,t,n){if(Oe.isDir(e.mode)){var r;try{r=Oe.lookupNode(t,n)}catch(e){}if(r)for(var o in r.contents)throw new Oe.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=n,t.contents[n]=e,t.timestamp=e.parent.timestamp},unlink(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir(e,t){var n=Oe.lookupNode(e,t);for(var r in n.contents)throw new Oe.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir(e){var t=[".",".."];for(var n of Object.keys(e.contents))t.push(n);return t},symlink(e,t,n){var r=Ce.createNode(e,t,41471,0);return r.link=n,r},readlink(e){if(!Oe.isLink(e.mode))throw new Oe.ErrnoError(28);return e.link}},stream_ops:{read(e,t,n,r,o){var a=e.node.contents;if(o>=e.node.usedBytes)return 0;var i=Math.min(e.node.usedBytes-o,r);if(C(i>=0),i>8&&a.subarray)t.set(a.subarray(o,o+i),n);else for(var s=0;s0||n+t(Ce.stream_ops.write(e,t,0,r,n,!1),0)}},xe=o.preloadPlugins||[],Te=(e,t)=>{var n=0;return e&&(n|=365),t&&(n|=146),n},ve={EPERM:63,ENOENT:44,ESRCH:71,EINTR:27,EIO:29,ENXIO:60,E2BIG:1,ENOEXEC:45,EBADF:8,ECHILD:12,EAGAIN:6,EWOULDBLOCK:6,ENOMEM:48,EACCES:2,EFAULT:21,ENOTBLK:105,EBUSY:10,EEXIST:20,EXDEV:75,ENODEV:43,ENOTDIR:54,EISDIR:31,EINVAL:28,ENFILE:41,EMFILE:33,ENOTTY:59,ETXTBSY:74,EFBIG:22,ENOSPC:51,ESPIPE:70,EROFS:69,EMLINK:34,EPIPE:64,EDOM:18,ERANGE:68,ENOMSG:49,EIDRM:24,ECHRNG:106,EL2NSYNC:156,EL3HLT:107,EL3RST:108,ELNRNG:109,EUNATCH:110,ENOCSI:111,EL2HLT:112,EDEADLK:16,ENOLCK:46,EBADE:113,EBADR:114,EXFULL:115,ENOANO:104,EBADRQC:103,EBADSLT:102,EDEADLOCK:16,EBFONT:101,ENOSTR:100,ENODATA:116,ETIME:117,ENOSR:118,ENONET:119,ENOPKG:120,EREMOTE:121,ENOLINK:47,EADV:122,ESRMNT:123,ECOMM:124,EPROTO:65,EMULTIHOP:36,EDOTDOT:125,EBADMSG:9,ENOTUNIQ:126,EBADFD:127,EREMCHG:128,ELIBACC:129,ELIBBAD:130,ELIBSCN:131,ELIBMAX:132,ELIBEXEC:133,ENOSYS:52,ENOTEMPTY:55,ENAMETOOLONG:37,ELOOP:32,EOPNOTSUPP:138,EPFNOSUPPORT:139,ECONNRESET:15,ENOBUFS:42,EAFNOSUPPORT:5,EPROTOTYPE:67,ENOTSOCK:57,ENOPROTOOPT:50,ESHUTDOWN:140,ECONNREFUSED:14,EADDRINUSE:3,ECONNABORTED:13,ENETUNREACH:40,ENETDOWN:38,ETIMEDOUT:73,EHOSTDOWN:142,EHOSTUNREACH:23,EINPROGRESS:26,EALREADY:7,EDESTADDRREQ:17,EMSGSIZE:35,EPROTONOSUPPORT:66,ESOCKTNOSUPPORT:137,EADDRNOTAVAIL:4,ENETRESET:39,EISCONN:30,ENOTCONN:53,ETOOMANYREFS:141,EUSERS:136,EDQUOT:19,ESTALE:72,ENOTSUP:138,ENOMEDIUM:148,EILSEQ:25,EOVERFLOW:61,ECANCELED:11,ENOTRECOVERABLE:56,EOWNERDEAD:62,ESTRPIPE:135},Oe={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:class extends Error{constructor(e){for(var t in super(k?(e=>ce(rt(e)))(e):""),this.name="ErrnoError",this.errno=e,ve)if(ve[t]===e){this.code=t;break}}},genericErrors:{},filesystems:null,syncFSRequests:0,readFiles:{},FSStream:class{constructor(){this.shared={}}get object(){return this.node}set object(e){this.node=e}get isRead(){return 1!=(2097155&this.flags)}get isWrite(){return!!(2097155&this.flags)}get isAppend(){return 1024&this.flags}get flags(){return this.shared.flags}set flags(e){this.shared.flags=e}get position(){return this.shared.position}set position(e){this.shared.position=e}},FSNode:class{constructor(e,t,n,r){e||(e=this),this.parent=e,this.mount=e.mount,this.mounted=null,this.id=Oe.nextInode++,this.name=t,this.mode=n,this.node_ops={},this.stream_ops={},this.rdev=r,this.readMode=365,this.writeMode=146}get read(){return(this.mode&this.readMode)===this.readMode}set read(e){e?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(e){e?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return Oe.isDir(this.mode)}get isDevice(){return Oe.isChrdev(this.mode)}},lookupPath(e,t={}){if(!(e=De.resolve(e)))return{path:"",node:null};if((t=Object.assign({follow_mount:!0,recurse_count:0},t)).recurse_count>8)throw new Oe.ErrnoError(32);for(var n=e.split("/").filter(e=>!!e),r=Oe.root,o="/",a=0;a40)throw new Oe.ErrnoError(32)}}return{path:o,node:r}},getPath(e){for(var t;;){if(Oe.isRoot(e)){var n=e.mount.mountpoint;return t?"/"!==n[n.length-1]?`${n}/${t}`:n+t:n}t=t?`${e.name}/${t}`:e.name,e=e.parent}},hashName(e,t){for(var n=0,r=0;r>>0)%Oe.nameTable.length},hashAddNode(e){var t=Oe.hashName(e.parent.id,e.name);e.name_next=Oe.nameTable[t],Oe.nameTable[t]=e},hashRemoveNode(e){var t=Oe.hashName(e.parent.id,e.name);if(Oe.nameTable[t]===e)Oe.nameTable[t]=e.name_next;else for(var n=Oe.nameTable[t];n;){if(n.name_next===e){n.name_next=e.name_next;break}n=n.name_next}},lookupNode(e,t){var n=Oe.mayLookup(e);if(n)throw new Oe.ErrnoError(n);for(var r=Oe.hashName(e.id,t),o=Oe.nameTable[r];o;o=o.name_next){var a=o.name;if(o.parent.id===e.id&&a===t)return o}return Oe.lookup(e,t)},createNode(e,t,n,r){C("object"==typeof e);var o=new Oe.FSNode(e,t,n,r);return Oe.hashAddNode(o),o},destroyNode(e){Oe.hashRemoveNode(e)},isRoot:e=>e===e.parent,isMountpoint:e=>!!e.mounted,isFile:e=>32768==(61440&e),isDir:e=>16384==(61440&e),isLink:e=>40960==(61440&e),isChrdev:e=>8192==(61440&e),isBlkdev:e=>24576==(61440&e),isFIFO:e=>4096==(61440&e),isSocket:e=>!(49152&~e),flagsToPermissionString(e){var t=["r","w","rw"][3&e];return 512&e&&(t+="w"),t},nodePermissions:(e,t)=>Oe.ignorePermissions||(!t.includes("r")||292&e.mode)&&(!t.includes("w")||146&e.mode)&&(!t.includes("x")||73&e.mode)?0:2,mayLookup(e){if(!Oe.isDir(e.mode))return 54;var t=Oe.nodePermissions(e,"x");return t||(e.node_ops.lookup?0:2)},mayCreate(e,t){try{return Oe.lookupNode(e,t),20}catch(e){}return Oe.nodePermissions(e,"wx")},mayDelete(e,t,n){var r;try{r=Oe.lookupNode(e,t)}catch(e){return e.errno}var o=Oe.nodePermissions(e,"wx");if(o)return o;if(n){if(!Oe.isDir(r.mode))return 54;if(Oe.isRoot(r)||Oe.getPath(r)===Oe.cwd())return 10}else if(Oe.isDir(r.mode))return 31;return 0},mayOpen:(e,t)=>e?Oe.isLink(e.mode)?32:Oe.isDir(e.mode)&&("r"!==Oe.flagsToPermissionString(t)||512&t)?31:Oe.nodePermissions(e,Oe.flagsToPermissionString(t)):44,MAX_OPEN_FDS:4096,nextfd(){for(var e=0;e<=Oe.MAX_OPEN_FDS;e++)if(!Oe.streams[e])return e;throw new Oe.ErrnoError(33)},getStreamChecked(e){var t=Oe.getStream(e);if(!t)throw new Oe.ErrnoError(8);return t},getStream:e=>Oe.streams[e],createStream:(e,t=-1)=>(C(t>=-1),e=Object.assign(new Oe.FSStream,e),-1==t&&(t=Oe.nextfd()),e.fd=t,Oe.streams[t]=e,e),closeStream(e){Oe.streams[e]=null},dupStream(e,t=-1){var n=Oe.createStream(e,t);return n.stream_ops?.dup?.(n),n},chrdev_stream_ops:{open(e){var t=Oe.getDevice(e.node.rdev);e.stream_ops=t.stream_ops,e.stream_ops.open?.(e)},llseek(){throw new Oe.ErrnoError(70)}},major:e=>e>>8,minor:e=>255&e,makedev:(e,t)=>e<<8|t,registerDevice(e,t){Oe.devices[e]={stream_ops:t}},getDevice:e=>Oe.devices[e],getMounts(e){for(var t=[],n=[e];n.length;){var r=n.pop();t.push(r),n.push(...r.mounts)}return t},syncfs(e,t){"function"==typeof e&&(t=e,e=!1),Oe.syncFSRequests++,Oe.syncFSRequests>1&&g(`warning: ${Oe.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var n=Oe.getMounts(Oe.root.mount),r=0;function o(e){return C(Oe.syncFSRequests>0),Oe.syncFSRequests--,t(e)}function a(e){if(e)return a.errored?void 0:(a.errored=!0,o(e));++r>=n.length&&o(null)}n.forEach(t=>{if(!t.type.syncfs)return a(null);t.type.syncfs(t,e,a)})},mount(e,t,n){if("string"==typeof e)throw e;var r,o="/"===n,a=!n;if(o&&Oe.root)throw new Oe.ErrnoError(10);if(!o&&!a){var i=Oe.lookupPath(n,{follow_mount:!1});if(n=i.path,r=i.node,Oe.isMountpoint(r))throw new Oe.ErrnoError(10);if(!Oe.isDir(r.mode))throw new Oe.ErrnoError(54)}var s={type:e,opts:t,mountpoint:n,mounts:[]},u=e.mount(s);return u.mount=s,s.root=u,o?Oe.root=u:r&&(r.mounted=s,r.mount&&r.mount.mounts.push(s)),u},unmount(e){var t=Oe.lookupPath(e,{follow_mount:!1});if(!Oe.isMountpoint(t.node))throw new Oe.ErrnoError(28);var n=t.node,r=n.mounted,o=Oe.getMounts(r);Object.keys(Oe.nameTable).forEach(e=>{for(var t=Oe.nameTable[e];t;){var n=t.name_next;o.includes(t.mount)&&Oe.destroyNode(t),t=n}}),n.mounted=null;var a=n.mount.mounts.indexOf(r);C(-1!==a),n.mount.mounts.splice(a,1)},lookup:(e,t)=>e.node_ops.lookup(e,t),mknod(e,t,n){var r=Oe.lookupPath(e,{parent:!0}).node,o=ge.basename(e);if(!o||"."===o||".."===o)throw new Oe.ErrnoError(28);var a=Oe.mayCreate(r,o);if(a)throw new Oe.ErrnoError(a);if(!r.node_ops.mknod)throw new Oe.ErrnoError(63);return r.node_ops.mknod(r,o,t,n)},create:(e,t)=>(t=void 0!==t?t:438,t&=4095,t|=32768,Oe.mknod(e,t,0)),mkdir:(e,t)=>(t=void 0!==t?t:511,t&=1023,t|=16384,Oe.mknod(e,t,0)),mkdirTree(e,t){for(var n=e.split("/"),r="",o=0;o(void 0===n&&(n=t,t=438),t|=8192,Oe.mknod(e,t,n)),symlink(e,t){if(!De.resolve(e))throw new Oe.ErrnoError(44);var n=Oe.lookupPath(t,{parent:!0}).node;if(!n)throw new Oe.ErrnoError(44);var r=ge.basename(t),o=Oe.mayCreate(n,r);if(o)throw new Oe.ErrnoError(o);if(!n.node_ops.symlink)throw new Oe.ErrnoError(63);return n.node_ops.symlink(n,r,e)},rename(e,t){var n,r,o=ge.dirname(e),a=ge.dirname(t),i=ge.basename(e),s=ge.basename(t);if(n=Oe.lookupPath(e,{parent:!0}).node,r=Oe.lookupPath(t,{parent:!0}).node,!n||!r)throw new Oe.ErrnoError(44);if(n.mount!==r.mount)throw new Oe.ErrnoError(75);var u,m=Oe.lookupNode(n,i),F=De.relative(e,a);if("."!==F.charAt(0))throw new Oe.ErrnoError(28);if("."!==(F=De.relative(t,o)).charAt(0))throw new Oe.ErrnoError(55);try{u=Oe.lookupNode(r,s)}catch(e){}if(m!==u){var l=Oe.isDir(m.mode),d=Oe.mayDelete(n,i,l);if(d)throw new Oe.ErrnoError(d);if(d=u?Oe.mayDelete(r,s,l):Oe.mayCreate(r,s))throw new Oe.ErrnoError(d);if(!n.node_ops.rename)throw new Oe.ErrnoError(63);if(Oe.isMountpoint(m)||u&&Oe.isMountpoint(u))throw new Oe.ErrnoError(10);if(r!==n&&(d=Oe.nodePermissions(n,"w")))throw new Oe.ErrnoError(d);Oe.hashRemoveNode(m);try{n.node_ops.rename(m,r,s),m.parent=r}catch(e){throw e}finally{Oe.hashAddNode(m)}}},rmdir(e){var t=Oe.lookupPath(e,{parent:!0}).node,n=ge.basename(e),r=Oe.lookupNode(t,n),o=Oe.mayDelete(t,n,!0);if(o)throw new Oe.ErrnoError(o);if(!t.node_ops.rmdir)throw new Oe.ErrnoError(63);if(Oe.isMountpoint(r))throw new Oe.ErrnoError(10);t.node_ops.rmdir(t,n),Oe.destroyNode(r)},readdir(e){var t=Oe.lookupPath(e,{follow:!0}).node;if(!t.node_ops.readdir)throw new Oe.ErrnoError(54);return t.node_ops.readdir(t)},unlink(e){var t=Oe.lookupPath(e,{parent:!0}).node;if(!t)throw new Oe.ErrnoError(44);var n=ge.basename(e),r=Oe.lookupNode(t,n),o=Oe.mayDelete(t,n,!1);if(o)throw new Oe.ErrnoError(o);if(!t.node_ops.unlink)throw new Oe.ErrnoError(63);if(Oe.isMountpoint(r))throw new Oe.ErrnoError(10);t.node_ops.unlink(t,n),Oe.destroyNode(r)},readlink(e){var t=Oe.lookupPath(e).node;if(!t)throw new Oe.ErrnoError(44);if(!t.node_ops.readlink)throw new Oe.ErrnoError(28);return De.resolve(Oe.getPath(t.parent),t.node_ops.readlink(t))},stat(e,t){var n=Oe.lookupPath(e,{follow:!t}).node;if(!n)throw new Oe.ErrnoError(44);if(!n.node_ops.getattr)throw new Oe.ErrnoError(63);return n.node_ops.getattr(n)},lstat:e=>Oe.stat(e,!0),chmod(e,t,n){var r;if(!(r="string"==typeof e?Oe.lookupPath(e,{follow:!n}).node:e).node_ops.setattr)throw new Oe.ErrnoError(63);r.node_ops.setattr(r,{mode:4095&t|-4096&r.mode,timestamp:Date.now()})},lchmod(e,t){Oe.chmod(e,t,!0)},fchmod(e,t){var n=Oe.getStreamChecked(e);Oe.chmod(n.node,t)},chown(e,t,n,r){var o;if(!(o="string"==typeof e?Oe.lookupPath(e,{follow:!r}).node:e).node_ops.setattr)throw new Oe.ErrnoError(63);o.node_ops.setattr(o,{timestamp:Date.now()})},lchown(e,t,n){Oe.chown(e,t,n,!0)},fchown(e,t,n){var r=Oe.getStreamChecked(e);Oe.chown(r.node,t,n)},truncate(e,t){if(t<0)throw new Oe.ErrnoError(28);var n;if(!(n="string"==typeof e?Oe.lookupPath(e,{follow:!0}).node:e).node_ops.setattr)throw new Oe.ErrnoError(63);if(Oe.isDir(n.mode))throw new Oe.ErrnoError(31);if(!Oe.isFile(n.mode))throw new Oe.ErrnoError(28);var r=Oe.nodePermissions(n,"w");if(r)throw new Oe.ErrnoError(r);n.node_ops.setattr(n,{size:t,timestamp:Date.now()})},ftruncate(e,t){var n=Oe.getStreamChecked(e);if(!(2097155&n.flags))throw new Oe.ErrnoError(28);Oe.truncate(n.node,t)},utime(e,t,n){var r=Oe.lookupPath(e,{follow:!0}).node;r.node_ops.setattr(r,{timestamp:Math.max(t,n)})},open(e,t,n){if(""===e)throw new Oe.ErrnoError(44);var r;if(n=64&(t="string"==typeof t?(e=>{var t={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[e];if(void 0===t)throw new Error(`Unknown file open mode: ${e}`);return t})(t):t)?4095&(n=void 0===n?438:n)|32768:0,"object"==typeof e)r=e;else{e=ge.normalize(e);try{r=Oe.lookupPath(e,{follow:!(131072&t)}).node}catch(e){}}var a=!1;if(64&t)if(r){if(128&t)throw new Oe.ErrnoError(20)}else r=Oe.mknod(e,n,0),a=!0;if(!r)throw new Oe.ErrnoError(44);if(Oe.isChrdev(r.mode)&&(t&=-513),65536&t&&!Oe.isDir(r.mode))throw new Oe.ErrnoError(54);if(!a){var i=Oe.mayOpen(r,t);if(i)throw new Oe.ErrnoError(i)}512&t&&!a&&Oe.truncate(r,0),t&=-131713;var s=Oe.createStream({node:r,path:Oe.getPath(r),flags:t,seekable:!0,position:0,stream_ops:r.stream_ops,ungotten:[],error:!1});return s.stream_ops.open&&s.stream_ops.open(s),!o.logReadFiles||1&t||e in Oe.readFiles||(Oe.readFiles[e]=1),s},close(e){if(Oe.isClosed(e))throw new Oe.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(e){throw e}finally{Oe.closeStream(e.fd)}e.fd=null},isClosed:e=>null===e.fd,llseek(e,t,n){if(Oe.isClosed(e))throw new Oe.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new Oe.ErrnoError(70);if(0!=n&&1!=n&&2!=n)throw new Oe.ErrnoError(28);return e.position=e.stream_ops.llseek(e,t,n),e.ungotten=[],e.position},read(e,t,n,r,o){if(C(n>=0),r<0||o<0)throw new Oe.ErrnoError(28);if(Oe.isClosed(e))throw new Oe.ErrnoError(8);if(1==(2097155&e.flags))throw new Oe.ErrnoError(8);if(Oe.isDir(e.node.mode))throw new Oe.ErrnoError(31);if(!e.stream_ops.read)throw new Oe.ErrnoError(28);var a=void 0!==o;if(a){if(!e.seekable)throw new Oe.ErrnoError(70)}else o=e.position;var i=e.stream_ops.read(e,t,n,r,o);return a||(e.position+=i),i},write(e,t,n,r,o,a){if(C(n>=0),r<0||o<0)throw new Oe.ErrnoError(28);if(Oe.isClosed(e))throw new Oe.ErrnoError(8);if(!(2097155&e.flags))throw new Oe.ErrnoError(8);if(Oe.isDir(e.node.mode))throw new Oe.ErrnoError(31);if(!e.stream_ops.write)throw new Oe.ErrnoError(28);e.seekable&&1024&e.flags&&Oe.llseek(e,0,2);var i=void 0!==o;if(i){if(!e.seekable)throw new Oe.ErrnoError(70)}else o=e.position;var s=e.stream_ops.write(e,t,n,r,o,a);return i||(e.position+=s),s},allocate(e,t,n){if(Oe.isClosed(e))throw new Oe.ErrnoError(8);if(t<0||n<=0)throw new Oe.ErrnoError(28);if(!(2097155&e.flags))throw new Oe.ErrnoError(8);if(!Oe.isFile(e.node.mode)&&!Oe.isDir(e.node.mode))throw new Oe.ErrnoError(43);if(!e.stream_ops.allocate)throw new Oe.ErrnoError(138);e.stream_ops.allocate(e,t,n)},mmap(e,t,n,r,o){if(2&r&&!(2&o)&&2!=(2097155&e.flags))throw new Oe.ErrnoError(2);if(1==(2097155&e.flags))throw new Oe.ErrnoError(2);if(!e.stream_ops.mmap)throw new Oe.ErrnoError(43);if(!t)throw new Oe.ErrnoError(28);return e.stream_ops.mmap(e,t,n,r,o)},msync:(e,t,n,r,o)=>(C(n>=0),e.stream_ops.msync?e.stream_ops.msync(e,t,n,r,o):0),ioctl(e,t,n){if(!e.stream_ops.ioctl)throw new Oe.ErrnoError(59);return e.stream_ops.ioctl(e,t,n)},readFile(e,t={}){if(t.flags=t.flags||0,t.encoding=t.encoding||"binary","utf8"!==t.encoding&&"binary"!==t.encoding)throw new Error(`Invalid encoding type "${t.encoding}"`);var n,r=Oe.open(e,t.flags),o=Oe.stat(e).size,a=new Uint8Array(o);return Oe.read(r,a,0,o,0),"utf8"===t.encoding?n=de(a):"binary"===t.encoding&&(n=a),Oe.close(r),n},writeFile(e,t,n={}){n.flags=n.flags||577;var r=Oe.open(e,n.flags,n.mode);if("string"==typeof t){var o=new Uint8Array(pe(t)+1),a=fe(t,o,0,o.length);Oe.write(r,o,0,a,void 0,n.canOwn)}else{if(!ArrayBuffer.isView(t))throw new Error("Unsupported data type");Oe.write(r,t,0,t.byteLength,void 0,n.canOwn)}Oe.close(r)},cwd:()=>Oe.currentPath,chdir(e){var t=Oe.lookupPath(e,{follow:!0});if(null===t.node)throw new Oe.ErrnoError(44);if(!Oe.isDir(t.node.mode))throw new Oe.ErrnoError(54);var n=Oe.nodePermissions(t.node,"x");if(n)throw new Oe.ErrnoError(n);Oe.currentPath=t.path},createDefaultDirectories(){Oe.mkdir("/tmp"),Oe.mkdir("/home"),Oe.mkdir("/home/web_user")},createDefaultDevices(){Oe.mkdir("/dev"),Oe.registerDevice(Oe.makedev(1,3),{read:()=>0,write:(e,t,n,r,o)=>r}),Oe.mkdev("/dev/null",Oe.makedev(1,3)),Me.register(Oe.makedev(5,0),Me.default_tty_ops),Me.register(Oe.makedev(6,0),Me.default_tty1_ops),Oe.mkdev("/dev/tty",Oe.makedev(5,0)),Oe.mkdev("/dev/tty1",Oe.makedev(6,0));var e=new Uint8Array(1024),t=0,n=()=>(0===t&&(t=he(e).byteLength),e[--t]);Oe.createDevice("/dev","random",n),Oe.createDevice("/dev","urandom",n),Oe.mkdir("/dev/shm"),Oe.mkdir("/dev/shm/tmp")},createSpecialDirectories(){Oe.mkdir("/proc");var e=Oe.mkdir("/proc/self");Oe.mkdir("/proc/self/fd"),Oe.mount({mount(){var t=Oe.createNode(e,"fd",16895,73);return t.node_ops={lookup(e,t){var n=+t,r=Oe.getStreamChecked(n),o={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>r.path}};return o.parent=o,o}},t}},{},"/proc/self/fd")},createStandardStreams(e,t,n){e?Oe.createDevice("/dev","stdin",e):Oe.symlink("/dev/tty","/dev/stdin"),t?Oe.createDevice("/dev","stdout",null,t):Oe.symlink("/dev/tty","/dev/stdout"),n?Oe.createDevice("/dev","stderr",null,n):Oe.symlink("/dev/tty1","/dev/stderr");var r=Oe.open("/dev/stdin",0),o=Oe.open("/dev/stdout",1),a=Oe.open("/dev/stderr",1);C(0===r.fd,`invalid handle for stdin (${r.fd})`),C(1===o.fd,`invalid handle for stdout (${o.fd})`),C(2===a.fd,`invalid handle for stderr (${a.fd})`)},staticInit(){[44].forEach(e=>{Oe.genericErrors[e]=new Oe.ErrnoError(e),Oe.genericErrors[e].stack=""}),Oe.nameTable=new Array(4096),Oe.mount(Ce,{},"/"),Oe.createDefaultDirectories(),Oe.createDefaultDevices(),Oe.createSpecialDirectories(),Oe.filesystems={MEMFS:Ce}},init(e,t,n){C(!Oe.initialized,"FS.init was previously called. If you want to initialize later with custom parameters, remove any earlier calls (note that one is automatically added to the generated code)"),Oe.initialized=!0,e??=o.stdin,t??=o.stdout,n??=o.stderr,Oe.createStandardStreams(e,t,n)},quit(){Oe.initialized=!1,tt(0);for(var e=0;ethis.length-1||e<0)){var t=e%this.chunkSize,n=e/this.chunkSize|0;return this.getter(n)[t]}}setDataGetter(e){this.getter=e}cacheLength(){var e=new XMLHttpRequest;if(e.open("HEAD",n,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+n+". Status: "+e.status);var t,r=Number(e.getResponseHeader("Content-length")),o=(t=e.getResponseHeader("Accept-Ranges"))&&"bytes"===t,a=(t=e.getResponseHeader("Content-Encoding"))&&"gzip"===t,i=1048576;o||(i=r);var s=this;s.setDataGetter(e=>{var t=e*i,o=(e+1)*i-1;if(o=Math.min(o,r-1),void 0===s.chunks[e]&&(s.chunks[e]=((e,t)=>{if(e>t)throw new Error("invalid range ("+e+", "+t+") or no bytes requested!");if(t>r-1)throw new Error("only "+r+" bytes available! programmer error!");var o=new XMLHttpRequest;if(o.open("GET",n,!1),r!==i&&o.setRequestHeader("Range","bytes="+e+"-"+t),o.responseType="arraybuffer",o.overrideMimeType&&o.overrideMimeType("text/plain; charset=x-user-defined"),o.send(null),!(o.status>=200&&o.status<300||304===o.status))throw new Error("Couldn't load "+n+". Status: "+o.status);return void 0!==o.response?new Uint8Array(o.response||[]):Ae(o.responseText||"")})(t,o)),void 0===s.chunks[e])throw new Error("doXHR failed!");return s.chunks[e]}),!a&&r||(i=r=1,r=this.getter(0).length,i=r,_("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=r,this._chunkSize=i,this.lengthKnown=!0}get length(){return this.lengthKnown||this.cacheLength(),this._length}get chunkSize(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}if("undefined"!=typeof XMLHttpRequest){if(!s)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var i={isDevice:!1,contents:new a}}else i={isDevice:!1,url:n};var u=Oe.createFile(e,t,i,r,o);i.contents?u.contents=i.contents:i.url&&(u.contents=null,u.url=i.url),Object.defineProperties(u,{usedBytes:{get:function(){return this.contents.length}}});var m={};function F(e,t,n,r,o){var a=e.node.contents;if(o>=a.length)return 0;var i=Math.min(a.length-o,r);if(C(i>=0),a.slice)for(var s=0;s{var t=u.stream_ops[e];m[e]=(...e)=>(Oe.forceLoadFile(u),t(...e))}),m.read=(e,t,n,r,o)=>(Oe.forceLoadFile(u),F(e,t,n,r,o)),m.mmap=(e,t,n,r,o)=>{Oe.forceLoadFile(u);var a=Se(t);if(!a)throw new Oe.ErrnoError(48);return F(e,b,a,t,n),{ptr:a,allocated:!0}},u.stream_ops=m,u},absolutePath(){W("FS.absolutePath has been removed; use PATH_FS.resolve instead")},createFolder(){W("FS.createFolder has been removed; use FS.mkdir instead")},createLink(){W("FS.createLink has been removed; use FS.symlink instead")},joinPath(){W("FS.joinPath has been removed; use PATH.join instead")},mmapAlloc(){W("FS.mmapAlloc has been replaced by the top level function mmapAlloc")},standardizePath(){W("FS.standardizePath has been removed; use PATH.normalize instead")}},Re={DEFAULT_POLLMASK:5,calculateAt(e,t,n){if(ge.isAbs(t))return t;var r;if(r=-100===e?Oe.cwd():Re.getStreamFromFD(e).path,0==t.length){if(!n)throw new Oe.ErrnoError(44);return r}return ge.join2(r,t)},doStat(e,t,n){var r=e(t);E[n>>2]=r.dev,E[n+4>>2]=r.mode,y[n+8>>2]=r.nlink,E[n+12>>2]=r.uid,E[n+16>>2]=r.gid,E[n+20>>2]=r.rdev,X=[r.size>>>0,(Y=r.size,+Math.abs(Y)>=1?Y>0?+Math.floor(Y/4294967296)>>>0:~~+Math.ceil((Y-+(~~Y>>>0))/4294967296)>>>0:0)],E[n+24>>2]=X[0],E[n+28>>2]=X[1],E[n+32>>2]=4096,E[n+36>>2]=r.blocks;var o=r.atime.getTime(),a=r.mtime.getTime(),i=r.ctime.getTime();return X=[Math.floor(o/1e3)>>>0,(Y=Math.floor(o/1e3),+Math.abs(Y)>=1?Y>0?+Math.floor(Y/4294967296)>>>0:~~+Math.ceil((Y-+(~~Y>>>0))/4294967296)>>>0:0)],E[n+40>>2]=X[0],E[n+44>>2]=X[1],y[n+48>>2]=o%1e3*1e3*1e3,X=[Math.floor(a/1e3)>>>0,(Y=Math.floor(a/1e3),+Math.abs(Y)>=1?Y>0?+Math.floor(Y/4294967296)>>>0:~~+Math.ceil((Y-+(~~Y>>>0))/4294967296)>>>0:0)],E[n+56>>2]=X[0],E[n+60>>2]=X[1],y[n+64>>2]=a%1e3*1e3*1e3,X=[Math.floor(i/1e3)>>>0,(Y=Math.floor(i/1e3),+Math.abs(Y)>=1?Y>0?+Math.floor(Y/4294967296)>>>0:~~+Math.ceil((Y-+(~~Y>>>0))/4294967296)>>>0:0)],E[n+72>>2]=X[0],E[n+76>>2]=X[1],y[n+80>>2]=i%1e3*1e3*1e3,X=[r.ino>>>0,(Y=r.ino,+Math.abs(Y)>=1?Y>0?+Math.floor(Y/4294967296)>>>0:~~+Math.ceil((Y-+(~~Y>>>0))/4294967296)>>>0:0)],E[n+88>>2]=X[0],E[n+92>>2]=X[1],0},doMsync(e,t,n,r,o){if(!Oe.isFile(t.node.mode))throw new Oe.ErrnoError(43);if(2&r)return 0;var a=p.slice(e,e+n);Oe.msync(t,a,o,n,r)},getStreamFromFD:e=>Oe.getStreamChecked(e),varargs:void 0,getStr:e=>ce(e)},ke=(e,t)=>(C(e==e>>>0||e==(0|e)),C(t===(0|t)),t+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*t:NaN),we=(e,t,n)=>(C("number"==typeof n,"stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!"),fe(e,p,t,n)),Ie=[0,31,60,91,121,152,182,213,244,274,305,335],Be=[0,31,59,90,120,151,181,212,243,273,304,334],je=e=>{var t=h.buffer,n=(e-t.byteLength+65535)/65536|0;try{return h.grow(n),x(),1}catch(n){g(`growMemory: Attempted to grow heap from ${t.byteLength} bytes to ${e} bytes, but got error: ${n}`)}},Le={},Ne=()=>{if(!Ne.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:d||"./this.program"};for(var t in Le)void 0===Le[t]?delete e[t]:e[t]=Le[t];var n=[];for(var t in e)n.push(`${t}=${e[t]}`);Ne.strings=n}return Ne.strings},Ve=[],Ue=e=>{var t=Ve[e];return t||(e>=Ve.length&&(Ve.length=e+1),Ve[e]=t=Ee.get(e)),C(Ee.get(e)==t,"JavaScript-side Wasm function table mirror is out of date!"),t},ze="undefined"!=typeof TextDecoder?new TextDecoder("utf-16le"):void 0,$e=(e,t)=>{C(e<16384),e<128?t.push(e):t.push(e%128|128,e>>7)},We=(e,t)=>{if(C(!t.includes("j"),"i64 not permitted in function signatures when WASM_BIGINT is disabled"),"function"==typeof WebAssembly.Function)return new WebAssembly.Function((e=>{C(!e.includes("j"),"i64 not permitted in function signatures when WASM_BIGINT is disabled");for(var t={i:"i32",j:"i64",f:"f32",d:"f64",e:"externref",p:"i32"},n={parameters:[],results:"v"==e[0]?[]:[t[e[0]]]},r=1;r{var n=e.slice(0,1),r=e.slice(1),o={i:127,p:127,j:126,f:125,d:124,e:111};t.push(96),$e(r.length,t);for(var a=0;a(ye||(ye=new WeakMap,((e,t)=>{if(ye)for(var n=e;n{Ee.set(e,t),Ve[e]=Ee.get(e)},Ke=e=>ut(e),Je=(e,t,n,r,a)=>{var i={string:e=>{var t=0;return null!=e&&0!==e&&(t=(e=>{var t=pe(e)+1,n=Ke(t);return we(e,n,t),n})(e)),t},array:e=>{var t,n,r=Ke(e.length);return n=r,C((t=e).length>=0,"writeArrayToMemory array must have a length (should be an array or typed array)"),b.set(t,n),r}},s=(e=>{var t=o["_"+e];return C(t,"Cannot call unknown function "+e+", make sure it is exported"),t})(e),u=[],m=0;if(C("array"!==t,'Return type should not be "array".'),r)for(var F=0;F{var l=t?De.resolve(ge.join2(e,t)):e,d=U(`cp ${l}`);function c(n){function u(n){F?.(),s||((e,t,n,r,o,a)=>{Oe.createDataFile(e,t,n,r,o,a)})(e,t,n,r,o,m),a?.(),$(d)}((e,t,n,r)=>{"undefined"!=typeof Browser&&Browser.init();var o=!1;return xe.forEach(a=>{o||a.canHandle(t)&&(a.handle(e,t,n,r),o=!0)}),o})(n,l,u,()=>{i?.(),$(d)})||u(n)}z(d),"string"==typeof n?((e,t,n)=>{var r=U(`al ${e}`);u(e).then(n=>{C(n,`Loading data file "${e}" failed (no arrayBuffer).`),t(new Uint8Array(n)),r&&$(r)},t=>{if(!n)throw`Loading data file "${e}" failed.`;n()}),r&&z(r)})(n,c,i):c(n)},Oe.staticInit();var qe={__assert_fail:(e,t,n,r)=>{W(`Assertion failed: ${ce(e)}, at: `+[t?ce(t):"unknown filename",n,r?ce(r):"unknown function"])},__syscall_fcntl64:function(e,t,n){Re.varargs=n;try{var r=Re.getStreamFromFD(e);switch(t){case 0:if((o=Pe())<0)return-28;for(;Oe.streams[o];)o++;return Oe.dupStream(r,o).fd;case 1:case 2:case 13:case 14:return 0;case 3:return r.flags;case 4:var o=Pe();return r.flags|=o,0;case 12:return o=_e(),f[o+0>>1]=2,0}return-28}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_fstat64:function(e,t){try{var n=Re.getStreamFromFD(e);return Re.doStat(Oe.stat,n.path,t)}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_ftruncate64:function(e,t,n){var r=ke(t,n);try{return isNaN(r)?61:(Oe.ftruncate(e,r),0)}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_getdents64:function(e,t,n){try{var r=Re.getStreamFromFD(e);r.getdents||=Oe.readdir(r.path);for(var o=280,a=0,i=Oe.llseek(r,0,1),s=Math.floor(i/o);s>>0,(Y=u,+Math.abs(Y)>=1?Y>0?+Math.floor(Y/4294967296)>>>0:~~+Math.ceil((Y-+(~~Y>>>0))/4294967296)>>>0:0)],E[t+a>>2]=X[0],E[t+a+4>>2]=X[1],X=[(s+1)*o>>>0,(Y=(s+1)*o,+Math.abs(Y)>=1?Y>0?+Math.floor(Y/4294967296)>>>0:~~+Math.ceil((Y-+(~~Y>>>0))/4294967296)>>>0:0)],E[t+a+8>>2]=X[0],E[t+a+12>>2]=X[1],f[t+a+16>>1]=280,b[t+a+18]=m,we(F,t+a+19,256),a+=o,s+=1}return Oe.llseek(r,s*o,0),a}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_ioctl:function(e,t,n){Re.varargs=n;try{var r=Re.getStreamFromFD(e);switch(t){case 21509:case 21510:case 21511:case 21512:case 21524:case 21515:return r.tty?0:-59;case 21505:if(!r.tty)return-59;if(r.tty.ops.ioctl_tcgets){var o=r.tty.ops.ioctl_tcgets(r),a=_e();E[a>>2]=o.c_iflag||0,E[a+4>>2]=o.c_oflag||0,E[a+8>>2]=o.c_cflag||0,E[a+12>>2]=o.c_lflag||0;for(var i=0;i<32;i++)b[a+i+17]=o.c_cc[i]||0;return 0}return 0;case 21506:case 21507:case 21508:if(!r.tty)return-59;if(r.tty.ops.ioctl_tcsets){a=_e();var s=E[a>>2],u=E[a+4>>2],m=E[a+8>>2],F=E[a+12>>2],l=[];for(i=0;i<32;i++)l.push(b[a+i+17]);return r.tty.ops.ioctl_tcsets(r.tty,t,{c_iflag:s,c_oflag:u,c_cflag:m,c_lflag:F,c_cc:l})}return 0;case 21519:return r.tty?(a=_e(),E[a>>2]=0,0):-59;case 21520:return r.tty?-28:-59;case 21531:return a=_e(),Oe.ioctl(r,t,a);case 21523:if(!r.tty)return-59;if(r.tty.ops.ioctl_tiocgwinsz){var d=r.tty.ops.ioctl_tiocgwinsz(r.tty);a=_e(),f[a>>1]=d[0],f[a+2>>1]=d[1]}return 0;default:return-28}}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_lstat64:function(e,t){try{return e=Re.getStr(e),Re.doStat(Oe.lstat,e,t)}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_newfstatat:function(e,t,n,r){try{t=Re.getStr(t);var o=256&r,a=4096&r;return C(!(r&=-6401),`unknown flags in __syscall_newfstatat: ${r}`),t=Re.calculateAt(e,t,a),Re.doStat(o?Oe.lstat:Oe.stat,t,n)}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_openat:function(e,t,n,r){Re.varargs=r;try{t=Re.getStr(t),t=Re.calculateAt(e,t);var o=r?Pe():0;return Oe.open(t,n,o).fd}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_rmdir:function(e){try{return e=Re.getStr(e),Oe.rmdir(e),0}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_stat64:function(e,t){try{return e=Re.getStr(e),Re.doStat(Oe.stat,e,t)}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_unlinkat:function(e,t,n){try{return t=Re.getStr(t),t=Re.calculateAt(e,t),0===n?Oe.unlink(t):512===n?Oe.rmdir(t):W("Invalid flags passed to unlinkat"),0}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return-e.errno}},_abort_js:()=>{W("native code called abort()")},_emscripten_memcpy_js:(e,t,n)=>p.copyWithin(e,t,t+n),_emscripten_throw_longjmp:()=>{throw 1/0},_gmtime_js:function(e,t,n){var r=ke(e,t),o=new Date(1e3*r);E[n>>2]=o.getUTCSeconds(),E[n+4>>2]=o.getUTCMinutes(),E[n+8>>2]=o.getUTCHours(),E[n+12>>2]=o.getUTCDate(),E[n+16>>2]=o.getUTCMonth(),E[n+20>>2]=o.getUTCFullYear()-1900,E[n+24>>2]=o.getUTCDay();var a=Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0),i=(o.getTime()-a)/864e5|0;E[n+28>>2]=i},_localtime_js:function(e,t,n){var r=ke(e,t),o=new Date(1e3*r);E[n>>2]=o.getSeconds(),E[n+4>>2]=o.getMinutes(),E[n+8>>2]=o.getHours(),E[n+12>>2]=o.getDate(),E[n+16>>2]=o.getMonth(),E[n+20>>2]=o.getFullYear()-1900,E[n+24>>2]=o.getDay();var a=0|(e=>{var t;return((t=e.getFullYear())%4!=0||t%100==0&&t%400!=0?Be:Ie)[e.getMonth()]+e.getDate()-1})(o);E[n+28>>2]=a,E[n+36>>2]=-60*o.getTimezoneOffset();var i=new Date(o.getFullYear(),0,1),s=new Date(o.getFullYear(),6,1).getTimezoneOffset(),u=i.getTimezoneOffset(),m=0|(s!=u&&o.getTimezoneOffset()==Math.min(u,s));E[n+32>>2]=m},_tzset_js:(e,t,n,r)=>{var o=(new Date).getFullYear(),a=new Date(o,0,1),i=new Date(o,6,1),s=a.getTimezoneOffset(),u=i.getTimezoneOffset(),m=Math.max(s,u);y[e>>2]=60*m,E[t>>2]=Number(s!=u);var F=e=>{var t=e>=0?"-":"+",n=Math.abs(e);return`UTC${t}${String(Math.floor(n/60)).padStart(2,"0")}${String(n%60).padStart(2,"0")}`},l=F(s),d=F(u);C(l),C(d),C(pe(l)<=16,`timezone name truncated to fit in TZNAME_MAX (${l})`),C(pe(d)<=16,`timezone name truncated to fit in TZNAME_MAX (${d})`),uDate.now(),emscripten_resize_heap:e=>{var t=p.length;C((e>>>=0)>t);var n=2147483648;if(e>n)return g(`Cannot enlarge memory, requested ${e} bytes, but the limit is 2147483648 bytes!`),!1;for(var r=1;r<=4;r*=2){var o=t*(1+.2/r);o=Math.min(o,e+100663296);var a=Math.min(n,Ge(Math.max(e,o),65536));if(je(a))return!0}return g(`Failed to grow the heap from ${t} bytes to ${a} bytes, not enough memory!`),!1},environ_get:(e,t)=>{var n=0;return Ne().forEach((r,o)=>{var a=t+n;y[e+4*o>>2]=a,((e,t)=>{for(var n=0;n{var n=Ne();y[e>>2]=n.length;var r=0;return n.forEach(e=>r+=e.length+1),y[t>>2]=r,0},fd_close:function(e){try{var t=Re.getStreamFromFD(e);return Oe.close(t),0}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return e.errno}},fd_read:function(e,t,n,r){try{var o=((e,t,n,r)=>{for(var o=0,a=0;a>2],s=y[t+4>>2];t+=8;var u=Oe.read(e,b,i,s,r);if(u<0)return-1;if(o+=u,u>2]=o,0}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return e.errno}},fd_seek:function(e,t,n,r,o){var a=ke(t,n);try{if(isNaN(a))return 61;var i=Re.getStreamFromFD(e);return Oe.llseek(i,a,r),X=[i.position>>>0,(Y=i.position,+Math.abs(Y)>=1?Y>0?+Math.floor(Y/4294967296)>>>0:~~+Math.ceil((Y-+(~~Y>>>0))/4294967296)>>>0:0)],E[o>>2]=X[0],E[o+4>>2]=X[1],i.getdents&&0===a&&0===r&&(i.getdents=null),0}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return e.errno}},fd_sync:function(e){try{var t=Re.getStreamFromFD(e);return t.stream_ops?.fsync?t.stream_ops.fsync(t):0}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return e.errno}},fd_write:function(e,t,n,r){try{var o=((e,t,n,r)=>{for(var o=0,a=0;a>2],s=y[t+4>>2];t+=8;var u=Oe.write(e,b,i,s,r);if(u<0)return-1;if(o+=u,u>2]=o,0}catch(e){if(void 0===Oe||"ErrnoError"!==e.name)throw e;return e.errno}},invoke_ii:function(e,t){var n=me();try{return Ue(e)(t)}catch(e){if(ue(n),e!==e+0)throw e;ot(1,0)}},invoke_iii:function(e,t,n){var r=me();try{return Ue(e)(t,n)}catch(e){if(ue(r),e!==e+0)throw e;ot(1,0)}},invoke_iiii:function(e,t,n,r){var o=me();try{return Ue(e)(t,n,r)}catch(e){if(ue(o),e!==e+0)throw e;ot(1,0)}},invoke_iiiii:function(e,t,n,r,o){var a=me();try{return Ue(e)(t,n,r,o)}catch(e){if(ue(a),e!==e+0)throw e;ot(1,0)}},invoke_v:function(e){var t=me();try{Ue(e)()}catch(e){if(ue(t),e!==e+0)throw e;ot(1,0)}},invoke_vii:function(e,t,n){var r=me();try{Ue(e)(t,n)}catch(e){if(ue(r),e!==e+0)throw e;ot(1,0)}},invoke_viii:function(e,t,n,r){var o=me();try{Ue(e)(t,n,r)}catch(e){if(ue(o),e!==e+0)throw e;ot(1,0)}},invoke_viiii:function(e,t,n,r,o){var a=me();try{Ue(e)(t,n,r,o)}catch(e){if(ue(a),e!==e+0)throw e;ot(1,0)}},invoke_viiiiiiiii:function(e,t,n,r,o,a,i,s,u,m){var F=me();try{Ue(e)(t,n,r,o,a,i,s,u,m)}catch(e){if(ue(F),e!==e+0)throw e;ot(1,0)}}},Qe=function(){var e={env:qe,wasi_snapshot_preview1:qe};function t(e,t){var n;return Qe=e.exports,o.wasmExports=Qe,C(h=Qe.memory,"memory not found in wasm exports"),x(),C(Ee=Qe.__indirect_function_table,"table not found in wasm exports"),n=Qe.__wasm_call_ctors,O.unshift(n),$("wasm-instantiate"),Qe}z("wasm-instantiate");var n,a,i,s,u=o;if(o.instantiateWasm)try{return o.instantiateWasm(e,t)}catch(e){g(`Module.instantiateWasm callback failed with error: ${e}`),r(e)}return H??=Q(),(n=D,a=H,i=e,s=function(e){C(o===u,"the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?"),u=null,t(e.instance)},n||"function"!=typeof WebAssembly.instantiateStreaming||K(a)||"function"!=typeof fetch?ee(a,i,s):fetch(a,{credentials:"same-origin"}).then(e=>WebAssembly.instantiateStreaming(e,i).then(s,function(e){return g(`wasm streaming compile failed: ${e}`),g("falling back to ArrayBuffer instantiation"),ee(a,i,s)}))).catch(r),{}}();o._PDFiumExt_Init=q("PDFiumExt_Init",0),o._FPDF_InitLibraryWithConfig=q("FPDF_InitLibraryWithConfig",1),o._PDFiumExt_OpenFileWriter=q("PDFiumExt_OpenFileWriter",0),o._PDFiumExt_GetFileWriterSize=q("PDFiumExt_GetFileWriterSize",1),o._PDFiumExt_GetFileWriterData=q("PDFiumExt_GetFileWriterData",3),o._PDFiumExt_CloseFileWriter=q("PDFiumExt_CloseFileWriter",1),o._PDFiumExt_SaveAsCopy=q("PDFiumExt_SaveAsCopy",2),o._FPDF_SaveAsCopy=q("FPDF_SaveAsCopy",3),o._PDFiumExt_OpenFormFillInfo=q("PDFiumExt_OpenFormFillInfo",0),o._PDFiumExt_CloseFormFillInfo=q("PDFiumExt_CloseFormFillInfo",1),o._PDFiumExt_InitFormFillEnvironment=q("PDFiumExt_InitFormFillEnvironment",2),o._FPDFDOC_InitFormFillEnvironment=q("FPDFDOC_InitFormFillEnvironment",2),o._PDFiumExt_ExitFormFillEnvironment=q("PDFiumExt_ExitFormFillEnvironment",1),o._FPDFDOC_ExitFormFillEnvironment=q("FPDFDOC_ExitFormFillEnvironment",1),o._EPDFNamedDest_SetDest=q("EPDFNamedDest_SetDest",3),o._EPDFNamedDest_Remove=q("EPDFNamedDest_Remove",2),o._EPDFDest_CreateView=q("EPDFDest_CreateView",4),o._EPDFDest_CreateXYZ=q("EPDFDest_CreateXYZ",7),o._EPDFDest_CreateRemoteView=q("EPDFDest_CreateRemoteView",5),o._EPDFDest_CreateRemoteXYZ=q("EPDFDest_CreateRemoteXYZ",8),o._EPDFAction_CreateGoTo=q("EPDFAction_CreateGoTo",2),o._EPDFAction_CreateGoToNamed=q("EPDFAction_CreateGoToNamed",2),o._EPDFAction_CreateLaunch=q("EPDFAction_CreateLaunch",2),o._EPDFAction_CreateRemoteGoToByName=q("EPDFAction_CreateRemoteGoToByName",3),o._EPDFAction_CreateRemoteGoToDest=q("EPDFAction_CreateRemoteGoToDest",3),o._EPDFAction_CreateURI=q("EPDFAction_CreateURI",2),o._EPDFBookmark_Create=q("EPDFBookmark_Create",2),o._EPDFBookmark_Delete=q("EPDFBookmark_Delete",2),o._EPDFBookmark_AppendChild=q("EPDFBookmark_AppendChild",3),o._EPDFBookmark_InsertAfter=q("EPDFBookmark_InsertAfter",4),o._EPDFBookmark_Clear=q("EPDFBookmark_Clear",1),o._EPDFBookmark_SetTitle=q("EPDFBookmark_SetTitle",2),o._EPDFBookmark_SetDest=q("EPDFBookmark_SetDest",3),o._EPDFBookmark_SetAction=q("EPDFBookmark_SetAction",3),o._EPDFBookmark_ClearTarget=q("EPDFBookmark_ClearTarget",1),o._EPDF_PNG_EncodeRGBA=q("EPDF_PNG_EncodeRGBA",6),o._FPDFAnnot_IsSupportedSubtype=q("FPDFAnnot_IsSupportedSubtype",1),o._FPDFPage_CreateAnnot=q("FPDFPage_CreateAnnot",2),o._FPDFPage_GetAnnotCount=q("FPDFPage_GetAnnotCount",1),o._FPDFPage_GetAnnot=q("FPDFPage_GetAnnot",2),o._FPDFPage_GetAnnotIndex=q("FPDFPage_GetAnnotIndex",2),o._FPDFPage_CloseAnnot=q("FPDFPage_CloseAnnot",1),o._FPDFPage_RemoveAnnot=q("FPDFPage_RemoveAnnot",2),o._FPDFAnnot_GetSubtype=q("FPDFAnnot_GetSubtype",1),o._FPDFAnnot_IsObjectSupportedSubtype=q("FPDFAnnot_IsObjectSupportedSubtype",1),o._FPDFAnnot_UpdateObject=q("FPDFAnnot_UpdateObject",2),o._FPDFAnnot_AddInkStroke=q("FPDFAnnot_AddInkStroke",3),o._FPDFAnnot_RemoveInkList=q("FPDFAnnot_RemoveInkList",1),o._FPDFAnnot_AppendObject=q("FPDFAnnot_AppendObject",2),o._FPDFAnnot_GetObjectCount=q("FPDFAnnot_GetObjectCount",1),o._FPDFAnnot_GetObject=q("FPDFAnnot_GetObject",2),o._FPDFAnnot_RemoveObject=q("FPDFAnnot_RemoveObject",2),o._FPDFAnnot_SetColor=q("FPDFAnnot_SetColor",6),o._FPDFAnnot_GetColor=q("FPDFAnnot_GetColor",6),o._FPDFAnnot_HasAttachmentPoints=q("FPDFAnnot_HasAttachmentPoints",1),o._FPDFAnnot_SetAttachmentPoints=q("FPDFAnnot_SetAttachmentPoints",3),o._FPDFAnnot_AppendAttachmentPoints=q("FPDFAnnot_AppendAttachmentPoints",2),o._FPDFAnnot_CountAttachmentPoints=q("FPDFAnnot_CountAttachmentPoints",1),o._FPDFAnnot_GetAttachmentPoints=q("FPDFAnnot_GetAttachmentPoints",3),o._FPDFAnnot_SetRect=q("FPDFAnnot_SetRect",2),o._FPDFAnnot_GetRect=q("FPDFAnnot_GetRect",2),o._FPDFAnnot_GetVertices=q("FPDFAnnot_GetVertices",3),o._FPDFAnnot_GetInkListCount=q("FPDFAnnot_GetInkListCount",1),o._FPDFAnnot_GetInkListPath=q("FPDFAnnot_GetInkListPath",4),o._FPDFAnnot_GetLine=q("FPDFAnnot_GetLine",3),o._FPDFAnnot_SetBorder=q("FPDFAnnot_SetBorder",4),o._FPDFAnnot_GetBorder=q("FPDFAnnot_GetBorder",4),o._FPDFAnnot_HasKey=q("FPDFAnnot_HasKey",2),o._FPDFAnnot_GetValueType=q("FPDFAnnot_GetValueType",2),o._FPDFAnnot_SetStringValue=q("FPDFAnnot_SetStringValue",3),o._FPDFAnnot_GetStringValue=q("FPDFAnnot_GetStringValue",4),o._FPDFAnnot_GetNumberValue=q("FPDFAnnot_GetNumberValue",3),o._FPDFAnnot_SetAP=q("FPDFAnnot_SetAP",3),o._FPDFAnnot_GetAP=q("FPDFAnnot_GetAP",4),o._FPDFAnnot_GetLinkedAnnot=q("FPDFAnnot_GetLinkedAnnot",2),o._FPDFAnnot_GetFlags=q("FPDFAnnot_GetFlags",1),o._FPDFAnnot_SetFlags=q("FPDFAnnot_SetFlags",2),o._FPDFAnnot_GetFormFieldFlags=q("FPDFAnnot_GetFormFieldFlags",2),o._FPDFAnnot_SetFormFieldFlags=q("FPDFAnnot_SetFormFieldFlags",3),o._FPDFAnnot_GetFormFieldAtPoint=q("FPDFAnnot_GetFormFieldAtPoint",3),o._FPDFAnnot_GetFormFieldName=q("FPDFAnnot_GetFormFieldName",4),o._FPDFAnnot_GetFormFieldType=q("FPDFAnnot_GetFormFieldType",2),o._FPDFAnnot_GetFormAdditionalActionJavaScript=q("FPDFAnnot_GetFormAdditionalActionJavaScript",5),o._FPDFAnnot_GetFormFieldAlternateName=q("FPDFAnnot_GetFormFieldAlternateName",4),o._FPDFAnnot_GetFormFieldValue=q("FPDFAnnot_GetFormFieldValue",4),o._FPDFAnnot_GetOptionCount=q("FPDFAnnot_GetOptionCount",2),o._FPDFAnnot_GetOptionLabel=q("FPDFAnnot_GetOptionLabel",5),o._FPDFAnnot_IsOptionSelected=q("FPDFAnnot_IsOptionSelected",3),o._FPDFAnnot_GetFontSize=q("FPDFAnnot_GetFontSize",3),o._FPDFAnnot_SetFontColor=q("FPDFAnnot_SetFontColor",5),o._FPDFAnnot_GetFontColor=q("FPDFAnnot_GetFontColor",5),o._FPDFAnnot_IsChecked=q("FPDFAnnot_IsChecked",2),o._FPDFAnnot_SetFocusableSubtypes=q("FPDFAnnot_SetFocusableSubtypes",3),o._FPDFAnnot_GetFocusableSubtypesCount=q("FPDFAnnot_GetFocusableSubtypesCount",1),o._FPDFAnnot_GetFocusableSubtypes=q("FPDFAnnot_GetFocusableSubtypes",3),o._FPDFAnnot_GetLink=q("FPDFAnnot_GetLink",1),o._FPDFAnnot_GetFormControlCount=q("FPDFAnnot_GetFormControlCount",2),o._FPDFAnnot_GetFormControlIndex=q("FPDFAnnot_GetFormControlIndex",2),o._FPDFAnnot_GetFormFieldExportValue=q("FPDFAnnot_GetFormFieldExportValue",4),o._FPDFAnnot_SetURI=q("FPDFAnnot_SetURI",2),o._EPDFAnnot_SetAction=q("EPDFAnnot_SetAction",2),o._FPDFAnnot_GetFileAttachment=q("FPDFAnnot_GetFileAttachment",1),o._FPDFAnnot_AddFileAttachment=q("FPDFAnnot_AddFileAttachment",2),o._EPDFAnnot_SetColor=q("EPDFAnnot_SetColor",5),o._EPDFAnnot_GetColor=q("EPDFAnnot_GetColor",5),o._EPDFAnnot_ClearColor=q("EPDFAnnot_ClearColor",2),o._EPDFAnnot_SetOpacity=q("EPDFAnnot_SetOpacity",2),o._EPDFAnnot_GetOpacity=q("EPDFAnnot_GetOpacity",2),o._EPDFAnnot_GetBorderEffect=q("EPDFAnnot_GetBorderEffect",2),o._EPDFAnnot_GetRectangleDifferences=q("EPDFAnnot_GetRectangleDifferences",5),o._EPDFAnnot_SetRectangleDifferences=q("EPDFAnnot_SetRectangleDifferences",5),o._EPDFAnnot_ClearRectangleDifferences=q("EPDFAnnot_ClearRectangleDifferences",1),o._EPDFAnnot_GetBorderDashPatternCount=q("EPDFAnnot_GetBorderDashPatternCount",1),o._EPDFAnnot_GetBorderDashPattern=q("EPDFAnnot_GetBorderDashPattern",3),o._EPDFAnnot_SetBorderDashPattern=q("EPDFAnnot_SetBorderDashPattern",3),o._EPDFAnnot_GetBorderStyle=q("EPDFAnnot_GetBorderStyle",2),o._EPDFAnnot_SetBorderStyle=q("EPDFAnnot_SetBorderStyle",3),o._EPDFAnnot_GenerateAppearance=q("EPDFAnnot_GenerateAppearance",1),o._EPDFAnnot_GenerateAppearanceWithBlend=q("EPDFAnnot_GenerateAppearanceWithBlend",2),o._EPDFAnnot_GetBlendMode=q("EPDFAnnot_GetBlendMode",1),o._EPDFAnnot_SetIntent=q("EPDFAnnot_SetIntent",2),o._EPDFAnnot_GetIntent=q("EPDFAnnot_GetIntent",3),o._EPDFAnnot_GetRichContent=q("EPDFAnnot_GetRichContent",3),o._EPDFAnnot_SetLineEndings=q("EPDFAnnot_SetLineEndings",3),o._EPDFAnnot_GetLineEndings=q("EPDFAnnot_GetLineEndings",3),o._EPDFAnnot_SetVertices=q("EPDFAnnot_SetVertices",3),o._EPDFAnnot_SetLine=q("EPDFAnnot_SetLine",3),o._EPDFAnnot_SetDefaultAppearance=q("EPDFAnnot_SetDefaultAppearance",6),o._EPDFAnnot_GetDefaultAppearance=q("EPDFAnnot_GetDefaultAppearance",6),o._EPDFAnnot_SetTextAlignment=q("EPDFAnnot_SetTextAlignment",2),o._EPDFAnnot_GetTextAlignment=q("EPDFAnnot_GetTextAlignment",1),o._EPDFAnnot_SetVerticalAlignment=q("EPDFAnnot_SetVerticalAlignment",2),o._EPDFAnnot_GetVerticalAlignment=q("EPDFAnnot_GetVerticalAlignment",1),o._EPDFPage_GetAnnotByName=q("EPDFPage_GetAnnotByName",2),o._EPDFPage_RemoveAnnotByName=q("EPDFPage_RemoveAnnotByName",2),o._EPDFAnnot_SetLinkedAnnot=q("EPDFAnnot_SetLinkedAnnot",3),o._EPDFPage_GetAnnotCountRaw=q("EPDFPage_GetAnnotCountRaw",2),o._EPDFPage_GetAnnotRaw=q("EPDFPage_GetAnnotRaw",3),o._EPDFPage_RemoveAnnotRaw=q("EPDFPage_RemoveAnnotRaw",3),o._EPDFAnnot_SetIcon=q("EPDFAnnot_SetIcon",2),o._EPDFAnnot_GetIcon=q("EPDFAnnot_GetIcon",1),o._EPDFAnnot_UpdateAppearanceToRect=q("EPDFAnnot_UpdateAppearanceToRect",2),o._EPDFPage_CreateAnnot=q("EPDFPage_CreateAnnot",2),o._EPDFAnnot_SetRotate=q("EPDFAnnot_SetRotate",2),o._EPDFAnnot_GetRotate=q("EPDFAnnot_GetRotate",2),o._EPDFAnnot_GetReplyType=q("EPDFAnnot_GetReplyType",1),o._EPDFAnnot_SetReplyType=q("EPDFAnnot_SetReplyType",2),o._EPDFAnnot_SetOverlayText=q("EPDFAnnot_SetOverlayText",2),o._EPDFAnnot_GetOverlayText=q("EPDFAnnot_GetOverlayText",3),o._EPDFAnnot_SetOverlayTextRepeat=q("EPDFAnnot_SetOverlayTextRepeat",2),o._EPDFAnnot_GetOverlayTextRepeat=q("EPDFAnnot_GetOverlayTextRepeat",1),o._EPDFAnnot_ApplyRedaction=q("EPDFAnnot_ApplyRedaction",2),o._EPDFPage_ApplyRedactions=q("EPDFPage_ApplyRedactions",1),o._EPDFAnnot_Flatten=q("EPDFAnnot_Flatten",2),o._EPDFAnnot_SetExtendedRotation=q("EPDFAnnot_SetExtendedRotation",2),o._EPDFAnnot_GetExtendedRotation=q("EPDFAnnot_GetExtendedRotation",2),o._EPDFAnnot_SetUnrotatedRect=q("EPDFAnnot_SetUnrotatedRect",2),o._EPDFAnnot_GetUnrotatedRect=q("EPDFAnnot_GetUnrotatedRect",2),o._EPDFAnnot_GetRect=q("EPDFAnnot_GetRect",2),o._EPDFAnnot_SetAPMatrix=q("EPDFAnnot_SetAPMatrix",3),o._EPDFAnnot_GetAPMatrix=q("EPDFAnnot_GetAPMatrix",3),o._EPDFAnnot_GetAvailableAppearanceModes=q("EPDFAnnot_GetAvailableAppearanceModes",1),o._EPDFAnnot_HasAppearanceStream=q("EPDFAnnot_HasAppearanceStream",2),o._FPDFDoc_GetAttachmentCount=q("FPDFDoc_GetAttachmentCount",1),o._FPDFDoc_AddAttachment=q("FPDFDoc_AddAttachment",2),o._FPDFDoc_GetAttachment=q("FPDFDoc_GetAttachment",2),o._FPDFDoc_DeleteAttachment=q("FPDFDoc_DeleteAttachment",2),o._FPDFAttachment_GetName=q("FPDFAttachment_GetName",3),o._FPDFAttachment_HasKey=q("FPDFAttachment_HasKey",2),o._FPDFAttachment_GetValueType=q("FPDFAttachment_GetValueType",2),o._FPDFAttachment_SetStringValue=q("FPDFAttachment_SetStringValue",3),o._FPDFAttachment_GetStringValue=q("FPDFAttachment_GetStringValue",4),o._FPDFAttachment_SetFile=q("FPDFAttachment_SetFile",4),o._FPDFAttachment_GetFile=q("FPDFAttachment_GetFile",4),o._FPDFAttachment_GetSubtype=q("FPDFAttachment_GetSubtype",3),o._EPDFAttachment_SetSubtype=q("EPDFAttachment_SetSubtype",2),o._EPDFAttachment_SetDescription=q("EPDFAttachment_SetDescription",2),o._EPDFAttachment_GetDescription=q("EPDFAttachment_GetDescription",3),o._EPDFAttachment_GetIntegerValue=q("EPDFAttachment_GetIntegerValue",3),o._FPDFCatalog_IsTagged=q("FPDFCatalog_IsTagged",1),o._FPDFCatalog_GetLanguage=q("FPDFCatalog_GetLanguage",3),o._FPDFCatalog_SetLanguage=q("FPDFCatalog_SetLanguage",2),o._EPDFCatalog_GetLanguage=q("EPDFCatalog_GetLanguage",3),o._FPDFAvail_Create=q("FPDFAvail_Create",2),o._FPDFAvail_Destroy=q("FPDFAvail_Destroy",1),o._FPDFAvail_IsDocAvail=q("FPDFAvail_IsDocAvail",2),o._FPDFAvail_GetDocument=q("FPDFAvail_GetDocument",2),o._FPDFAvail_GetFirstPageNum=q("FPDFAvail_GetFirstPageNum",1),o._FPDFAvail_IsPageAvail=q("FPDFAvail_IsPageAvail",3),o._FPDFAvail_IsFormAvail=q("FPDFAvail_IsFormAvail",2),o._FPDFAvail_IsLinearized=q("FPDFAvail_IsLinearized",1),o._FPDFBookmark_GetFirstChild=q("FPDFBookmark_GetFirstChild",2),o._FPDFBookmark_GetNextSibling=q("FPDFBookmark_GetNextSibling",2),o._FPDFBookmark_GetTitle=q("FPDFBookmark_GetTitle",3),o._FPDFBookmark_GetCount=q("FPDFBookmark_GetCount",1),o._FPDFBookmark_Find=q("FPDFBookmark_Find",2),o._FPDFBookmark_GetDest=q("FPDFBookmark_GetDest",2),o._FPDFBookmark_GetAction=q("FPDFBookmark_GetAction",1),o._FPDFAction_GetType=q("FPDFAction_GetType",1),o._FPDFAction_GetDest=q("FPDFAction_GetDest",2),o._FPDFAction_GetFilePath=q("FPDFAction_GetFilePath",3),o._FPDFAction_GetURIPath=q("FPDFAction_GetURIPath",4),o._FPDFDest_GetDestPageIndex=q("FPDFDest_GetDestPageIndex",2),o._FPDFDest_GetView=q("FPDFDest_GetView",3),o._FPDFDest_GetLocationInPage=q("FPDFDest_GetLocationInPage",7),o._FPDFLink_GetLinkAtPoint=q("FPDFLink_GetLinkAtPoint",3),o._FPDFLink_GetLinkZOrderAtPoint=q("FPDFLink_GetLinkZOrderAtPoint",3),o._FPDFLink_GetDest=q("FPDFLink_GetDest",2),o._FPDFLink_GetAction=q("FPDFLink_GetAction",1),o._FPDFLink_Enumerate=q("FPDFLink_Enumerate",3),o._FPDFLink_GetAnnot=q("FPDFLink_GetAnnot",2),o._FPDFLink_GetAnnotRect=q("FPDFLink_GetAnnotRect",2),o._FPDFLink_CountQuadPoints=q("FPDFLink_CountQuadPoints",1),o._FPDFLink_GetQuadPoints=q("FPDFLink_GetQuadPoints",3),o._FPDF_GetPageAAction=q("FPDF_GetPageAAction",2),o._FPDF_GetFileIdentifier=q("FPDF_GetFileIdentifier",4),o._FPDF_GetMetaText=q("FPDF_GetMetaText",4),o._FPDF_GetPageLabel=q("FPDF_GetPageLabel",4),o._EPDF_SetMetaText=q("EPDF_SetMetaText",3),o._EPDF_HasMetaText=q("EPDF_HasMetaText",2),o._EPDF_GetMetaTrapped=q("EPDF_GetMetaTrapped",1),o._EPDF_SetMetaTrapped=q("EPDF_SetMetaTrapped",2),o._EPDF_GetMetaKeyCount=q("EPDF_GetMetaKeyCount",2),o._EPDF_GetMetaKeyName=q("EPDF_GetMetaKeyName",5),o._FPDFPageObj_NewImageObj=q("FPDFPageObj_NewImageObj",1),o._FPDFImageObj_LoadJpegFile=q("FPDFImageObj_LoadJpegFile",4),o._FPDFImageObj_LoadJpegFileInline=q("FPDFImageObj_LoadJpegFileInline",4),o._FPDFImageObj_SetMatrix=q("FPDFImageObj_SetMatrix",7),o._FPDFImageObj_SetBitmap=q("FPDFImageObj_SetBitmap",4),o._FPDFImageObj_GetBitmap=q("FPDFImageObj_GetBitmap",1),o._FPDFImageObj_GetRenderedBitmap=q("FPDFImageObj_GetRenderedBitmap",3),o._FPDFImageObj_GetImageDataDecoded=q("FPDFImageObj_GetImageDataDecoded",3),o._FPDFImageObj_GetImageDataRaw=q("FPDFImageObj_GetImageDataRaw",3),o._FPDFImageObj_GetImageFilterCount=q("FPDFImageObj_GetImageFilterCount",1),o._FPDFImageObj_GetImageFilter=q("FPDFImageObj_GetImageFilter",4),o._FPDFImageObj_GetImageMetadata=q("FPDFImageObj_GetImageMetadata",3),o._FPDFImageObj_GetImagePixelSize=q("FPDFImageObj_GetImagePixelSize",3),o._FPDFImageObj_GetIccProfileDataDecoded=q("FPDFImageObj_GetIccProfileDataDecoded",5),o._FPDF_CreateNewDocument=q("FPDF_CreateNewDocument",0),o._FPDFPage_Delete=q("FPDFPage_Delete",2),o._FPDF_MovePages=q("FPDF_MovePages",4),o._FPDFPage_New=q("FPDFPage_New",4),o._FPDFPage_GetRotation=q("FPDFPage_GetRotation",1),o._FPDFPage_InsertObject=q("FPDFPage_InsertObject",2),o._FPDFPage_InsertObjectAtIndex=q("FPDFPage_InsertObjectAtIndex",3),o._FPDFPage_RemoveObject=q("FPDFPage_RemoveObject",2),o._FPDFPage_CountObjects=q("FPDFPage_CountObjects",1),o._FPDFPage_GetObject=q("FPDFPage_GetObject",2),o._FPDFPage_HasTransparency=q("FPDFPage_HasTransparency",1),o._FPDFPageObj_Destroy=q("FPDFPageObj_Destroy",1),o._FPDFPageObj_GetMarkedContentID=q("FPDFPageObj_GetMarkedContentID",1),o._FPDFPageObj_CountMarks=q("FPDFPageObj_CountMarks",1),o._FPDFPageObj_GetMark=q("FPDFPageObj_GetMark",2),o._FPDFPageObj_AddMark=q("FPDFPageObj_AddMark",2),o._FPDFPageObj_RemoveMark=q("FPDFPageObj_RemoveMark",2),o._FPDFPageObjMark_GetName=q("FPDFPageObjMark_GetName",4),o._FPDFPageObjMark_CountParams=q("FPDFPageObjMark_CountParams",1),o._FPDFPageObjMark_GetParamKey=q("FPDFPageObjMark_GetParamKey",5),o._FPDFPageObjMark_GetParamValueType=q("FPDFPageObjMark_GetParamValueType",2),o._FPDFPageObjMark_GetParamIntValue=q("FPDFPageObjMark_GetParamIntValue",3),o._FPDFPageObjMark_GetParamFloatValue=q("FPDFPageObjMark_GetParamFloatValue",3),o._FPDFPageObjMark_GetParamStringValue=q("FPDFPageObjMark_GetParamStringValue",5),o._FPDFPageObjMark_GetParamBlobValue=q("FPDFPageObjMark_GetParamBlobValue",5),o._FPDFPageObj_HasTransparency=q("FPDFPageObj_HasTransparency",1),o._FPDFPageObjMark_SetIntParam=q("FPDFPageObjMark_SetIntParam",5),o._FPDFPageObjMark_SetFloatParam=q("FPDFPageObjMark_SetFloatParam",5),o._FPDFPageObjMark_SetStringParam=q("FPDFPageObjMark_SetStringParam",5),o._FPDFPageObjMark_SetBlobParam=q("FPDFPageObjMark_SetBlobParam",6),o._FPDFPageObjMark_RemoveParam=q("FPDFPageObjMark_RemoveParam",3),o._FPDFPageObj_GetType=q("FPDFPageObj_GetType",1),o._FPDFPageObj_GetIsActive=q("FPDFPageObj_GetIsActive",2),o._FPDFPageObj_SetIsActive=q("FPDFPageObj_SetIsActive",2),o._FPDFPage_GenerateContent=q("FPDFPage_GenerateContent",1),o._FPDFPageObj_Transform=q("FPDFPageObj_Transform",7),o._FPDFPageObj_TransformF=q("FPDFPageObj_TransformF",2),o._FPDFPageObj_GetMatrix=q("FPDFPageObj_GetMatrix",2),o._FPDFPageObj_SetMatrix=q("FPDFPageObj_SetMatrix",2),o._FPDFPageObj_SetBlendMode=q("FPDFPageObj_SetBlendMode",2),o._FPDFPage_TransformAnnots=q("FPDFPage_TransformAnnots",7),o._FPDFPage_SetRotation=q("FPDFPage_SetRotation",2),o._FPDFPageObj_SetFillColor=q("FPDFPageObj_SetFillColor",5),o._FPDFPageObj_GetFillColor=q("FPDFPageObj_GetFillColor",5),o._FPDFPageObj_GetBounds=q("FPDFPageObj_GetBounds",5),o._FPDFPageObj_GetRotatedBounds=q("FPDFPageObj_GetRotatedBounds",2),o._FPDFPageObj_SetStrokeColor=q("FPDFPageObj_SetStrokeColor",5),o._FPDFPageObj_GetStrokeColor=q("FPDFPageObj_GetStrokeColor",5),o._FPDFPageObj_SetStrokeWidth=q("FPDFPageObj_SetStrokeWidth",2),o._FPDFPageObj_GetStrokeWidth=q("FPDFPageObj_GetStrokeWidth",2),o._FPDFPageObj_GetLineJoin=q("FPDFPageObj_GetLineJoin",1),o._FPDFPageObj_SetLineJoin=q("FPDFPageObj_SetLineJoin",2),o._FPDFPageObj_GetLineCap=q("FPDFPageObj_GetLineCap",1),o._FPDFPageObj_SetLineCap=q("FPDFPageObj_SetLineCap",2),o._FPDFPageObj_GetDashPhase=q("FPDFPageObj_GetDashPhase",2),o._FPDFPageObj_SetDashPhase=q("FPDFPageObj_SetDashPhase",2),o._FPDFPageObj_GetDashCount=q("FPDFPageObj_GetDashCount",1),o._FPDFPageObj_GetDashArray=q("FPDFPageObj_GetDashArray",3),o._FPDFPageObj_SetDashArray=q("FPDFPageObj_SetDashArray",4),o._FPDFFormObj_CountObjects=q("FPDFFormObj_CountObjects",1),o._FPDFFormObj_GetObject=q("FPDFFormObj_GetObject",2),o._FPDFFormObj_RemoveObject=q("FPDFFormObj_RemoveObject",2),o._FPDFPageObj_CreateNewPath=q("FPDFPageObj_CreateNewPath",2),o._FPDFPageObj_CreateNewRect=q("FPDFPageObj_CreateNewRect",4),o._FPDFPath_CountSegments=q("FPDFPath_CountSegments",1),o._FPDFPath_GetPathSegment=q("FPDFPath_GetPathSegment",2),o._FPDFPath_MoveTo=q("FPDFPath_MoveTo",3),o._FPDFPath_LineTo=q("FPDFPath_LineTo",3),o._FPDFPath_BezierTo=q("FPDFPath_BezierTo",7),o._FPDFPath_Close=q("FPDFPath_Close",1),o._FPDFPath_SetDrawMode=q("FPDFPath_SetDrawMode",3),o._FPDFPath_GetDrawMode=q("FPDFPath_GetDrawMode",3),o._FPDFPathSegment_GetPoint=q("FPDFPathSegment_GetPoint",3),o._FPDFPathSegment_GetType=q("FPDFPathSegment_GetType",1),o._FPDFPathSegment_GetClose=q("FPDFPathSegment_GetClose",1),o._FPDFPageObj_NewTextObj=q("FPDFPageObj_NewTextObj",3),o._FPDFText_SetText=q("FPDFText_SetText",2),o._FPDFText_SetCharcodes=q("FPDFText_SetCharcodes",3),o._FPDFText_LoadFont=q("FPDFText_LoadFont",5),o._FPDFText_LoadStandardFont=q("FPDFText_LoadStandardFont",2),o._FPDFText_LoadCidType2Font=q("FPDFText_LoadCidType2Font",6),o._FPDFTextObj_GetFontSize=q("FPDFTextObj_GetFontSize",2),o._FPDFTextObj_GetText=q("FPDFTextObj_GetText",4),o._FPDFTextObj_GetRenderedBitmap=q("FPDFTextObj_GetRenderedBitmap",4),o._FPDFFont_Close=q("FPDFFont_Close",1),o._FPDFPageObj_CreateTextObj=q("FPDFPageObj_CreateTextObj",3),o._FPDFTextObj_GetTextRenderMode=q("FPDFTextObj_GetTextRenderMode",1),o._FPDFTextObj_SetTextRenderMode=q("FPDFTextObj_SetTextRenderMode",2),o._FPDFTextObj_GetFont=q("FPDFTextObj_GetFont",1),o._FPDFFont_GetBaseFontName=q("FPDFFont_GetBaseFontName",3),o._FPDFFont_GetFamilyName=q("FPDFFont_GetFamilyName",3),o._FPDFFont_GetFontData=q("FPDFFont_GetFontData",4),o._FPDFFont_GetIsEmbedded=q("FPDFFont_GetIsEmbedded",1),o._FPDFFont_GetFlags=q("FPDFFont_GetFlags",1),o._FPDFFont_GetWeight=q("FPDFFont_GetWeight",1),o._FPDFFont_GetItalicAngle=q("FPDFFont_GetItalicAngle",2),o._FPDFFont_GetAscent=q("FPDFFont_GetAscent",3),o._FPDFFont_GetDescent=q("FPDFFont_GetDescent",3),o._FPDFFont_GetGlyphWidth=q("FPDFFont_GetGlyphWidth",4),o._FPDFFont_GetGlyphPath=q("FPDFFont_GetGlyphPath",3),o._FPDFGlyphPath_CountGlyphSegments=q("FPDFGlyphPath_CountGlyphSegments",1),o._FPDFGlyphPath_GetGlyphPathSegment=q("FPDFGlyphPath_GetGlyphPathSegment",2),o._EPDFText_RedactInRect=q("EPDFText_RedactInRect",4),o._EPDFText_RedactInQuads=q("EPDFText_RedactInQuads",5),o._FPDFDoc_GetPageMode=q("FPDFDoc_GetPageMode",1),o._FPDFPage_Flatten=q("FPDFPage_Flatten",2),o._FPDFPage_HasFormFieldAtPoint=q("FPDFPage_HasFormFieldAtPoint",4),o._FPDFPage_FormFieldZOrderAtPoint=q("FPDFPage_FormFieldZOrderAtPoint",4),o._malloc=q("malloc",1),o._free=q("free",1),o._FORM_OnMouseMove=q("FORM_OnMouseMove",5),o._FORM_OnMouseWheel=q("FORM_OnMouseWheel",6),o._FORM_OnFocus=q("FORM_OnFocus",5),o._FORM_OnLButtonDown=q("FORM_OnLButtonDown",5),o._FORM_OnLButtonUp=q("FORM_OnLButtonUp",5),o._FORM_OnLButtonDoubleClick=q("FORM_OnLButtonDoubleClick",5),o._FORM_OnRButtonDown=q("FORM_OnRButtonDown",5),o._FORM_OnRButtonUp=q("FORM_OnRButtonUp",5),o._FORM_OnKeyDown=q("FORM_OnKeyDown",4),o._FORM_OnKeyUp=q("FORM_OnKeyUp",4),o._FORM_OnChar=q("FORM_OnChar",4),o._FORM_GetFocusedText=q("FORM_GetFocusedText",4),o._FORM_GetSelectedText=q("FORM_GetSelectedText",4),o._FORM_ReplaceAndKeepSelection=q("FORM_ReplaceAndKeepSelection",3),o._FORM_ReplaceSelection=q("FORM_ReplaceSelection",3),o._FORM_SelectAllText=q("FORM_SelectAllText",2),o._FORM_CanUndo=q("FORM_CanUndo",2),o._FORM_CanRedo=q("FORM_CanRedo",2),o._FORM_Undo=q("FORM_Undo",2),o._FORM_Redo=q("FORM_Redo",2),o._FORM_ForceToKillFocus=q("FORM_ForceToKillFocus",1),o._FORM_GetFocusedAnnot=q("FORM_GetFocusedAnnot",3),o._FORM_SetFocusedAnnot=q("FORM_SetFocusedAnnot",2),o._FPDF_FFLDraw=q("FPDF_FFLDraw",9),o._FPDF_SetFormFieldHighlightColor=q("FPDF_SetFormFieldHighlightColor",3),o._FPDF_SetFormFieldHighlightAlpha=q("FPDF_SetFormFieldHighlightAlpha",2),o._FPDF_RemoveFormFieldHighlight=q("FPDF_RemoveFormFieldHighlight",1),o._FORM_OnAfterLoadPage=q("FORM_OnAfterLoadPage",2),o._FORM_OnBeforeClosePage=q("FORM_OnBeforeClosePage",2),o._FORM_DoDocumentJSAction=q("FORM_DoDocumentJSAction",1),o._FORM_DoDocumentOpenAction=q("FORM_DoDocumentOpenAction",1),o._FORM_DoDocumentAAction=q("FORM_DoDocumentAAction",2),o._FORM_DoPageAAction=q("FORM_DoPageAAction",3),o._FORM_SetIndexSelected=q("FORM_SetIndexSelected",4),o._FORM_IsIndexSelected=q("FORM_IsIndexSelected",3),o._FPDFDoc_GetJavaScriptActionCount=q("FPDFDoc_GetJavaScriptActionCount",1),o._FPDFDoc_GetJavaScriptAction=q("FPDFDoc_GetJavaScriptAction",2),o._FPDFDoc_CloseJavaScriptAction=q("FPDFDoc_CloseJavaScriptAction",1),o._FPDFJavaScriptAction_GetName=q("FPDFJavaScriptAction_GetName",3),o._FPDFJavaScriptAction_GetScript=q("FPDFJavaScriptAction_GetScript",3),o._FPDF_ImportPagesByIndex=q("FPDF_ImportPagesByIndex",5),o._FPDF_ImportPages=q("FPDF_ImportPages",4),o._FPDF_ImportNPagesToOne=q("FPDF_ImportNPagesToOne",5),o._FPDF_NewXObjectFromPage=q("FPDF_NewXObjectFromPage",3),o._FPDF_CloseXObject=q("FPDF_CloseXObject",1),o._FPDF_NewFormObjectFromXObject=q("FPDF_NewFormObjectFromXObject",1),o._FPDF_CopyViewerPreferences=q("FPDF_CopyViewerPreferences",2),o._FPDF_RenderPageBitmapWithColorScheme_Start=q("FPDF_RenderPageBitmapWithColorScheme_Start",10),o._FPDF_RenderPageBitmap_Start=q("FPDF_RenderPageBitmap_Start",9),o._FPDF_RenderPage_Continue=q("FPDF_RenderPage_Continue",2),o._FPDF_RenderPage_Close=q("FPDF_RenderPage_Close",1),o._FPDF_SaveWithVersion=q("FPDF_SaveWithVersion",4),o._FPDFText_GetCharIndexFromTextIndex=q("FPDFText_GetCharIndexFromTextIndex",2),o._FPDFText_GetTextIndexFromCharIndex=q("FPDFText_GetTextIndexFromCharIndex",2),o._FPDF_GetSignatureCount=q("FPDF_GetSignatureCount",1),o._FPDF_GetSignatureObject=q("FPDF_GetSignatureObject",2),o._FPDFSignatureObj_GetContents=q("FPDFSignatureObj_GetContents",3),o._FPDFSignatureObj_GetByteRange=q("FPDFSignatureObj_GetByteRange",3),o._FPDFSignatureObj_GetSubFilter=q("FPDFSignatureObj_GetSubFilter",3),o._FPDFSignatureObj_GetReason=q("FPDFSignatureObj_GetReason",3),o._FPDFSignatureObj_GetTime=q("FPDFSignatureObj_GetTime",3),o._FPDFSignatureObj_GetDocMDPPermission=q("FPDFSignatureObj_GetDocMDPPermission",1),o._FPDF_StructTree_GetForPage=q("FPDF_StructTree_GetForPage",1),o._FPDF_StructTree_Close=q("FPDF_StructTree_Close",1),o._FPDF_StructTree_CountChildren=q("FPDF_StructTree_CountChildren",1),o._FPDF_StructTree_GetChildAtIndex=q("FPDF_StructTree_GetChildAtIndex",2),o._FPDF_StructElement_GetAltText=q("FPDF_StructElement_GetAltText",3),o._FPDF_StructElement_GetActualText=q("FPDF_StructElement_GetActualText",3),o._FPDF_StructElement_GetID=q("FPDF_StructElement_GetID",3),o._FPDF_StructElement_GetLang=q("FPDF_StructElement_GetLang",3),o._FPDF_StructElement_GetAttributeCount=q("FPDF_StructElement_GetAttributeCount",1),o._FPDF_StructElement_GetAttributeAtIndex=q("FPDF_StructElement_GetAttributeAtIndex",2),o._FPDF_StructElement_GetStringAttribute=q("FPDF_StructElement_GetStringAttribute",4),o._FPDF_StructElement_GetMarkedContentID=q("FPDF_StructElement_GetMarkedContentID",1),o._FPDF_StructElement_GetType=q("FPDF_StructElement_GetType",3),o._FPDF_StructElement_GetObjType=q("FPDF_StructElement_GetObjType",3),o._FPDF_StructElement_GetTitle=q("FPDF_StructElement_GetTitle",3),o._FPDF_StructElement_CountChildren=q("FPDF_StructElement_CountChildren",1),o._FPDF_StructElement_GetChildAtIndex=q("FPDF_StructElement_GetChildAtIndex",2),o._FPDF_StructElement_GetChildMarkedContentID=q("FPDF_StructElement_GetChildMarkedContentID",2),o._FPDF_StructElement_GetParent=q("FPDF_StructElement_GetParent",1),o._FPDF_StructElement_Attr_GetCount=q("FPDF_StructElement_Attr_GetCount",1),o._FPDF_StructElement_Attr_GetName=q("FPDF_StructElement_Attr_GetName",5),o._FPDF_StructElement_Attr_GetValue=q("FPDF_StructElement_Attr_GetValue",2),o._FPDF_StructElement_Attr_GetType=q("FPDF_StructElement_Attr_GetType",1),o._FPDF_StructElement_Attr_GetBooleanValue=q("FPDF_StructElement_Attr_GetBooleanValue",2),o._FPDF_StructElement_Attr_GetNumberValue=q("FPDF_StructElement_Attr_GetNumberValue",2),o._FPDF_StructElement_Attr_GetStringValue=q("FPDF_StructElement_Attr_GetStringValue",4),o._FPDF_StructElement_Attr_GetBlobValue=q("FPDF_StructElement_Attr_GetBlobValue",4),o._FPDF_StructElement_Attr_CountChildren=q("FPDF_StructElement_Attr_CountChildren",1),o._FPDF_StructElement_Attr_GetChildAtIndex=q("FPDF_StructElement_Attr_GetChildAtIndex",2),o._FPDF_StructElement_GetMarkedContentIdCount=q("FPDF_StructElement_GetMarkedContentIdCount",1),o._FPDF_StructElement_GetMarkedContentIdAtIndex=q("FPDF_StructElement_GetMarkedContentIdAtIndex",2),o._FPDF_AddInstalledFont=q("FPDF_AddInstalledFont",3),o._FPDF_SetSystemFontInfo=q("FPDF_SetSystemFontInfo",1),o._FPDF_GetDefaultTTFMap=q("FPDF_GetDefaultTTFMap",0),o._FPDF_GetDefaultTTFMapCount=q("FPDF_GetDefaultTTFMapCount",0),o._FPDF_GetDefaultTTFMapEntry=q("FPDF_GetDefaultTTFMapEntry",1),o._FPDF_GetDefaultSystemFontInfo=q("FPDF_GetDefaultSystemFontInfo",0),o._FPDF_FreeDefaultSystemFontInfo=q("FPDF_FreeDefaultSystemFontInfo",1),o._FPDFText_LoadPage=q("FPDFText_LoadPage",1),o._FPDFText_ClosePage=q("FPDFText_ClosePage",1),o._FPDFText_CountChars=q("FPDFText_CountChars",1),o._FPDFText_GetUnicode=q("FPDFText_GetUnicode",2),o._FPDFText_GetTextObject=q("FPDFText_GetTextObject",2),o._FPDFText_IsGenerated=q("FPDFText_IsGenerated",2),o._FPDFText_IsHyphen=q("FPDFText_IsHyphen",2),o._FPDFText_HasUnicodeMapError=q("FPDFText_HasUnicodeMapError",2),o._FPDFText_GetFontSize=q("FPDFText_GetFontSize",2),o._FPDFText_GetFontInfo=q("FPDFText_GetFontInfo",5),o._FPDFText_GetFontWeight=q("FPDFText_GetFontWeight",2),o._FPDFText_GetFillColor=q("FPDFText_GetFillColor",6),o._FPDFText_GetStrokeColor=q("FPDFText_GetStrokeColor",6),o._FPDFText_GetCharAngle=q("FPDFText_GetCharAngle",2),o._FPDFText_GetCharBox=q("FPDFText_GetCharBox",6),o._FPDFText_GetLooseCharBox=q("FPDFText_GetLooseCharBox",3),o._FPDFText_GetMatrix=q("FPDFText_GetMatrix",3),o._FPDFText_GetCharOrigin=q("FPDFText_GetCharOrigin",4),o._FPDFText_GetCharIndexAtPos=q("FPDFText_GetCharIndexAtPos",5),o._FPDFText_GetText=q("FPDFText_GetText",4),o._FPDFText_CountRects=q("FPDFText_CountRects",3),o._FPDFText_GetRect=q("FPDFText_GetRect",6),o._FPDFText_GetBoundedText=q("FPDFText_GetBoundedText",7),o._FPDFText_FindStart=q("FPDFText_FindStart",4),o._FPDFText_FindNext=q("FPDFText_FindNext",1),o._FPDFText_FindPrev=q("FPDFText_FindPrev",1),o._FPDFText_GetSchResultIndex=q("FPDFText_GetSchResultIndex",1),o._FPDFText_GetSchCount=q("FPDFText_GetSchCount",1),o._FPDFText_FindClose=q("FPDFText_FindClose",1),o._FPDFLink_LoadWebLinks=q("FPDFLink_LoadWebLinks",1),o._FPDFLink_CountWebLinks=q("FPDFLink_CountWebLinks",1),o._FPDFLink_GetURL=q("FPDFLink_GetURL",4),o._FPDFLink_CountRects=q("FPDFLink_CountRects",2),o._FPDFLink_GetRect=q("FPDFLink_GetRect",7),o._FPDFLink_GetTextRange=q("FPDFLink_GetTextRange",4),o._FPDFLink_CloseWebLinks=q("FPDFLink_CloseWebLinks",1),o._FPDFPage_GetDecodedThumbnailData=q("FPDFPage_GetDecodedThumbnailData",3),o._FPDFPage_GetRawThumbnailData=q("FPDFPage_GetRawThumbnailData",3),o._FPDFPage_GetThumbnailAsBitmap=q("FPDFPage_GetThumbnailAsBitmap",1),o._FPDFPage_SetMediaBox=q("FPDFPage_SetMediaBox",5),o._FPDFPage_SetCropBox=q("FPDFPage_SetCropBox",5),o._FPDFPage_SetBleedBox=q("FPDFPage_SetBleedBox",5),o._FPDFPage_SetTrimBox=q("FPDFPage_SetTrimBox",5),o._FPDFPage_SetArtBox=q("FPDFPage_SetArtBox",5),o._FPDFPage_GetMediaBox=q("FPDFPage_GetMediaBox",5),o._FPDFPage_GetCropBox=q("FPDFPage_GetCropBox",5),o._FPDFPage_GetBleedBox=q("FPDFPage_GetBleedBox",5),o._FPDFPage_GetTrimBox=q("FPDFPage_GetTrimBox",5),o._FPDFPage_GetArtBox=q("FPDFPage_GetArtBox",5),o._FPDFPage_TransFormWithClip=q("FPDFPage_TransFormWithClip",3),o._FPDFPageObj_TransformClipPath=q("FPDFPageObj_TransformClipPath",7),o._FPDFPageObj_GetClipPath=q("FPDFPageObj_GetClipPath",1),o._FPDFClipPath_CountPaths=q("FPDFClipPath_CountPaths",1),o._FPDFClipPath_CountPathSegments=q("FPDFClipPath_CountPathSegments",2),o._FPDFClipPath_GetPathSegment=q("FPDFClipPath_GetPathSegment",3),o._FPDF_CreateClipPath=q("FPDF_CreateClipPath",4),o._FPDF_DestroyClipPath=q("FPDF_DestroyClipPath",1),o._FPDFPage_InsertClipPath=q("FPDFPage_InsertClipPath",2),o._FPDF_InitLibrary=q("FPDF_InitLibrary",0),o._FPDF_DestroyLibrary=q("FPDF_DestroyLibrary",0),o._FPDF_SetSandBoxPolicy=q("FPDF_SetSandBoxPolicy",2),o._FPDF_LoadDocument=q("FPDF_LoadDocument",2),o._FPDF_GetFormType=q("FPDF_GetFormType",1),o._FPDF_LoadXFA=q("FPDF_LoadXFA",1),o._FPDF_LoadMemDocument=q("FPDF_LoadMemDocument",3),o._FPDF_LoadMemDocument64=q("FPDF_LoadMemDocument64",3),o._FPDF_LoadCustomDocument=q("FPDF_LoadCustomDocument",2),o._FPDF_GetFileVersion=q("FPDF_GetFileVersion",2),o._FPDF_DocumentHasValidCrossReferenceTable=q("FPDF_DocumentHasValidCrossReferenceTable",1),o._FPDF_GetDocPermissions=q("FPDF_GetDocPermissions",1),o._FPDF_GetDocUserPermissions=q("FPDF_GetDocUserPermissions",1),o._FPDF_GetSecurityHandlerRevision=q("FPDF_GetSecurityHandlerRevision",1),o._EPDF_SetEncryption=q("EPDF_SetEncryption",4),o._EPDF_RemoveEncryption=q("EPDF_RemoveEncryption",1),o._EPDF_UnlockOwnerPermissions=q("EPDF_UnlockOwnerPermissions",2),o._EPDF_IsEncrypted=q("EPDF_IsEncrypted",1),o._EPDF_IsOwnerUnlocked=q("EPDF_IsOwnerUnlocked",1),o._FPDF_GetPageCount=q("FPDF_GetPageCount",1),o._FPDF_LoadPage=q("FPDF_LoadPage",2),o._FPDF_GetPageWidthF=q("FPDF_GetPageWidthF",1),o._FPDF_GetPageWidth=q("FPDF_GetPageWidth",1),o._FPDF_GetPageHeightF=q("FPDF_GetPageHeightF",1),o._FPDF_GetPageHeight=q("FPDF_GetPageHeight",1),o._FPDF_GetPageBoundingBox=q("FPDF_GetPageBoundingBox",2),o._FPDF_RenderPageBitmap=q("FPDF_RenderPageBitmap",8),o._FPDF_RenderPageBitmapWithMatrix=q("FPDF_RenderPageBitmapWithMatrix",5),o._EPDF_RenderAnnotBitmap=q("EPDF_RenderAnnotBitmap",6),o._EPDF_RenderAnnotBitmapUnrotated=q("EPDF_RenderAnnotBitmapUnrotated",6),o._FPDF_ClosePage=q("FPDF_ClosePage",1),o._FPDF_CloseDocument=q("FPDF_CloseDocument",1),o._FPDF_GetLastError=q("FPDF_GetLastError",0),o._FPDF_DeviceToPage=q("FPDF_DeviceToPage",10),o._FPDF_PageToDevice=q("FPDF_PageToDevice",10),o._FPDFBitmap_Create=q("FPDFBitmap_Create",3),o._FPDFBitmap_CreateEx=q("FPDFBitmap_CreateEx",5),o._FPDFBitmap_GetFormat=q("FPDFBitmap_GetFormat",1),o._FPDFBitmap_FillRect=q("FPDFBitmap_FillRect",6),o._FPDFBitmap_GetBuffer=q("FPDFBitmap_GetBuffer",1),o._FPDFBitmap_GetWidth=q("FPDFBitmap_GetWidth",1),o._FPDFBitmap_GetHeight=q("FPDFBitmap_GetHeight",1),o._FPDFBitmap_GetStride=q("FPDFBitmap_GetStride",1),o._FPDFBitmap_Destroy=q("FPDFBitmap_Destroy",1),o._FPDF_GetPageSizeByIndexF=q("FPDF_GetPageSizeByIndexF",3),o._EPDF_GetPageRotationByIndex=q("EPDF_GetPageRotationByIndex",2),o._EPDF_GetPageSizeByIndexNormalized=q("EPDF_GetPageSizeByIndexNormalized",3),o._EPDF_LoadPageNormalized=q("EPDF_LoadPageNormalized",3),o._FPDF_GetPageSizeByIndex=q("FPDF_GetPageSizeByIndex",4),o._FPDF_VIEWERREF_GetPrintScaling=q("FPDF_VIEWERREF_GetPrintScaling",1),o._FPDF_VIEWERREF_GetNumCopies=q("FPDF_VIEWERREF_GetNumCopies",1),o._FPDF_VIEWERREF_GetPrintPageRange=q("FPDF_VIEWERREF_GetPrintPageRange",1),o._FPDF_VIEWERREF_GetPrintPageRangeCount=q("FPDF_VIEWERREF_GetPrintPageRangeCount",1),o._FPDF_VIEWERREF_GetPrintPageRangeElement=q("FPDF_VIEWERREF_GetPrintPageRangeElement",2),o._FPDF_VIEWERREF_GetDuplex=q("FPDF_VIEWERREF_GetDuplex",1),o._FPDF_VIEWERREF_GetName=q("FPDF_VIEWERREF_GetName",4),o._FPDF_CountNamedDests=q("FPDF_CountNamedDests",1),o._FPDF_GetNamedDestByName=q("FPDF_GetNamedDestByName",2),o._FPDF_GetNamedDest=q("FPDF_GetNamedDest",4),o._FPDF_GetXFAPacketCount=q("FPDF_GetXFAPacketCount",1),o._FPDF_GetXFAPacketName=q("FPDF_GetXFAPacketName",4),o._FPDF_GetXFAPacketContent=q("FPDF_GetXFAPacketContent",5),o._FPDF_GetTrailerEnds=q("FPDF_GetTrailerEnds",3);var Ze,et,tt=q("fflush",1),nt=q("emscripten_builtin_memalign",2),rt=q("strerror",1),ot=q("setThrew",2),at=()=>(at=Qe.emscripten_stack_init)(),it=()=>(it=Qe.emscripten_stack_get_end)(),st=e=>(st=Qe._emscripten_stack_restore)(e),ut=e=>(ut=Qe._emscripten_stack_alloc)(e),mt=()=>(mt=Qe.emscripten_stack_get_current)();function Ft(){var e;at(),C(!(3&(e=it()))),0==e&&(e+=4),y[e>>2]=34821223,y[e+4>>2]=2310721022,y[0]=1668509029}function lt(){var e;function t(){Ze||(Ze=1,o.calledRun=1,S||(C(!k),k=!0,T(),o.noFSInit||Oe.initialized||Oe.init(),Oe.ignorePermissions=!1,ie(O),n(o),o.onRuntimeInitialized?.(),C(!o._main,'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]'),function(){T();var e=o.postRun;e&&("function"==typeof e&&(e=[e]),e.forEach(I)),ie(R)}()))}B>0||(Ft(),!et&&(et=1,(e=o.preRun)&&("function"==typeof e&&(e=[e]),e.forEach(w)),ie(v),B>0)||(o.setStatus?(o.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>o.setStatus(""),1),t()},1)):t(),T()))}if(o.dynCall_j=q("dynCall_j",1),o.dynCall_ji=q("dynCall_ji",2),o.dynCall_iiij=q("dynCall_iiij",5),o.dynCall_jji=q("dynCall_jji",4),o.dynCall_iji=q("dynCall_iji",4),o.dynCall_viijii=q("dynCall_viijii",7),o.dynCall_jij=q("dynCall_jij",4),o.dynCall_iij=q("dynCall_iij",4),o.dynCall_iiji=q("dynCall_iiji",5),o.dynCall_jiji=q("dynCall_jiji",5),o.dynCall_iiiiij=q("dynCall_iiiiij",7),o.dynCall_iiiiijj=q("dynCall_iiiiijj",9),o.dynCall_iiiiiijj=q("dynCall_iiiiiijj",10),o.dynCall_viji=q("dynCall_viji",5),o.wasmExports=Qe,o.ccall=Je,o.cwrap=(e,t,n,r)=>(...r)=>Je(e,t,n,r),o.addFunction=(e,t)=>{C(void 0!==e);var n=He(e);if(n)return n;var r=(()=>{if(Ye.length)return Ye.pop();try{Ee.grow(1)}catch(e){if(!(e instanceof RangeError))throw e;throw"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."}return Ee.length-1})();try{Xe(r,e)}catch(n){if(!(n instanceof TypeError))throw n;C(void 0!==t,"Missing signature argument to addFunction: "+e);var o=We(e,t);Xe(r,o)}return ye.set(e,r),r},o.removeFunction=e=>{ye.delete(Ue(e)),Xe(e,null),Ye.push(e)},o.setValue=function(e,t,n="i8"){switch(n.endsWith("*")&&(n="*"),n){case"i1":case"i8":b[e]=t;break;case"i16":f[e>>1]=t;break;case"i32":E[e>>2]=t;break;case"i64":W("to do setValue(i64) use WASM_BIGINT");case"float":M[e>>2]=t;break;case"double":G[e>>3]=t;break;case"*":y[e>>2]=t;break;default:W(`invalid type for setValue: ${n}`)}},o.getValue=function(e,t="i8"){switch(t.endsWith("*")&&(t="*"),t){case"i1":case"i8":return b[e];case"i16":return f[e>>1];case"i32":return E[e>>2];case"i64":W("to do getValue(i64) use WASM_BIGINT");case"float":return M[e>>2];case"double":return G[e>>3];case"*":return y[e>>2];default:W(`invalid type for getValue: ${t}`)}},o.UTF8ToString=ce,o.stringToUTF8=we,o.UTF16ToString=(e,t)=>{C(e%2==0,"Pointer passed to UTF16ToString must be aligned to two bytes!");for(var n=e,r=n>>1,o=r+t/2;!(r>=o)&&A[r];)++r;if((n=r<<1)-e>32&&ze)return ze.decode(p.subarray(e,n));for(var a="",i=0;!(i>=t/2);++i){var s=f[e+2*i>>1];if(0==s)break;a+=String.fromCharCode(s)}return a},o.stringToUTF16=(e,t,n)=>{if(C(t%2==0,"Pointer passed to stringToUTF16 must be aligned to two bytes!"),C("number"==typeof n,"stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!"),n??=2147483647,n<2)return 0;for(var r=t,o=(n-=2)<2*e.length?n/2:e.length,a=0;a>1]=i,t+=2}return f[t>>1]=0,t-r},["writeI53ToI64","writeI53ToI64Clamped","writeI53ToI64Signaling","writeI53ToU64Clamped","writeI53ToU64Signaling","readI53FromI64","readI53FromU64","convertI32PairToI53","convertU32PairToI53","getTempRet0","setTempRet0","exitJS","inetPton4","inetNtop4","inetPton6","inetNtop6","readSockaddr","writeSockaddr","emscriptenLog","readEmAsmArgs","jstoi_q","listenOnce","autoResumeAudioContext","dynCallLegacy","getDynCaller","dynCall","handleException","keepRuntimeAlive","runtimeKeepalivePush","runtimeKeepalivePop","callUserCallback","maybeExit","asmjsMangle","HandleAllocator","getNativeTypeSize","STACK_SIZE","STACK_ALIGN","POINTER_SIZE","ASSERTIONS","reallyNegative","unSign","strLen","reSign","formatString","intArrayToString","AsciiToString","lengthBytesUTF16","UTF32ToString","stringToUTF32","lengthBytesUTF32","stringToNewUTF8","registerKeyEventCallback","maybeCStringToJsString","findEventTarget","getBoundingClientRect","fillMouseEventData","registerMouseEventCallback","registerWheelEventCallback","registerUiEventCallback","registerFocusEventCallback","fillDeviceOrientationEventData","registerDeviceOrientationEventCallback","fillDeviceMotionEventData","registerDeviceMotionEventCallback","screenOrientation","fillOrientationChangeEventData","registerOrientationChangeEventCallback","fillFullscreenChangeEventData","registerFullscreenChangeEventCallback","JSEvents_requestFullscreen","JSEvents_resizeCanvasForFullscreen","registerRestoreOldStyle","hideEverythingExceptGivenElement","restoreHiddenElements","setLetterbox","softFullscreenResizeWebGLRenderTarget","doRequestFullscreen","fillPointerlockChangeEventData","registerPointerlockChangeEventCallback","registerPointerlockErrorEventCallback","requestPointerLock","fillVisibilityChangeEventData","registerVisibilityChangeEventCallback","registerTouchEventCallback","fillGamepadEventData","registerGamepadEventCallback","registerBeforeUnloadEventCallback","fillBatteryEventData","battery","registerBatteryEventCallback","setCanvasElementSize","getCanvasElementSize","jsStackTrace","getCallstack","convertPCtoSourceLocation","checkWasiClock","wasiRightsToMuslOFlags","wasiOFlagsToMuslOFlags","createDyncallWrapper","safeSetTimeout","setImmediateWrapped","clearImmediateWrapped","polyfillSetImmediate","registerPostMainLoop","registerPreMainLoop","getPromise","makePromise","idsToPromises","makePromiseCallback","ExceptionInfo","findMatchingCatch","Browser_asyncPrepareDataCounter","safeRequestAnimationFrame","arraySum","addDays","getSocketFromFD","getSocketAddress","FS_unlink","FS_mkdirTree","_setNetworkCallback","heapObjectForWebGLType","toTypedArrayIndex","webgl_enable_ANGLE_instanced_arrays","webgl_enable_OES_vertex_array_object","webgl_enable_WEBGL_draw_buffers","webgl_enable_WEBGL_multi_draw","webgl_enable_EXT_polygon_offset_clamp","webgl_enable_EXT_clip_control","webgl_enable_WEBGL_polygon_mode","emscriptenWebGLGet","computeUnpackAlignedImageSize","colorChannelsInGlTextureFormat","emscriptenWebGLGetTexPixelData","emscriptenWebGLGetUniform","webglGetUniformLocation","webglPrepareUniformLocationsBeforeFirstUse","webglGetLeftBracePos","emscriptenWebGLGetVertexAttrib","__glGetActiveAttribOrUniform","writeGLArray","registerWebGlEventCallback","runAndAbortIfError","ALLOC_NORMAL","ALLOC_STACK","allocate","writeStringToMemory","writeAsciiToMemory","setErrNo","demangle","stackTrace"].forEach(function(e){re(e,()=>{var t=`\`${e}\` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line`,n=e;n.startsWith("_")||(n="$"+e),t+=` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='${n}')`,ne(e)&&(t+=". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you"),Fe(t)}),ae(e)}),["run","addOnPreRun","addOnInit","addOnPreMain","addOnExit","addOnPostRun","addRunDependency","removeRunDependency","out","err","callMain","abort","wasmMemory","writeStackCookie","checkStackCookie","convertI32PairToI53Checked","stackSave","stackRestore","stackAlloc","ptrToString","zeroMemory","getHeapMax","growMemory","ENV","ERRNO_CODES","strError","DNS","Protocols","Sockets","initRandomFill","randomFill","timers","warnOnce","readEmAsmArgsArray","jstoi_s","getExecutableName","asyncLoad","alignMemory","mmapAlloc","wasmTable","noExitRuntime","getCFunc","uleb128Encode","sigToWasmTypes","generateFuncType","convertJsFunctionToWasm","freeTableIndexes","functionsInTableMap","getEmptyTableSlot","updateTableMap","getFunctionAddress","PATH","PATH_FS","UTF8Decoder","UTF8ArrayToString","stringToUTF8Array","lengthBytesUTF8","intArrayFromString","stringToAscii","UTF16Decoder","stringToUTF8OnStack","writeArrayToMemory","JSEvents","specialHTMLTargets","findCanvasEventTarget","currentFullscreenStrategy","restoreOldWindowedStyle","UNWIND_CACHE","ExitStatus","getEnvStrings","doReadv","doWritev","promiseMap","uncaughtExceptionCount","exceptionLast","exceptionCaught","Browser","getPreloadedImageData__data","wget","MONTH_DAYS_REGULAR","MONTH_DAYS_LEAP","MONTH_DAYS_REGULAR_CUMULATIVE","MONTH_DAYS_LEAP_CUMULATIVE","isLeapYear","ydayFromDate","SYSCALLS","preloadPlugins","FS_createPreloadedFile","FS_modeStringToFlags","FS_getMode","FS_stdin_getChar_buffer","FS_stdin_getChar","FS_createPath","FS_createDevice","FS_readFile","FS","FS_createDataFile","FS_createLazyFile","MEMFS","TTY","PIPEFS","SOCKFS","tempFixedLengthArray","miniTempWebGLFloatBuffers","miniTempWebGLIntBuffers","GL","AL","GLUT","EGL","GLEW","IDBStore","SDL","SDL_gfx","allocateUTF8","allocateUTF8OnStack","print","printErr"].forEach(ae),L=function e(){Ze||lt(),Ze||(L=e)},o.preInit)for("function"==typeof o.preInit&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();lt(),t=a;for(const t of Object.keys(o))t in e||Object.defineProperty(e,t,{configurable:!0,get(){W(`Access to module property ('${t}') is no longer possible via the module constructor argument; Instead, use the result of the module constructor.`)}});return t});const z={EPDF_GetMetaKeyCount:[["number","boolean"],"number"],EPDF_GetMetaKeyName:[["number","number","boolean","number","number"],"number"],EPDF_GetMetaTrapped:[["number"],"number"],EPDF_GetPageRotationByIndex:[["number","number"],"number"],EPDF_GetPageSizeByIndexNormalized:[["number","number","number"],"boolean"],EPDF_HasMetaText:[["number","string"],"boolean"],EPDF_IsEncrypted:[["number"],"boolean"],EPDF_IsOwnerUnlocked:[["number"],"boolean"],EPDF_LoadPageNormalized:[["number","number","number"],"number"],EPDF_PNG_EncodeRGBA:[["number","number","number","number","number","number"],"number"],EPDF_RemoveEncryption:[["number"],"boolean"],EPDF_RenderAnnotBitmap:[["number","number","number","number","number","number"],"boolean"],EPDF_RenderAnnotBitmapUnrotated:[["number","number","number","number","number","number"],"boolean"],EPDF_SetEncryption:[["number","string","string","number"],"boolean"],EPDF_SetMetaText:[["number","string","number"],"boolean"],EPDF_SetMetaTrapped:[["number","number"],"boolean"],EPDF_UnlockOwnerPermissions:[["number","string"],"boolean"],EPDFAction_CreateGoTo:[["number","number"],"number"],EPDFAction_CreateGoToNamed:[["number","string"],"number"],EPDFAction_CreateLaunch:[["number","number"],"number"],EPDFAction_CreateRemoteGoToByName:[["number","number","number"],"number"],EPDFAction_CreateRemoteGoToDest:[["number","number","number"],"number"],EPDFAction_CreateURI:[["number","string"],"number"],EPDFAnnot_ApplyRedaction:[["number","number"],"boolean"],EPDFAnnot_ClearColor:[["number","number"],"boolean"],EPDFAnnot_ClearRectangleDifferences:[["number"],"boolean"],EPDFAnnot_Flatten:[["number","number"],"boolean"],EPDFAnnot_GenerateAppearance:[["number"],"boolean"],EPDFAnnot_GenerateAppearanceWithBlend:[["number","number"],"boolean"],EPDFAnnot_GetAPMatrix:[["number","number","number"],"boolean"],EPDFAnnot_GetAvailableAppearanceModes:[["number"],"number"],EPDFAnnot_GetBlendMode:[["number"],"number"],EPDFAnnot_GetBorderDashPattern:[["number","number","number"],"boolean"],EPDFAnnot_GetBorderDashPatternCount:[["number"],"number"],EPDFAnnot_GetBorderEffect:[["number","number"],"boolean"],EPDFAnnot_GetBorderStyle:[["number","number"],"number"],EPDFAnnot_GetColor:[["number","number","number","number","number"],"boolean"],EPDFAnnot_GetDefaultAppearance:[["number","number","number","number","number","number"],"boolean"],EPDFAnnot_GetExtendedRotation:[["number","number"],"boolean"],EPDFAnnot_GetIcon:[["number"],"number"],EPDFAnnot_GetIntent:[["number","number","number"],"number"],EPDFAnnot_GetLineEndings:[["number","number","number"],"boolean"],EPDFAnnot_GetOpacity:[["number","number"],"boolean"],EPDFAnnot_GetOverlayText:[["number","number","number"],"number"],EPDFAnnot_GetOverlayTextRepeat:[["number"],"boolean"],EPDFAnnot_GetRect:[["number","number"],"boolean"],EPDFAnnot_GetRectangleDifferences:[["number","number","number","number","number"],"boolean"],EPDFAnnot_GetReplyType:[["number"],"number"],EPDFAnnot_GetRichContent:[["number","number","number"],"number"],EPDFAnnot_GetRotate:[["number","number"],"boolean"],EPDFAnnot_GetTextAlignment:[["number"],"number"],EPDFAnnot_GetUnrotatedRect:[["number","number"],"boolean"],EPDFAnnot_GetVerticalAlignment:[["number"],"number"],EPDFAnnot_HasAppearanceStream:[["number","number"],"boolean"],EPDFAnnot_SetAction:[["number","number"],"boolean"],EPDFAnnot_SetAPMatrix:[["number","number","number"],"boolean"],EPDFAnnot_SetBorderDashPattern:[["number","number","number"],"boolean"],EPDFAnnot_SetBorderStyle:[["number","number","number"],"boolean"],EPDFAnnot_SetColor:[["number","number","number","number","number"],"boolean"],EPDFAnnot_SetDefaultAppearance:[["number","number","number","number","number","number"],"boolean"],EPDFAnnot_SetExtendedRotation:[["number","number"],"boolean"],EPDFAnnot_SetIcon:[["number","number"],"boolean"],EPDFAnnot_SetIntent:[["number","string"],"boolean"],EPDFAnnot_SetLine:[["number","number","number"],"boolean"],EPDFAnnot_SetLineEndings:[["number","number","number"],"boolean"],EPDFAnnot_SetLinkedAnnot:[["number","string","number"],"boolean"],EPDFAnnot_SetOpacity:[["number","number"],"boolean"],EPDFAnnot_SetOverlayText:[["number","number"],"boolean"],EPDFAnnot_SetOverlayTextRepeat:[["number","boolean"],"boolean"],EPDFAnnot_SetRectangleDifferences:[["number","number","number","number","number"],"boolean"],EPDFAnnot_SetReplyType:[["number","number"],"boolean"],EPDFAnnot_SetRotate:[["number","number"],"boolean"],EPDFAnnot_SetTextAlignment:[["number","number"],"boolean"],EPDFAnnot_SetUnrotatedRect:[["number","number"],"boolean"],EPDFAnnot_SetVerticalAlignment:[["number","number"],"boolean"],EPDFAnnot_SetVertices:[["number","number","number"],"boolean"],EPDFAnnot_UpdateAppearanceToRect:[["number","number"],"boolean"],EPDFAttachment_GetDescription:[["number","number","number"],"number"],EPDFAttachment_GetIntegerValue:[["number","string","number"],"boolean"],EPDFAttachment_SetDescription:[["number","number"],"boolean"],EPDFAttachment_SetSubtype:[["number","string"],"boolean"],EPDFBookmark_AppendChild:[["number","number","number"],"number"],EPDFBookmark_Clear:[["number"],"boolean"],EPDFBookmark_ClearTarget:[["number"],"boolean"],EPDFBookmark_Create:[["number","number"],"number"],EPDFBookmark_Delete:[["number","number"],"boolean"],EPDFBookmark_InsertAfter:[["number","number","number","number"],"number"],EPDFBookmark_SetAction:[["number","number","number"],"boolean"],EPDFBookmark_SetDest:[["number","number","number"],"boolean"],EPDFBookmark_SetTitle:[["number","number"],"boolean"],EPDFCatalog_GetLanguage:[["number","number","number"],"number"],EPDFDest_CreateRemoteView:[["number","number","number","number","number"],"number"],EPDFDest_CreateRemoteXYZ:[["number","number","boolean","number","boolean","number","boolean","number"],"number"],EPDFDest_CreateView:[["number","number","number","number"],"number"],EPDFDest_CreateXYZ:[["number","boolean","number","boolean","number","boolean","number"],"number"],EPDFNamedDest_Remove:[["number","string"],"boolean"],EPDFNamedDest_SetDest:[["number","string","number"],"boolean"],EPDFPage_ApplyRedactions:[["number"],"boolean"],EPDFPage_CreateAnnot:[["number","number"],"number"],EPDFPage_GetAnnotByName:[["number","number"],"number"],EPDFPage_GetAnnotCountRaw:[["number","number"],"number"],EPDFPage_GetAnnotRaw:[["number","number","number"],"number"],EPDFPage_RemoveAnnotByName:[["number","number"],"boolean"],EPDFPage_RemoveAnnotRaw:[["number","number","number"],"boolean"],EPDFText_RedactInQuads:[["number","number","number","boolean","boolean"],"boolean"],EPDFText_RedactInRect:[["number","number","boolean","boolean"],"boolean"],FORM_CanRedo:[["number","number"],"boolean"],FORM_CanUndo:[["number","number"],"boolean"],FORM_DoDocumentAAction:[["number","number"],null],FORM_DoDocumentJSAction:[["number"],null],FORM_DoDocumentOpenAction:[["number"],null],FORM_DoPageAAction:[["number","number","number"],null],FORM_ForceToKillFocus:[["number"],"boolean"],FORM_GetFocusedAnnot:[["number","number","number"],"boolean"],FORM_GetFocusedText:[["number","number","number","number"],"number"],FORM_GetSelectedText:[["number","number","number","number"],"number"],FORM_IsIndexSelected:[["number","number","number"],"boolean"],FORM_OnAfterLoadPage:[["number","number"],null],FORM_OnBeforeClosePage:[["number","number"],null],FORM_OnChar:[["number","number","number","number"],"boolean"],FORM_OnFocus:[["number","number","number","number","number"],"boolean"],FORM_OnKeyDown:[["number","number","number","number"],"boolean"],FORM_OnKeyUp:[["number","number","number","number"],"boolean"],FORM_OnLButtonDoubleClick:[["number","number","number","number","number"],"boolean"],FORM_OnLButtonDown:[["number","number","number","number","number"],"boolean"],FORM_OnLButtonUp:[["number","number","number","number","number"],"boolean"],FORM_OnMouseMove:[["number","number","number","number","number"],"boolean"],FORM_OnMouseWheel:[["number","number","number","number","number","number"],"boolean"],FORM_OnRButtonDown:[["number","number","number","number","number"],"boolean"],FORM_OnRButtonUp:[["number","number","number","number","number"],"boolean"],FORM_Redo:[["number","number"],"boolean"],FORM_ReplaceAndKeepSelection:[["number","number","number"],null],FORM_ReplaceSelection:[["number","number","number"],null],FORM_SelectAllText:[["number","number"],"boolean"],FORM_SetFocusedAnnot:[["number","number"],"boolean"],FORM_SetIndexSelected:[["number","number","number","boolean"],"boolean"],FORM_Undo:[["number","number"],"boolean"],FPDF_AddInstalledFont:[["number","number","number"],null],FPDF_CloseDocument:[["number"],null],FPDF_ClosePage:[["number"],null],FPDF_CloseXObject:[["number"],null],FPDF_CopyViewerPreferences:[["number","number"],"boolean"],FPDF_CountNamedDests:[["number"],"number"],FPDF_CreateClipPath:[["number","number","number","number"],"number"],FPDF_CreateNewDocument:[[],"number"],FPDF_DestroyClipPath:[["number"],null],FPDF_DestroyLibrary:[[],null],FPDF_DeviceToPage:[["number","number","number","number","number","number","number","number","number","number"],"boolean"],FPDF_DocumentHasValidCrossReferenceTable:[["number"],"boolean"],FPDF_FFLDraw:[["number","number","number","number","number","number","number","number","number"],null],FPDF_FreeDefaultSystemFontInfo:[["number"],null],FPDF_GetDefaultSystemFontInfo:[[],"number"],FPDF_GetDefaultTTFMap:[[],"number"],FPDF_GetDefaultTTFMapCount:[[],"number"],FPDF_GetDefaultTTFMapEntry:[["number"],"number"],FPDF_GetDocPermissions:[["number"],"number"],FPDF_GetDocUserPermissions:[["number"],"number"],FPDF_GetFileIdentifier:[["number","number","number","number"],"number"],FPDF_GetFileVersion:[["number","number"],"boolean"],FPDF_GetFormType:[["number"],"number"],FPDF_GetLastError:[[],"number"],FPDF_GetMetaText:[["number","string","number","number"],"number"],FPDF_GetNamedDest:[["number","number","number","number"],"number"],FPDF_GetNamedDestByName:[["number","string"],"number"],FPDF_GetPageAAction:[["number","number"],"number"],FPDF_GetPageBoundingBox:[["number","number"],"boolean"],FPDF_GetPageCount:[["number"],"number"],FPDF_GetPageHeight:[["number"],"number"],FPDF_GetPageHeightF:[["number"],"number"],FPDF_GetPageLabel:[["number","number","number","number"],"number"],FPDF_GetPageSizeByIndex:[["number","number","number","number"],"number"],FPDF_GetPageSizeByIndexF:[["number","number","number"],"boolean"],FPDF_GetPageWidth:[["number"],"number"],FPDF_GetPageWidthF:[["number"],"number"],FPDF_GetSecurityHandlerRevision:[["number"],"number"],FPDF_GetSignatureCount:[["number"],"number"],FPDF_GetSignatureObject:[["number","number"],"number"],FPDF_GetTrailerEnds:[["number","number","number"],"number"],FPDF_GetXFAPacketContent:[["number","number","number","number","number"],"boolean"],FPDF_GetXFAPacketCount:[["number"],"number"],FPDF_GetXFAPacketName:[["number","number","number","number"],"number"],FPDF_ImportNPagesToOne:[["number","number","number","number","number"],"number"],FPDF_ImportPages:[["number","number","string","number"],"boolean"],FPDF_ImportPagesByIndex:[["number","number","number","number","number"],"boolean"],FPDF_InitLibrary:[[],null],FPDF_InitLibraryWithConfig:[["number"],null],FPDF_LoadCustomDocument:[["number","string"],"number"],FPDF_LoadDocument:[["number","string"],"number"],FPDF_LoadMemDocument:[["number","number","string"],"number"],FPDF_LoadMemDocument64:[["number","number","string"],"number"],FPDF_LoadPage:[["number","number"],"number"],FPDF_LoadXFA:[["number"],"boolean"],FPDF_MovePages:[["number","number","number","number"],"boolean"],FPDF_NewFormObjectFromXObject:[["number"],"number"],FPDF_NewXObjectFromPage:[["number","number","number"],"number"],FPDF_PageToDevice:[["number","number","number","number","number","number","number","number","number","number"],"boolean"],FPDF_RemoveFormFieldHighlight:[["number"],null],FPDF_RenderPage_Close:[["number"],null],FPDF_RenderPage_Continue:[["number","number"],"number"],FPDF_RenderPageBitmap:[["number","number","number","number","number","number","number","number"],null],FPDF_RenderPageBitmap_Start:[["number","number","number","number","number","number","number","number","number"],"number"],FPDF_RenderPageBitmapWithColorScheme_Start:[["number","number","number","number","number","number","number","number","number","number"],"number"],FPDF_RenderPageBitmapWithMatrix:[["number","number","number","number","number"],null],FPDF_SaveAsCopy:[["number","number","number"],"boolean"],FPDF_SaveWithVersion:[["number","number","number","number"],"boolean"],FPDF_SetFormFieldHighlightAlpha:[["number","number"],null],FPDF_SetFormFieldHighlightColor:[["number","number","number"],null],FPDF_SetSandBoxPolicy:[["number","boolean"],null],FPDF_SetSystemFontInfo:[["number"],null],FPDF_StructElement_Attr_CountChildren:[["number"],"number"],FPDF_StructElement_Attr_GetBlobValue:[["number","number","number","number"],"boolean"],FPDF_StructElement_Attr_GetBooleanValue:[["number","number"],"boolean"],FPDF_StructElement_Attr_GetChildAtIndex:[["number","number"],"number"],FPDF_StructElement_Attr_GetCount:[["number"],"number"],FPDF_StructElement_Attr_GetName:[["number","number","number","number","number"],"boolean"],FPDF_StructElement_Attr_GetNumberValue:[["number","number"],"boolean"],FPDF_StructElement_Attr_GetStringValue:[["number","number","number","number"],"boolean"],FPDF_StructElement_Attr_GetType:[["number"],"number"],FPDF_StructElement_Attr_GetValue:[["number","string"],"number"],FPDF_StructElement_CountChildren:[["number"],"number"],FPDF_StructElement_GetActualText:[["number","number","number"],"number"],FPDF_StructElement_GetAltText:[["number","number","number"],"number"],FPDF_StructElement_GetAttributeAtIndex:[["number","number"],"number"],FPDF_StructElement_GetAttributeCount:[["number"],"number"],FPDF_StructElement_GetChildAtIndex:[["number","number"],"number"],FPDF_StructElement_GetChildMarkedContentID:[["number","number"],"number"],FPDF_StructElement_GetID:[["number","number","number"],"number"],FPDF_StructElement_GetLang:[["number","number","number"],"number"],FPDF_StructElement_GetMarkedContentID:[["number"],"number"],FPDF_StructElement_GetMarkedContentIdAtIndex:[["number","number"],"number"],FPDF_StructElement_GetMarkedContentIdCount:[["number"],"number"],FPDF_StructElement_GetObjType:[["number","number","number"],"number"],FPDF_StructElement_GetParent:[["number"],"number"],FPDF_StructElement_GetStringAttribute:[["number","string","number","number"],"number"],FPDF_StructElement_GetTitle:[["number","number","number"],"number"],FPDF_StructElement_GetType:[["number","number","number"],"number"],FPDF_StructTree_Close:[["number"],null],FPDF_StructTree_CountChildren:[["number"],"number"],FPDF_StructTree_GetChildAtIndex:[["number","number"],"number"],FPDF_StructTree_GetForPage:[["number"],"number"],FPDF_VIEWERREF_GetDuplex:[["number"],"number"],FPDF_VIEWERREF_GetName:[["number","string","number","number"],"number"],FPDF_VIEWERREF_GetNumCopies:[["number"],"number"],FPDF_VIEWERREF_GetPrintPageRange:[["number"],"number"],FPDF_VIEWERREF_GetPrintPageRangeCount:[["number"],"number"],FPDF_VIEWERREF_GetPrintPageRangeElement:[["number","number"],"number"],FPDF_VIEWERREF_GetPrintScaling:[["number"],"boolean"],FPDFAction_GetDest:[["number","number"],"number"],FPDFAction_GetFilePath:[["number","number","number"],"number"],FPDFAction_GetType:[["number"],"number"],FPDFAction_GetURIPath:[["number","number","number","number"],"number"],FPDFAnnot_AddFileAttachment:[["number","number"],"number"],FPDFAnnot_AddInkStroke:[["number","number","number"],"number"],FPDFAnnot_AppendAttachmentPoints:[["number","number"],"boolean"],FPDFAnnot_AppendObject:[["number","number"],"boolean"],FPDFAnnot_CountAttachmentPoints:[["number"],"number"],FPDFAnnot_GetAP:[["number","number","number","number"],"number"],FPDFAnnot_GetAttachmentPoints:[["number","number","number"],"boolean"],FPDFAnnot_GetBorder:[["number","number","number","number"],"boolean"],FPDFAnnot_GetColor:[["number","number","number","number","number","number"],"boolean"],FPDFAnnot_GetFileAttachment:[["number"],"number"],FPDFAnnot_GetFlags:[["number"],"number"],FPDFAnnot_GetFocusableSubtypes:[["number","number","number"],"boolean"],FPDFAnnot_GetFocusableSubtypesCount:[["number"],"number"],FPDFAnnot_GetFontColor:[["number","number","number","number","number"],"boolean"],FPDFAnnot_GetFontSize:[["number","number","number"],"boolean"],FPDFAnnot_GetFormAdditionalActionJavaScript:[["number","number","number","number","number"],"number"],FPDFAnnot_GetFormControlCount:[["number","number"],"number"],FPDFAnnot_GetFormControlIndex:[["number","number"],"number"],FPDFAnnot_GetFormFieldAlternateName:[["number","number","number","number"],"number"],FPDFAnnot_GetFormFieldAtPoint:[["number","number","number"],"number"],FPDFAnnot_GetFormFieldExportValue:[["number","number","number","number"],"number"],FPDFAnnot_GetFormFieldFlags:[["number","number"],"number"],FPDFAnnot_GetFormFieldName:[["number","number","number","number"],"number"],FPDFAnnot_GetFormFieldType:[["number","number"],"number"],FPDFAnnot_GetFormFieldValue:[["number","number","number","number"],"number"],FPDFAnnot_GetInkListCount:[["number"],"number"],FPDFAnnot_GetInkListPath:[["number","number","number","number"],"number"],FPDFAnnot_GetLine:[["number","number","number"],"boolean"],FPDFAnnot_GetLink:[["number"],"number"],FPDFAnnot_GetLinkedAnnot:[["number","string"],"number"],FPDFAnnot_GetNumberValue:[["number","string","number"],"boolean"],FPDFAnnot_GetObject:[["number","number"],"number"],FPDFAnnot_GetObjectCount:[["number"],"number"],FPDFAnnot_GetOptionCount:[["number","number"],"number"],FPDFAnnot_GetOptionLabel:[["number","number","number","number","number"],"number"],FPDFAnnot_GetRect:[["number","number"],"boolean"],FPDFAnnot_GetStringValue:[["number","string","number","number"],"number"],FPDFAnnot_GetSubtype:[["number"],"number"],FPDFAnnot_GetValueType:[["number","string"],"number"],FPDFAnnot_GetVertices:[["number","number","number"],"number"],FPDFAnnot_HasAttachmentPoints:[["number"],"boolean"],FPDFAnnot_HasKey:[["number","string"],"boolean"],FPDFAnnot_IsChecked:[["number","number"],"boolean"],FPDFAnnot_IsObjectSupportedSubtype:[["number"],"boolean"],FPDFAnnot_IsOptionSelected:[["number","number","number"],"boolean"],FPDFAnnot_IsSupportedSubtype:[["number"],"boolean"],FPDFAnnot_RemoveInkList:[["number"],"boolean"],FPDFAnnot_RemoveObject:[["number","number"],"boolean"],FPDFAnnot_SetAP:[["number","number","number"],"boolean"],FPDFAnnot_SetAttachmentPoints:[["number","number","number"],"boolean"],FPDFAnnot_SetBorder:[["number","number","number","number"],"boolean"],FPDFAnnot_SetColor:[["number","number","number","number","number","number"],"boolean"],FPDFAnnot_SetFlags:[["number","number"],"boolean"],FPDFAnnot_SetFocusableSubtypes:[["number","number","number"],"boolean"],FPDFAnnot_SetFontColor:[["number","number","number","number","number"],"boolean"],FPDFAnnot_SetFormFieldFlags:[["number","number","number"],"boolean"],FPDFAnnot_SetRect:[["number","number"],"boolean"],FPDFAnnot_SetStringValue:[["number","string","number"],"boolean"],FPDFAnnot_SetURI:[["number","number"],"boolean"],FPDFAnnot_UpdateObject:[["number","number"],"boolean"],FPDFAttachment_GetFile:[["number","number","number","number"],"boolean"],FPDFAttachment_GetName:[["number","number","number"],"number"],FPDFAttachment_GetStringValue:[["number","string","number","number"],"number"],FPDFAttachment_GetSubtype:[["number","number","number"],"number"],FPDFAttachment_GetValueType:[["number","string"],"number"],FPDFAttachment_HasKey:[["number","string"],"boolean"],FPDFAttachment_SetFile:[["number","number","number","number"],"boolean"],FPDFAttachment_SetStringValue:[["number","string","number"],"boolean"],FPDFAvail_Create:[["number","number"],"number"],FPDFAvail_Destroy:[["number"],null],FPDFAvail_GetDocument:[["number","string"],"number"],FPDFAvail_GetFirstPageNum:[["number"],"number"],FPDFAvail_IsDocAvail:[["number","number"],"number"],FPDFAvail_IsFormAvail:[["number","number"],"number"],FPDFAvail_IsLinearized:[["number"],"number"],FPDFAvail_IsPageAvail:[["number","number","number"],"number"],FPDFBitmap_Create:[["number","number","number"],"number"],FPDFBitmap_CreateEx:[["number","number","number","number","number"],"number"],FPDFBitmap_Destroy:[["number"],null],FPDFBitmap_FillRect:[["number","number","number","number","number","number"],"boolean"],FPDFBitmap_GetBuffer:[["number"],"number"],FPDFBitmap_GetFormat:[["number"],"number"],FPDFBitmap_GetHeight:[["number"],"number"],FPDFBitmap_GetStride:[["number"],"number"],FPDFBitmap_GetWidth:[["number"],"number"],FPDFBookmark_Find:[["number","number"],"number"],FPDFBookmark_GetAction:[["number"],"number"],FPDFBookmark_GetCount:[["number"],"number"],FPDFBookmark_GetDest:[["number","number"],"number"],FPDFBookmark_GetFirstChild:[["number","number"],"number"],FPDFBookmark_GetNextSibling:[["number","number"],"number"],FPDFBookmark_GetTitle:[["number","number","number"],"number"],FPDFCatalog_GetLanguage:[["number","number","number"],"number"],FPDFCatalog_IsTagged:[["number"],"boolean"],FPDFCatalog_SetLanguage:[["number","number"],"boolean"],FPDFClipPath_CountPaths:[["number"],"number"],FPDFClipPath_CountPathSegments:[["number","number"],"number"],FPDFClipPath_GetPathSegment:[["number","number","number"],"number"],FPDFDest_GetDestPageIndex:[["number","number"],"number"],FPDFDest_GetLocationInPage:[["number","number","number","number","number","number","number"],"boolean"],FPDFDest_GetView:[["number","number","number"],"number"],FPDFDoc_AddAttachment:[["number","number"],"number"],FPDFDoc_CloseJavaScriptAction:[["number"],null],FPDFDoc_DeleteAttachment:[["number","number"],"boolean"],FPDFDOC_ExitFormFillEnvironment:[["number"],null],FPDFDoc_GetAttachment:[["number","number"],"number"],FPDFDoc_GetAttachmentCount:[["number"],"number"],FPDFDoc_GetJavaScriptAction:[["number","number"],"number"],FPDFDoc_GetJavaScriptActionCount:[["number"],"number"],FPDFDoc_GetPageMode:[["number"],"number"],FPDFDOC_InitFormFillEnvironment:[["number","number"],"number"],FPDFFont_Close:[["number"],null],FPDFFont_GetAscent:[["number","number","number"],"boolean"],FPDFFont_GetBaseFontName:[["number","number","number"],"number"],FPDFFont_GetDescent:[["number","number","number"],"boolean"],FPDFFont_GetFamilyName:[["number","number","number"],"number"],FPDFFont_GetFlags:[["number"],"number"],FPDFFont_GetFontData:[["number","number","number","number"],"boolean"],FPDFFont_GetGlyphPath:[["number","number","number"],"number"],FPDFFont_GetGlyphWidth:[["number","number","number","number"],"boolean"],FPDFFont_GetIsEmbedded:[["number"],"number"],FPDFFont_GetItalicAngle:[["number","number"],"boolean"],FPDFFont_GetWeight:[["number"],"number"],FPDFFormObj_CountObjects:[["number"],"number"],FPDFFormObj_GetObject:[["number","number"],"number"],FPDFFormObj_RemoveObject:[["number","number"],"boolean"],FPDFGlyphPath_CountGlyphSegments:[["number"],"number"],FPDFGlyphPath_GetGlyphPathSegment:[["number","number"],"number"],FPDFImageObj_GetBitmap:[["number"],"number"],FPDFImageObj_GetIccProfileDataDecoded:[["number","number","number","number","number"],"boolean"],FPDFImageObj_GetImageDataDecoded:[["number","number","number"],"number"],FPDFImageObj_GetImageDataRaw:[["number","number","number"],"number"],FPDFImageObj_GetImageFilter:[["number","number","number","number"],"number"],FPDFImageObj_GetImageFilterCount:[["number"],"number"],FPDFImageObj_GetImageMetadata:[["number","number","number"],"boolean"],FPDFImageObj_GetImagePixelSize:[["number","number","number"],"boolean"],FPDFImageObj_GetRenderedBitmap:[["number","number","number"],"number"],FPDFImageObj_LoadJpegFile:[["number","number","number","number"],"boolean"],FPDFImageObj_LoadJpegFileInline:[["number","number","number","number"],"boolean"],FPDFImageObj_SetBitmap:[["number","number","number","number"],"boolean"],FPDFImageObj_SetMatrix:[["number","number","number","number","number","number","number"],"boolean"],FPDFJavaScriptAction_GetName:[["number","number","number"],"number"],FPDFJavaScriptAction_GetScript:[["number","number","number"],"number"],FPDFLink_CloseWebLinks:[["number"],null],FPDFLink_CountQuadPoints:[["number"],"number"],FPDFLink_CountRects:[["number","number"],"number"],FPDFLink_CountWebLinks:[["number"],"number"],FPDFLink_Enumerate:[["number","number","number"],"boolean"],FPDFLink_GetAction:[["number"],"number"],FPDFLink_GetAnnot:[["number","number"],"number"],FPDFLink_GetAnnotRect:[["number","number"],"boolean"],FPDFLink_GetDest:[["number","number"],"number"],FPDFLink_GetLinkAtPoint:[["number","number","number"],"number"],FPDFLink_GetLinkZOrderAtPoint:[["number","number","number"],"number"],FPDFLink_GetQuadPoints:[["number","number","number"],"boolean"],FPDFLink_GetRect:[["number","number","number","number","number","number","number"],"boolean"],FPDFLink_GetTextRange:[["number","number","number","number"],"boolean"],FPDFLink_GetURL:[["number","number","number","number"],"number"],FPDFLink_LoadWebLinks:[["number"],"number"],FPDFPage_CloseAnnot:[["number"],null],FPDFPage_CountObjects:[["number"],"number"],FPDFPage_CreateAnnot:[["number","number"],"number"],FPDFPage_Delete:[["number","number"],null],FPDFPage_Flatten:[["number","number"],"number"],FPDFPage_FormFieldZOrderAtPoint:[["number","number","number","number"],"number"],FPDFPage_GenerateContent:[["number"],"boolean"],FPDFPage_GetAnnot:[["number","number"],"number"],FPDFPage_GetAnnotCount:[["number"],"number"],FPDFPage_GetAnnotIndex:[["number","number"],"number"],FPDFPage_GetArtBox:[["number","number","number","number","number"],"boolean"],FPDFPage_GetBleedBox:[["number","number","number","number","number"],"boolean"],FPDFPage_GetCropBox:[["number","number","number","number","number"],"boolean"],FPDFPage_GetDecodedThumbnailData:[["number","number","number"],"number"],FPDFPage_GetMediaBox:[["number","number","number","number","number"],"boolean"],FPDFPage_GetObject:[["number","number"],"number"],FPDFPage_GetRawThumbnailData:[["number","number","number"],"number"],FPDFPage_GetRotation:[["number"],"number"],FPDFPage_GetThumbnailAsBitmap:[["number"],"number"],FPDFPage_GetTrimBox:[["number","number","number","number","number"],"boolean"],FPDFPage_HasFormFieldAtPoint:[["number","number","number","number"],"number"],FPDFPage_HasTransparency:[["number"],"boolean"],FPDFPage_InsertClipPath:[["number","number"],null],FPDFPage_InsertObject:[["number","number"],null],FPDFPage_InsertObjectAtIndex:[["number","number","number"],"boolean"],FPDFPage_New:[["number","number","number","number"],"number"],FPDFPage_RemoveAnnot:[["number","number"],"boolean"],FPDFPage_RemoveObject:[["number","number"],"boolean"],FPDFPage_SetArtBox:[["number","number","number","number","number"],null],FPDFPage_SetBleedBox:[["number","number","number","number","number"],null],FPDFPage_SetCropBox:[["number","number","number","number","number"],null],FPDFPage_SetMediaBox:[["number","number","number","number","number"],null],FPDFPage_SetRotation:[["number","number"],null],FPDFPage_SetTrimBox:[["number","number","number","number","number"],null],FPDFPage_TransformAnnots:[["number","number","number","number","number","number","number"],null],FPDFPage_TransFormWithClip:[["number","number","number"],"boolean"],FPDFPageObj_AddMark:[["number","string"],"number"],FPDFPageObj_CountMarks:[["number"],"number"],FPDFPageObj_CreateNewPath:[["number","number"],"number"],FPDFPageObj_CreateNewRect:[["number","number","number","number"],"number"],FPDFPageObj_CreateTextObj:[["number","number","number"],"number"],FPDFPageObj_Destroy:[["number"],null],FPDFPageObj_GetBounds:[["number","number","number","number","number"],"boolean"],FPDFPageObj_GetClipPath:[["number"],"number"],FPDFPageObj_GetDashArray:[["number","number","number"],"boolean"],FPDFPageObj_GetDashCount:[["number"],"number"],FPDFPageObj_GetDashPhase:[["number","number"],"boolean"],FPDFPageObj_GetFillColor:[["number","number","number","number","number"],"boolean"],FPDFPageObj_GetIsActive:[["number","number"],"boolean"],FPDFPageObj_GetLineCap:[["number"],"number"],FPDFPageObj_GetLineJoin:[["number"],"number"],FPDFPageObj_GetMark:[["number","number"],"number"],FPDFPageObj_GetMarkedContentID:[["number"],"number"],FPDFPageObj_GetMatrix:[["number","number"],"boolean"],FPDFPageObj_GetRotatedBounds:[["number","number"],"boolean"],FPDFPageObj_GetStrokeColor:[["number","number","number","number","number"],"boolean"],FPDFPageObj_GetStrokeWidth:[["number","number"],"boolean"],FPDFPageObj_GetType:[["number"],"number"],FPDFPageObj_HasTransparency:[["number"],"boolean"],FPDFPageObj_NewImageObj:[["number"],"number"],FPDFPageObj_NewTextObj:[["number","string","number"],"number"],FPDFPageObj_RemoveMark:[["number","number"],"boolean"],FPDFPageObj_SetBlendMode:[["number","string"],null],FPDFPageObj_SetDashArray:[["number","number","number","number"],"boolean"],FPDFPageObj_SetDashPhase:[["number","number"],"boolean"],FPDFPageObj_SetFillColor:[["number","number","number","number","number"],"boolean"],FPDFPageObj_SetIsActive:[["number","boolean"],"boolean"],FPDFPageObj_SetLineCap:[["number","number"],"boolean"],FPDFPageObj_SetLineJoin:[["number","number"],"boolean"],FPDFPageObj_SetMatrix:[["number","number"],"boolean"],FPDFPageObj_SetStrokeColor:[["number","number","number","number","number"],"boolean"],FPDFPageObj_SetStrokeWidth:[["number","number"],"boolean"],FPDFPageObj_Transform:[["number","number","number","number","number","number","number"],null],FPDFPageObj_TransformClipPath:[["number","number","number","number","number","number","number"],null],FPDFPageObj_TransformF:[["number","number"],"boolean"],FPDFPageObjMark_CountParams:[["number"],"number"],FPDFPageObjMark_GetName:[["number","number","number","number"],"boolean"],FPDFPageObjMark_GetParamBlobValue:[["number","string","number","number","number"],"boolean"],FPDFPageObjMark_GetParamFloatValue:[["number","string","number"],"boolean"],FPDFPageObjMark_GetParamIntValue:[["number","string","number"],"boolean"],FPDFPageObjMark_GetParamKey:[["number","number","number","number","number"],"boolean"],FPDFPageObjMark_GetParamStringValue:[["number","string","number","number","number"],"boolean"],FPDFPageObjMark_GetParamValueType:[["number","string"],"number"],FPDFPageObjMark_RemoveParam:[["number","number","string"],"boolean"],FPDFPageObjMark_SetBlobParam:[["number","number","number","string","number","number"],"boolean"],FPDFPageObjMark_SetFloatParam:[["number","number","number","string","number"],"boolean"],FPDFPageObjMark_SetIntParam:[["number","number","number","string","number"],"boolean"],FPDFPageObjMark_SetStringParam:[["number","number","number","string","string"],"boolean"],FPDFPath_BezierTo:[["number","number","number","number","number","number","number"],"boolean"],FPDFPath_Close:[["number"],"boolean"],FPDFPath_CountSegments:[["number"],"number"],FPDFPath_GetDrawMode:[["number","number","number"],"boolean"],FPDFPath_GetPathSegment:[["number","number"],"number"],FPDFPath_LineTo:[["number","number","number"],"boolean"],FPDFPath_MoveTo:[["number","number","number"],"boolean"],FPDFPath_SetDrawMode:[["number","number","boolean"],"boolean"],FPDFPathSegment_GetClose:[["number"],"boolean"],FPDFPathSegment_GetPoint:[["number","number","number"],"boolean"],FPDFPathSegment_GetType:[["number"],"number"],FPDFSignatureObj_GetByteRange:[["number","number","number"],"number"],FPDFSignatureObj_GetContents:[["number","number","number"],"number"],FPDFSignatureObj_GetDocMDPPermission:[["number"],"number"],FPDFSignatureObj_GetReason:[["number","number","number"],"number"],FPDFSignatureObj_GetSubFilter:[["number","number","number"],"number"],FPDFSignatureObj_GetTime:[["number","number","number"],"number"],FPDFText_ClosePage:[["number"],null],FPDFText_CountChars:[["number"],"number"],FPDFText_CountRects:[["number","number","number"],"number"],FPDFText_FindClose:[["number"],null],FPDFText_FindNext:[["number"],"boolean"],FPDFText_FindPrev:[["number"],"boolean"],FPDFText_FindStart:[["number","number","number","number"],"number"],FPDFText_GetBoundedText:[["number","number","number","number","number","number","number"],"number"],FPDFText_GetCharAngle:[["number","number"],"number"],FPDFText_GetCharBox:[["number","number","number","number","number","number"],"boolean"],FPDFText_GetCharIndexAtPos:[["number","number","number","number","number"],"number"],FPDFText_GetCharIndexFromTextIndex:[["number","number"],"number"],FPDFText_GetCharOrigin:[["number","number","number","number"],"boolean"],FPDFText_GetFillColor:[["number","number","number","number","number","number"],"boolean"],FPDFText_GetFontInfo:[["number","number","number","number","number"],"number"],FPDFText_GetFontSize:[["number","number"],"number"],FPDFText_GetFontWeight:[["number","number"],"number"],FPDFText_GetLooseCharBox:[["number","number","number"],"boolean"],FPDFText_GetMatrix:[["number","number","number"],"boolean"],FPDFText_GetRect:[["number","number","number","number","number","number"],"boolean"],FPDFText_GetSchCount:[["number"],"number"],FPDFText_GetSchResultIndex:[["number"],"number"],FPDFText_GetStrokeColor:[["number","number","number","number","number","number"],"boolean"],FPDFText_GetText:[["number","number","number","number"],"number"],FPDFText_GetTextIndexFromCharIndex:[["number","number"],"number"],FPDFText_GetTextObject:[["number","number"],"number"],FPDFText_GetUnicode:[["number","number"],"number"],FPDFText_HasUnicodeMapError:[["number","number"],"number"],FPDFText_IsGenerated:[["number","number"],"number"],FPDFText_IsHyphen:[["number","number"],"number"],FPDFText_LoadCidType2Font:[["number","number","number","string","number","number"],"number"],FPDFText_LoadFont:[["number","number","number","number","boolean"],"number"],FPDFText_LoadPage:[["number"],"number"],FPDFText_LoadStandardFont:[["number","string"],"number"],FPDFText_SetCharcodes:[["number","number","number"],"boolean"],FPDFText_SetText:[["number","number"],"boolean"],FPDFTextObj_GetFont:[["number"],"number"],FPDFTextObj_GetFontSize:[["number","number"],"boolean"],FPDFTextObj_GetRenderedBitmap:[["number","number","number","number"],"number"],FPDFTextObj_GetText:[["number","number","number","number"],"number"],FPDFTextObj_GetTextRenderMode:[["number"],"number"],FPDFTextObj_SetTextRenderMode:[["number","number"],"boolean"],PDFiumExt_CloseFileWriter:[["number"],null],PDFiumExt_CloseFormFillInfo:[["number"],null],PDFiumExt_ExitFormFillEnvironment:[["number"],null],PDFiumExt_GetFileWriterData:[["number","number","number"],"number"],PDFiumExt_GetFileWriterSize:[["number"],"number"],PDFiumExt_Init:[[],null],PDFiumExt_InitFormFillEnvironment:[["number","number"],"number"],PDFiumExt_OpenFileWriter:[[],"number"],PDFiumExt_OpenFormFillInfo:[[],"number"],PDFiumExt_SaveAsCopy:[["number","number"],"number"]};async function $(e){return async function(e){const t={pdfium:e};for(const n in z){const r=n,o=z[r][0],a=z[r][1];t[r]=e.cwrap(n,a,o)}return t}(await U(e))}function W(e,t,n,r=100){let o=e.wasmExports.malloc(r);for(let t=0;tr){e.wasmExports.free(o),o=e.wasmExports.malloc(a);for(let t=0;t127)return!1;if(Y.has(e))return!1;if("/"===e[0])return!1;for(let t=0;t126)return!1}return!0}const K={pageTtl:5e3,maxPagesPerDocument:10,normalizeRotation:!1};class J{constructor(e,t,n={}){this.pdfium=e,this.memoryManager=t,this.docs=new Map,this.config={...K,...n}}setDocument(e,t,n,r=!1){let o=this.docs.get(e);if(!o){const a={...this.config,normalizeRotation:r};o=new q(t,n,this.pdfium,this.memoryManager,a),this.docs.set(e,o)}}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 e of this.docs.values())e.updateConfig(this.config)}getCacheStats(){const e={};let t=0;for(const[n,r]of this.docs.entries()){const o=r.getCacheSize();e[n]=o,t+=o}return{documents:this.docs.size,totalPages:t,pagesByDocument:e}}}class q{constructor(e,t,n,r,o){this.filePtr=e,this.docPtr=t,this.memoryManager=r,this.normalizeRotation=o.normalizeRotation,this.pageCache=new Q(n,t,o)}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 Q{constructor(e,t,n){this.pdf=e,this.docPtr=t,this.cache=new Map,this.accessOrder=[],this.config=n}acquire(e){let t=this.cache.get(e);if(!t){let n;this.evictIfNeeded(),n=this.config.normalizeRotation?this.pdf.EPDF_LoadPageNormalized(this.docPtr,e,0):this.pdf.FPDF_LoadPage(this.docPtr,e),t=new Z(this.pdf,this.docPtr,e,n,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 n=this.cache.has(e),r=this.acquire(e);try{return t(r)}finally{n?r.release():r.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 Z{constructor(e,t,n,r,o,a){this.pdf=e,this.docPtr=t,this.pageIdx=n,this.pagePtr=r,this.onFinalDispose=a,this.refCount=0,this.disposed=!1,this.ttl=o}bumpRefCount(){if(this.disposed)throw new Error("Context already disposed");this.refCount++}getRefCount(){return this.refCount}clearExpiryTimer(){this.expiryTimer&&(clearTimeout(this.expiryTimer),this.expiryTimer=void 0)}updateTtl(e){this.ttl=e,this.expiryTimer&&0===this.refCount&&(this.clearExpiryTimer(),this.expiryTimer=setTimeout(()=>this.disposeImmediate(),this.ttl))}release(){this.disposed||(this.refCount--,0===this.refCount&&(this.expiryTimer=setTimeout(()=>this.disposeImmediate(),this.ttl)))}disposeImmediate(){this.disposed||(this.disposed=!0,this.clearExpiryTimer(),void 0!==this.textPagePtr&&this.pdf.FPDFText_ClosePage(this.textPagePtr),void 0!==this.formHandle&&(this.pdf.FORM_OnBeforeClosePage(this.pagePtr,this.formHandle),this.pdf.PDFiumExt_ExitFormFillEnvironment(this.formHandle)),void 0!==this.formInfoPtr&&this.pdf.PDFiumExt_CloseFormFillInfo(this.formInfoPtr),this.pdf.FPDF_ClosePage(this.pagePtr),this.onFinalDispose())}getTextPage(){return this.ensureAlive(),void 0===this.textPagePtr&&(this.textPagePtr=this.pdf.FPDFText_LoadPage(this.pagePtr)),this.textPagePtr}getFormHandle(){return this.ensureAlive(),void 0===this.formHandle&&(this.formInfoPtr=this.pdf.PDFiumExt_OpenFormFillInfo(),this.formHandle=this.pdf.PDFiumExt_InitFormFillEnvironment(this.docPtr,this.formInfoPtr),this.pdf.FORM_OnAfterLoadPage(this.pagePtr,this.formHandle)),this.formHandle}withAnnotation(e,t){this.ensureAlive();const n=this.pdf.FPDFPage_GetAnnot(this.pagePtr,e);try{return t(n)}finally{this.pdf.FPDFPage_CloseAnnot(n)}}ensureAlive(){if(this.disposed)throw new Error("PageContext already disposed")}}const ee={MAX_TOTAL_MEMORY:2147483648},te="PDFiumEngine",ne="MemoryManager";class re{constructor(e,t){this.pdfiumModule=e,this.logger=t,this.allocations=new Map,this.totalAllocated=0}malloc(e){if(this.totalAllocated+e>ee.MAX_TOTAL_MEMORY)throw new Error(`Total memory usage would exceed limit: ${this.totalAllocated+e} > ${ee.MAX_TOTAL_MEMORY}`);const t=this.pdfiumModule.pdfium.wasmExports.malloc(e);if(!t)throw new Error(`Failed to allocate ${e} bytes`);const n={ptr:t,size:e,timestamp:Date.now(),stack:this.logger.isEnabled("debug")?(new Error).stack:void 0};return this.allocations.set(t,n),this.totalAllocated+=e,t}free(e){const t=this.allocations.get(e);t?(this.totalAllocated-=t.size,this.allocations.delete(e)):this.logger.warn(te,ne,`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(te,ne,`Potential memory leak: ${this.allocations.size} unfreed allocations`);for(const[e,t]of this.allocations)this.logger.warn(te,ne,` - ${e}: ${t.size} bytes`,t.stack)}}}const oe="pdfium",ae="font-fallback";class ie{constructor(t,n=new e){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=t,this.logger=n}initialize(e){if(this.enabled)return void this.logger.warn(oe,ae,"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,n,r,o,a,i,s)=>{const u=i?t.UTF8ToString(i):"",m=this.mapFont(n,r,o,a,u);return s&&t.setValue(s,0,"i32"),m},"iiiiiiii"),this.getFontFnPtr=t.addFunction((e,n)=>{const r=n?t.UTF8ToString(n):"";return this.mapFont(400,0,0,0,r)},"iii"),this.getFontDataFnPtr=t.addFunction((e,t,n,r,o)=>this.getFontData(t,n,r,o),"iiiiii"),this.getFaceNameFnPtr=t.addFunction((e,t,n,r)=>0,"iiiii"),this.getFontCharsetFnPtr=t.addFunction((e,t)=>{const n=this.fontHandles.get(t);return(null==n?void 0:n.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(oe,ae,"Font fallback system initialized (pure TypeScript)",Object.keys(this.fontConfig.fonts))}catch(e){throw this.logger.error(oe,ae,"Failed to initialize font fallback",e),this.cleanup(),e}else this.logger.error(oe,ae,"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(oe,ae,"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),n=[...new Set(t)];await Promise.all(n.map(async e=>{if(!this.fontCache.has(e))try{const t=await this.fetchFontAsync(e);t&&(this.fontCache.set(e,t),this.logger.debug(oe,ae,`Pre-loaded font: ${e}`))}catch(t){this.logger.warn(oe,ae,`Failed to pre-load font: ${e}`,t)}}))}mapFont(e,t,n,r,o){const a=0!==t;this.logger.debug(oe,ae,"MapFont called",{weight:e,italic:a,charset:n,pitchFamily:r,face:o});const i=this.findBestFontMatch(n,e,a);if(!i)return this.logger.debug(oe,ae,`No font configured for charset ${n}`),0;const s={id:this.nextHandleId++,charset:n,weight:e,italic:a,url:i.url,data:null};return this.fontHandles.set(s.id,s),this.logger.debug(oe,ae,`Created font handle ${s.id} for ${i.url} (requested: weight=${e}, italic=${a}, matched: weight=${i.matchedWeight}, italic=${i.matchedItalic})`),s.id}getFontData(e,t,n,r){const o=this.fontHandles.get(e);if(!o)return this.logger.warn(oe,ae,`Unknown font handle: ${e}`),0;if(o.data||(this.fontCache.has(o.url)?o.data=this.fontCache.get(o.url):(o.data=this.fetchFontSync(o.url),o.data&&this.fontCache.set(o.url,o.data))),!o.data)return this.logger.warn(oe,ae,`Failed to load font: ${o.url}`),0;const a=o.data;if(0!==t)return this.logger.debug(oe,ae,`Table ${t} requested - returning 0 to request whole file`),0;if(0===n||r({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,n){if(1===e.length)return e[0];const r=e.filter(e=>(e.italic??!1)===n),o=r.length>0?r:e;let a=o[0],i=Math.abs((a.weight??400)-t);for(const e of o){const n=e.weight??400,r=Math.abs(n-t);if(r=500?n>r&&(a=e):n{this.memoryManager.checkLeaks()},1e4)),this.logger.debug(se,ue,"initialize"),this.logger.perf(se,ue,"Initialize","Begin","General"),this.pdfiumModule.PDFiumExt_Init(),this.logger.perf(se,ue,"Initialize","End","General"),o&&(this.fontFallbackManager=new ie(o,this.logger),this.fontFallbackManager.initialize(this.pdfiumModule),this.logger.info(se,ue,"Font fallback system enabled"))}destroy(){return this.logger.debug(se,ue,"destroy"),this.logger.perf(se,ue,"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(se,ue,"Destroy","End","General"),t.resolve(!0)}getFontFallbackManager(){return this.fontFallbackManager}withWString(e,t){const n=2*(e.length+1),r=this.memoryManager.malloc(n);try{return this.pdfiumModule.pdfium.stringToUTF16(e,r,n),t(r)}finally{this.memoryManager.free(r)}}withFloatArray(e,t){const n=e??[],r=4*n.length,o=r?this.memoryManager.malloc(r):0;try{if(r)for(let e=0;e{const n=r[e];if(void 0===n)return;if(null===n)return void(this.setMetaText(o.docPtr,t,null)||(i=!1));const a=p(n);this.setMetaText(o.docPtr,t,a)||(i=!1)};if(s("creationDate","CreationDate"),s("modificationDate","ModDate"),void 0!==r.trapped&&(this.setMetaTrapped(o.docPtr,r.trapped??null)||(i=!1)),void 0!==r.custom)for(const[e,t]of Object.entries(r.custom))X(e)?this.setMetaText(o.docPtr,e,t??null)||(i=!1):this.logger.warn(se,ue,"Invalid custom metadata key skipped",e);return this.logger.perf(se,ue,"SetMetadata","End",e.id),i?t.resolve(!0):t.reject({code:n.Unknown,message:"one or more metadata fields could not be written"})}getDocPermissions(e){this.logger.debug(se,ue,"getDocPermissions",e),this.logger.perf(se,ue,"getDocPermissions","Begin",e.id);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(se,ue,"getDocPermissions","End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});const o=this.pdfiumModule.FPDF_GetDocPermissions(r.docPtr);return t.resolve(o)}getDocUserPermissions(e){this.logger.debug(se,ue,"getDocUserPermissions",e),this.logger.perf(se,ue,"getDocUserPermissions","Begin",e.id);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(se,ue,"getDocUserPermissions","End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});const o=this.pdfiumModule.FPDF_GetDocUserPermissions(r.docPtr);return t.resolve(o)}getSignatures(e){this.logger.debug(se,ue,"getSignatures",e),this.logger.perf(se,ue,"GetSignatures","Begin",e.id);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(se,ue,"GetSignatures","End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});const o=[],a=this.pdfiumModule.FPDF_GetSignatureCount(r.docPtr);for(let e=0;ethis.pdfiumModule.FPDFSignatureObj_GetContents(t,e,n)),a=H(this.pdfiumModule.pdfium,(e,n)=>4*this.pdfiumModule.FPDFSignatureObj_GetByteRange(t,e,n)),i=H(this.pdfiumModule.pdfium,(e,n)=>this.pdfiumModule.FPDFSignatureObj_GetSubFilter(t,e,n)),s=W(this.pdfiumModule.pdfium,(e,n)=>this.pdfiumModule.FPDFSignatureObj_GetReason(t,e,n),this.pdfiumModule.pdfium.UTF16ToString),u=W(this.pdfiumModule.pdfium,(e,n)=>this.pdfiumModule.FPDFSignatureObj_GetTime(t,e,n),this.pdfiumModule.pdfium.UTF8ToString),m=this.pdfiumModule.FPDFSignatureObj_GetDocMDPPermission(t);o.push({contents:n,byteRange:a,subFilter:i,reason:s,time:u,docMDP:m})}return this.logger.perf(se,ue,"GetSignatures","End",e.id),t.resolve(o)}getBookmarks(e){this.logger.debug(se,ue,"getBookmarks",e),this.logger.perf(se,ue,"GetBookmarks","Begin",e.id);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(se,ue,"getBookmarks","End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});const o=this.readPdfBookmarks(r.docPtr,0);return this.logger.perf(se,ue,"GetBookmarks","End",e.id),t.resolve({bookmarks:o})}setBookmarks(e,r){this.logger.debug(se,ue,"setBookmarks",e,r),this.logger.perf(se,ue,"SetBookmarks","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(se,ue,"SetBookmarks","End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});if(!this.pdfiumModule.EPDFBookmark_Clear(o.docPtr))return this.logger.perf(se,ue,"SetBookmarks","End",e.id),t.reject({code:n.Unknown,message:"failed to clear existing bookmarks"});const a=(e,t)=>{var n;for(const r of t){const t=this.withWString(r.title??"",t=>this.pdfiumModule.EPDFBookmark_AppendChild(o.docPtr,e,t));if(!t)return!1;if(r.target){if(!this.applyBookmarkTarget(o.docPtr,t,r.target))return!1}if(null==(n=r.children)?void 0:n.length){if(!a(t,r.children))return!1}}return!0},i=a(0,r);return this.logger.perf(se,ue,"SetBookmarks","End",e.id),i?t.resolve(!0):t.reject({code:n.Unknown,message:"failed to build bookmark tree"})}deleteBookmarks(e){this.logger.debug(se,ue,"deleteBookmarks",e),this.logger.perf(se,ue,"DeleteBookmarks","Begin",e.id);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(se,ue,"DeleteBookmarks","End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});const o=this.pdfiumModule.EPDFBookmark_Clear(r.docPtr);return this.logger.perf(se,ue,"DeleteBookmarks","End",e.id),o?t.resolve(!0):t.reject({code:n.Unknown,message:"failed to clear bookmarks"})}renderPageRaw(e,t,n){this.logger.debug(se,ue,"renderPage",e,t,n),this.logger.perf(se,ue,"RenderPage","Begin",`${e.id}-${t.index}`);const r={origin:{x:0,y:0},size:t.size},o=this.renderRectEncoded(e,t,r,n);return this.logger.perf(se,ue,"RenderPage","End",`${e.id}-${t.index}`),o}renderPageRect(e,t,n,r){this.logger.debug(se,ue,"renderPageRect",e,t,n,r),this.logger.perf(se,ue,"RenderPageRect","Begin",`${e.id}-${t.index}`);const o=this.renderRectEncoded(e,t,n,r);return this.logger.perf(se,ue,"RenderPageRect","End",`${e.id}-${t.index}`),o}getPageAnnotations(e,r){this.logger.debug(se,ue,"getPageAnnotations",e,r),this.logger.perf(se,ue,"GetPageAnnotations","Begin",`${e.id}-${r.index}`);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(se,ue,"GetPageAnnotations","End",`${e.id}-${r.index}`),t.reject({code:n.DocNotOpen,message:"document does not open"});const a=this.readPageAnnotations(e,o,r);return this.logger.perf(se,ue,"GetPageAnnotations","End",`${e.id}-${r.index}`),this.logger.debug(se,ue,"GetPageAnnotations",`${e.id}-${r.index}`,a),t.resolve(a)}createPageAnnotation(e,r,s,u){this.logger.debug(se,ue,"createPageAnnotation",e,r,s),this.logger.perf(se,ue,"CreatePageAnnotation","Begin",`${e.id}-${r.index}`);const m=this.cache.getContext(e.id);if(!m)return this.logger.perf(se,ue,"CreatePageAnnotation","End",`${e.id}-${r.index}`),t.reject({code:n.DocNotOpen,message:"document does not open"});const F=m.acquirePage(r.index),l=this.pdfiumModule.EPDFPage_CreateAnnot(F.pagePtr,s.type);if(!l)return this.logger.perf(se,ue,"CreatePageAnnotation","End",`${e.id}-${r.index}`),F.release(),t.reject({code:n.CantCreateAnnot,message:"can not create annotation with specified type"});if(o(s.id)||(s.id=a()),!this.setAnnotString(l,"NM",s.id))return this.pdfiumModule.FPDFPage_CloseAnnot(l),F.release(),t.reject({code:n.CantSetAnnotString,message:"can not set the name of the annotation"});if(!this.setPageAnnoRect(e,r,l,s.rect))return this.pdfiumModule.FPDFPage_CloseAnnot(l),F.release(),this.logger.perf(se,ue,"CreatePageAnnotation","End",`${e.id}-${r.index}`),t.reject({code:n.CantSetAnnotRect,message:"can not set the rect of the annotation"});const d=this.prepareAnnotationForSave(s);let c=!1;switch(d.type){case i.INK:c=this.addInkStroke(e,r,F.pagePtr,l,d);break;case i.STAMP:c=this.addStampContent(e,m.docPtr,r,F.pagePtr,l,d,null==u?void 0:u.imageData);break;case i.TEXT:c=this.addTextContent(e,r,F.pagePtr,l,d);break;case i.FREETEXT:c=this.addFreeTextContent(e,r,F.pagePtr,l,d);break;case i.LINE:c=this.addLineContent(e,r,F.pagePtr,l,d);break;case i.POLYLINE:case i.POLYGON:c=this.addPolyContent(e,r,F.pagePtr,l,d);break;case i.CIRCLE:case i.SQUARE:c=this.addShapeContent(e,r,F.pagePtr,l,d);break;case i.UNDERLINE:case i.STRIKEOUT:case i.SQUIGGLY:case i.HIGHLIGHT:c=this.addTextMarkupContent(e,r,F.pagePtr,l,d);break;case i.LINK:c=this.addLinkContent(e,r,m.docPtr,F.pagePtr,l,d);break;case i.CARET:c=this.addCaretContent(e,r,F.pagePtr,l,d);break;case i.REDACT:c=this.addRedactContent(e,r,F.pagePtr,l,d)}return c?(void 0!==s.blendMode?this.pdfiumModule.EPDFAnnot_GenerateAppearanceWithBlend(l,s.blendMode):this.pdfiumModule.EPDFAnnot_GenerateAppearance(l),this.pdfiumModule.FPDFPage_GenerateContent(F.pagePtr),this.pdfiumModule.FPDFPage_CloseAnnot(l),F.release(),this.logger.perf(se,ue,"CreatePageAnnotation","End",`${e.id}-${r.index}`),t.resolve(s.id)):(this.pdfiumModule.FPDFPage_RemoveAnnot(F.pagePtr,l),F.release(),this.logger.perf(se,ue,"CreatePageAnnotation","End",`${e.id}-${r.index}`),t.reject({code:n.CantSetAnnotContent,message:"can not add content of the annotation"}))}updatePageAnnotation(e,r,o,a){this.logger.debug(se,ue,"updatePageAnnotation",e,r,o),this.logger.perf(se,ue,"UpdatePageAnnotation","Begin",`${e.id}-${r.index}`);const s=this.cache.getContext(e.id);if(!s)return this.logger.perf(se,ue,"UpdatePageAnnotation","End",`${e.id}-${r.index}`),t.reject({code:n.DocNotOpen,message:"document does not open"});const u=s.acquirePage(r.index),m=this.getAnnotationByName(u.pagePtr,o.id);if(!m)return u.release(),this.logger.perf(se,ue,"UpdatePageAnnotation","End",`${e.id}-${r.index}`),t.reject({code:n.NotFound,message:"annotation not found"});if(!this.setPageAnnoRect(e,r,m,o.rect))return this.pdfiumModule.FPDFPage_CloseAnnot(m),u.release(),this.logger.perf(se,ue,"UpdatePageAnnotation","End",`${e.id}-${r.index}`),t.reject({code:n.CantSetAnnotRect,message:"failed to move annotation"});const F=this.prepareAnnotationForSave(o);let l=!1;switch(F.type){case i.INK:if(!this.pdfiumModule.FPDFAnnot_RemoveInkList(m))break;l=this.addInkStroke(e,r,u.pagePtr,m,F);break;case i.STAMP:l=this.addStampContent(e,s.docPtr,r,u.pagePtr,m,F);break;case i.TEXT:l=this.addTextContent(e,r,u.pagePtr,m,F);break;case i.FREETEXT:l=this.addFreeTextContent(e,r,u.pagePtr,m,F);break;case i.CIRCLE:case i.SQUARE:l=this.addShapeContent(e,r,u.pagePtr,m,F);break;case i.LINE:l=this.addLineContent(e,r,u.pagePtr,m,F);break;case i.POLYGON:case i.POLYLINE:l=this.addPolyContent(e,r,u.pagePtr,m,F);break;case i.HIGHLIGHT:case i.UNDERLINE:case i.STRIKEOUT:case i.SQUIGGLY:l=this.addTextMarkupContent(e,r,u.pagePtr,m,F);break;case i.LINK:l=this.addLinkContent(e,r,s.docPtr,u.pagePtr,m,F);break;case i.CARET:l=this.addCaretContent(e,r,u.pagePtr,m,F);break;case i.REDACT:l=this.addRedactContent(e,r,u.pagePtr,m,F);break;default:l=!1}return l&&!1!==(null==a?void 0:a.regenerateAppearance)&&(void 0!==o.blendMode?this.pdfiumModule.EPDFAnnot_GenerateAppearanceWithBlend(m,o.blendMode):this.pdfiumModule.EPDFAnnot_GenerateAppearance(m),this.pdfiumModule.FPDFPage_GenerateContent(u.pagePtr)),this.pdfiumModule.FPDFPage_CloseAnnot(m),u.release(),this.logger.perf(se,ue,"UpdatePageAnnotation","End",`${e.id}-${r.index}`),l?t.resolve(!0):t.reject({code:n.CantSetAnnotContent,message:"failed to update annotation"})}removePageAnnotation(e,r,o){this.logger.debug(se,ue,"removePageAnnotation",e,r,o),this.logger.perf(se,ue,"RemovePageAnnotation","Begin",`${e.id}-${r.index}`);const a=this.cache.getContext(e.id);if(!a)return this.logger.perf(se,ue,"RemovePageAnnotation","End",`${e.id}-${r.index}`),t.reject({code:n.DocNotOpen,message:"document does not open"});const i=a.acquirePage(r.index);let s=!1;return s=this.removeAnnotationByName(i.pagePtr,o.id),s?(s=this.pdfiumModule.FPDFPage_GenerateContent(i.pagePtr),s||this.logger.error(se,ue,"FPDFPage_GenerateContent Failed",`${e.id}-${r.index}`)):this.logger.error(se,ue,"FPDFPage_RemoveAnnot Failed",`${e.id}-${r.index}`),i.release(),this.logger.perf(se,ue,"RemovePageAnnotation","End",`${e.id}-${r.index}`),t.resolve(s)}getPageTextRects(e,r){this.logger.debug(se,ue,"getPageTextRects",e,r),this.logger.perf(se,ue,"GetPageTextRects","Begin",`${e.id}-${r.index}`);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(se,ue,"GetPageTextRects","End",`${e.id}-${r.index}`),t.reject({code:n.DocNotOpen,message:"document does not open"});const a=o.acquirePage(r.index),i=this.pdfiumModule.FPDFText_LoadPage(a.pagePtr),s=this.readPageTextRects(r,a.docPtr,a.pagePtr,i);return this.pdfiumModule.FPDFText_ClosePage(i),a.release(),this.logger.perf(se,ue,"GetPageTextRects","End",`${e.id}-${r.index}`),t.resolve(s)}renderThumbnailRaw(e,r,o){const{scaleFactor:a=1,...i}=o??{};this.logger.debug(se,ue,"renderThumbnail",e,r,o),this.logger.perf(se,ue,"RenderThumbnail","Begin",`${e.id}-${r.index}`);if(!this.cache.getContext(e.id))return this.logger.perf(se,ue,"RenderThumbnail","End",`${e.id}-${r.index}`),t.reject({code:n.DocNotOpen,message:"document does not open"});const s=this.renderPageRaw(e,r,{scaleFactor:Math.max(a,.5),...i});return this.logger.perf(se,ue,"RenderThumbnail","End",`${e.id}-${r.index}`),s}getAttachments(e){this.logger.debug(se,ue,"getAttachments",e),this.logger.perf(se,ue,"GetAttachments","Begin",e.id);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(se,ue,"GetAttachments","End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});const o=[],a=this.pdfiumModule.FPDFDoc_GetAttachmentCount(r.docPtr);for(let e=0;ethis.pdfiumModule.FPDFDoc_AddAttachment(o.docPtr,e));if(!m)return this.logger.perf(se,ue,"AddAttachment","End",e.id),t.reject({code:n.Unknown,message:`An attachment named "${a}" already exists`});this.withWString(i,e=>this.pdfiumModule.EPDFAttachment_SetDescription(m,e)),this.pdfiumModule.EPDFAttachment_SetSubtype(m,s);const F=u instanceof Uint8Array?u:new Uint8Array(u),l=F.byteLength,d=this.memoryManager.malloc(l);try{this.pdfiumModule.pdfium.HEAPU8.set(F,d);if(!this.pdfiumModule.FPDFAttachment_SetFile(m,o.docPtr,d,l))return this.logger.perf(se,ue,"AddAttachment","End",e.id),t.reject({code:n.Unknown,message:"failed to write attachment bytes"})}finally{this.memoryManager.free(d)}return this.logger.perf(se,ue,"AddAttachment","End",e.id),t.resolve(!0)}removeAttachment(e,r){this.logger.debug(se,ue,"deleteAttachment",e,r),this.logger.perf(se,ue,"DeleteAttachment","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(se,ue,"DeleteAttachment","End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});const a=this.pdfiumModule.FPDFDoc_GetAttachmentCount(o.docPtr);if(r.index<0||r.index>=a)return this.logger.perf(se,ue,"DeleteAttachment","End",e.id),t.reject({code:n.Unknown,message:`attachment index ${r.index} out of range`});const i=this.pdfiumModule.FPDFDoc_DeleteAttachment(o.docPtr,r.index);return this.logger.perf(se,ue,"DeleteAttachment","End",e.id),i?t.resolve(!0):t.reject({code:n.Unknown,message:"failed to delete attachment"})}readAttachmentContent(e,r){this.logger.debug(se,ue,"readAttachmentContent",e,r),this.logger.perf(se,ue,"ReadAttachmentContent","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(se,ue,"ReadAttachmentContent","End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});const a=this.pdfiumModule.FPDFDoc_GetAttachment(o.docPtr,r.index),i=this.memoryManager.malloc(4);if(!this.pdfiumModule.FPDFAttachment_GetFile(a,0,0,i))return this.memoryManager.free(i),this.logger.perf(se,ue,"ReadAttachmentContent","End",e.id),t.reject({code:n.CantReadAttachmentSize,message:"can not read attachment size"});const s=this.pdfiumModule.pdfium.getValue(i,"i32")>>>0,u=this.memoryManager.malloc(s);if(!this.pdfiumModule.FPDFAttachment_GetFile(a,u,s,i))return this.memoryManager.free(i),this.memoryManager.free(u),this.logger.perf(se,ue,"ReadAttachmentContent","End",e.id),t.reject({code:n.CantReadAttachmentContent,message:"can not read attachment content"});const m=new ArrayBuffer(s),F=new DataView(m);for(let e=0;e{(a.get(e.pageIndex)??a.set(e.pageIndex,[]).get(e.pageIndex)).push({slice:e,pos:t})});for(const[e,t]of a){const r=o.acquirePage(e),a=r.getTextPage();for(const{slice:e,pos:r}of t){const t=this.memoryManager.malloc(2*(e.charCount+1));this.pdfiumModule.FPDFText_GetText(a,e.charIndex,e.charCount,t),n[r]=u(this.pdfiumModule.pdfium.UTF16ToString(t)),this.memoryManager.free(t)}r.release()}return this.logger.perf(se,ue,"GetTextSlices","End",e.id),t.resolve(n)}catch(r){return this.logger.error(se,ue,"getTextSlices error",r),this.logger.perf(se,ue,"GetTextSlices","End",e.id),t.reject({code:n.Unknown,message:String(r)})}}merge(e){this.logger.debug(se,ue,"merge",e);const r=e.map(e=>e.id).join(".");this.logger.perf(se,ue,"Merge","Begin",r);const o=this.pdfiumModule.FPDF_CreateNewDocument();if(!o)return this.logger.perf(se,ue,"Merge","End",r),t.reject({code:n.CantCreateNewDoc,message:"can not create new document"});const a=[];for(const i of e.reverse()){const e=new Uint8Array(i.content),s=e.length,u=this.memoryManager.malloc(s);this.pdfiumModule.pdfium.HEAPU8.set(e,u);const m=this.pdfiumModule.FPDF_LoadMemDocument(u,s,"");if(!m){const e=this.pdfiumModule.FPDF_GetLastError();this.logger.error(se,ue,`FPDF_LoadMemDocument failed with ${e}`),this.memoryManager.free(u);for(const e of a)this.pdfiumModule.FPDF_CloseDocument(e.docPtr),this.memoryManager.free(e.filePtr);return this.logger.perf(se,ue,"Merge","End",r),t.reject({code:e,message:"FPDF_LoadMemDocument failed"})}if(a.push({filePtr:u,docPtr:m}),!this.pdfiumModule.FPDF_ImportPages(o,m,"",0)){this.pdfiumModule.FPDF_CloseDocument(o);for(const e of a)this.pdfiumModule.FPDF_CloseDocument(e.docPtr),this.memoryManager.free(e.filePtr);return this.logger.perf(se,ue,"Merge","End",r),t.reject({code:n.CantImportPages,message:"can not import pages to new document"})}}const i=this.saveDocument(o);this.pdfiumModule.FPDF_CloseDocument(o);for(const e of a)this.pdfiumModule.FPDF_CloseDocument(e.docPtr),this.memoryManager.free(e.filePtr);const s={id:`${Math.random()}`,content:i};return this.logger.perf(se,ue,"Merge","End",r),t.resolve(s)}mergePages(e){const r=e.map(e=>`${e.docId}:${e.pageIndices.join(",")}`).join("|");this.logger.debug(se,ue,"mergePages",e),this.logger.perf(se,ue,"MergePages","Begin",r);const o=this.pdfiumModule.FPDF_CreateNewDocument();if(!o)return this.logger.perf(se,ue,"MergePages","End",r),t.reject({code:n.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(se,ue,`Document ${t.docId} is not open, skipping`);continue}const n=this.pdfiumModule.FPDF_GetPageCount(e.docPtr),r=t.pageIndices.filter(e=>e>=0&&ee+1).join(",");try{if(!this.pdfiumModule.FPDF_ImportPages(o,e.docPtr,a,0))throw new Error(`Failed to import pages ${a} from document ${t.docId}`)}finally{}}const n=this.saveDocument(o),a={id:`${Math.random()}`,content:n};return this.logger.perf(se,ue,"MergePages","End",r),t.resolve(a)}catch(e){return this.logger.error(se,ue,"mergePages failed",e),this.logger.perf(se,ue,"MergePages","End",r),t.reject({code:n.CantImportPages,message:e instanceof Error?e.message:"Failed to merge pages"})}finally{o&&this.pdfiumModule.FPDF_CloseDocument(o)}}setDocumentEncryption(e,r,o,a){this.logger.debug(se,ue,"setDocumentEncryption",e,a);const i=this.cache.getContext(e.id);if(!i)return t.reject({code:n.DocNotOpen,message:"document does not open"});const s=this.pdfiumModule.EPDF_SetEncryption(i.docPtr,r,o,a);return t.resolve(s)}removeEncryption(e){this.logger.debug(se,ue,"removeEncryption",e);const r=this.cache.getContext(e.id);if(!r)return t.reject({code:n.DocNotOpen,message:"document does not open"});const o=this.pdfiumModule.EPDF_RemoveEncryption(r.docPtr);return t.resolve(o)}unlockOwnerPermissions(e,r){this.logger.debug(se,ue,"unlockOwnerPermissions",e.id);const o=this.cache.getContext(e.id);if(!o)return t.reject({code:n.DocNotOpen,message:"document does not open"});const a=this.pdfiumModule.EPDF_UnlockOwnerPermissions(o.docPtr,r);return t.resolve(a)}isEncrypted(e){this.logger.debug(se,ue,"isEncrypted",e.id);const r=this.cache.getContext(e.id);if(!r)return t.reject({code:n.DocNotOpen,message:"document does not open"});const o=this.pdfiumModule.EPDF_IsEncrypted(r.docPtr);return t.resolve(o)}isOwnerUnlocked(e){this.logger.debug(se,ue,"isOwnerUnlocked",e.id);const r=this.cache.getContext(e.id);if(!r)return t.reject({code:n.DocNotOpen,message:"document does not open"});const o=this.pdfiumModule.EPDF_IsOwnerUnlocked(r.docPtr);return t.resolve(o)}saveAsCopy(e){this.logger.debug(se,ue,"saveAsCopy",e),this.logger.perf(se,ue,"SaveAsCopy","Begin",e.id);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(se,ue,"SaveAsCopy","End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});const o=this.saveDocument(r.docPtr);return this.logger.perf(se,ue,"SaveAsCopy","End",e.id),t.resolve(o)}closeDocument(e){this.logger.debug(se,ue,"closeDocument",e),this.logger.perf(se,ue,"CloseDocument","Begin",e.id);const n=this.cache.getContext(e.id);return n?(n.dispose(),this.logger.perf(se,ue,"CloseDocument","End",e.id),t.resolve(!0)):t.resolve(!0)}closeAllDocuments(){return this.logger.debug(se,ue,"closeAllDocuments"),this.logger.perf(se,ue,"CloseAllDocuments","Begin"),this.cache.closeAllDocuments(),this.logger.perf(se,ue,"CloseAllDocuments","End"),t.resolve(!0)}addTextContent(e,t,n,r,o){if(!this.setAnnotationIcon(r,o.icon||m.Comment))return!1;if(o.state&&!this.setAnnotString(r,"State",o.state))return!1;if(o.stateModel&&!this.setAnnotString(r,"StateModel",o.stateModel))return!1;if(!this.setAnnotationOpacity(r,o.opacity??1))return!1;const a=o.strokeColor??o.color??"#FFFF00";return!!this.setAnnotationColor(r,a,F.Color)&&(!(!o.flags&&!this.setAnnotationFlags(r,["print","noZoom","noRotate"]))&&this.applyBaseAnnotationProperties(e,t,n,r,o))}addCaretContent(e,t,n,r,o){return o.strokeColor&&this.setAnnotationColor(r,o.strokeColor,F.Color),void 0!==o.opacity&&this.setAnnotationOpacity(r,o.opacity),o.intent&&this.setAnnotIntent(r,o.intent),this.setRectangleDifferences(r,o.rectangleDifferences),this.applyBaseAnnotationProperties(e,t,n,r,o)}addFreeTextContent(e,t,n,r,o){if(!this.setBorderStyle(r,l.SOLID,0))return!1;if(!this.setAnnotationOpacity(r,o.opacity??1))return!1;if(!this.setAnnotationTextAlignment(r,o.textAlign))return!1;if(!this.setAnnotationVerticalAlignment(r,o.verticalAlign))return!1;if(!this.setAnnotationDefaultAppearance(r,o.fontFamily,o.fontSize,o.fontColor))return!1;if(o.intent&&!this.setAnnotIntent(r,o.intent))return!1;const a=o.color??o.backgroundColor;if(a&&"transparent"!==a){if(!this.setAnnotationColor(r,a??"#FFFFFF",F.Color))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(r,F.Color))return!1;return this.setRectangleDifferences(r,o.rectangleDifferences),this.applyBaseAnnotationProperties(e,t,n,r,o)}addInkStroke(e,t,n,r,o){if(!this.setBorderStyle(r,l.SOLID,o.strokeWidth))return!1;if(!this.setInkList(e,t,r,o.inkList))return!1;if(!this.setAnnotationOpacity(r,o.opacity??1))return!1;const a=o.strokeColor??o.color??"#FFFF00";return!!this.setAnnotationColor(r,a,F.Color)&&this.applyBaseAnnotationProperties(e,t,n,r,o)}addLineContent(e,t,n,r,o){var a,i;if(!this.setLinePoints(e,t,r,o.linePoints.start,o.linePoints.end))return!1;if(!this.setLineEndings(r,(null==(a=o.lineEndings)?void 0:a.start)??d.None,(null==(i=o.lineEndings)?void 0:i.end)??d.None))return!1;if(!this.setBorderStyle(r,o.strokeStyle,o.strokeWidth))return!1;if(!this.setBorderDashPattern(r,o.strokeDashArray??[]))return!1;if(o.intent&&!this.setAnnotIntent(r,o.intent))return!1;if(o.color&&"transparent"!==o.color){if(!this.setAnnotationColor(r,o.color??"#FFFF00",F.InteriorColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(r,F.InteriorColor))return!1;return!!this.setAnnotationOpacity(r,o.opacity??1)&&(!!this.setAnnotationColor(r,o.strokeColor??"#FFFF00",F.Color)&&this.applyBaseAnnotationProperties(e,t,n,r,o))}addPolyContent(e,t,n,r,o){var a,s;if(o.type===i.POLYLINE&&!this.setLineEndings(r,(null==(a=o.lineEndings)?void 0:a.start)??d.None,(null==(s=o.lineEndings)?void 0:s.end)??d.None))return!1;if(!this.setPdfAnnoVertices(e,t,r,o.vertices))return!1;if(!this.setBorderStyle(r,o.strokeStyle,o.strokeWidth))return!1;if(!this.setBorderDashPattern(r,o.strokeDashArray??[]))return!1;if(o.intent&&!this.setAnnotIntent(r,o.intent))return!1;if(o.color&&"transparent"!==o.color){if(!this.setAnnotationColor(r,o.color??"#FFFF00",F.InteriorColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(r,F.InteriorColor))return!1;return!!this.setAnnotationOpacity(r,o.opacity??1)&&(!!this.setAnnotationColor(r,o.strokeColor??"#FFFF00",F.Color)&&(o.type===i.POLYGON&&this.setRectangleDifferences(r,o.rectangleDifferences),this.applyBaseAnnotationProperties(e,t,n,r,o)))}addLinkContent(e,t,n,r,o,a){const i=a.strokeStyle??l.UNDERLINE,s=a.strokeWidth??2;return!!this.setBorderStyle(o,i,s)&&(!(a.strokeDashArray&&!this.setBorderDashPattern(o,a.strokeDashArray))&&(!(a.strokeColor&&!this.setAnnotationColor(o,a.strokeColor,F.Color))&&(!(a.target&&!this.applyLinkTarget(n,o,a.target))&&this.applyBaseAnnotationProperties(e,t,r,o,a))))}addShapeContent(e,t,n,r,o){if(!this.setBorderStyle(r,o.strokeStyle,o.strokeWidth))return!1;if(!this.setBorderDashPattern(r,o.strokeDashArray??[]))return!1;if(o.color&&"transparent"!==o.color){if(!this.setAnnotationColor(r,o.color??"#FFFF00",F.InteriorColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(r,F.InteriorColor))return!1;return!!this.setAnnotationOpacity(r,o.opacity??1)&&(!!this.setAnnotationColor(r,o.strokeColor??"#FFFF00",F.Color)&&(this.setRectangleDifferences(r,o.rectangleDifferences),this.applyBaseAnnotationProperties(e,t,n,r,o)))}addTextMarkupContent(e,t,n,r,o){if(!this.syncQuadPointsAnno(e,t,r,o.segmentRects))return!1;if(!this.setAnnotationOpacity(r,o.opacity??1))return!1;const a=o.strokeColor??o.color??"#FFFF00";return!!this.setAnnotationColor(r,a,F.Color)&&this.applyBaseAnnotationProperties(e,t,n,r,o)}addRedactContent(e,t,n,r,o){if(!this.syncQuadPointsAnno(e,t,r,o.segmentRects))return!1;if(!this.setAnnotationOpacity(r,o.opacity??1))return!1;if(o.color&&"transparent"!==o.color){if(!this.setAnnotationColor(r,o.color,F.InteriorColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(r,F.InteriorColor))return!1;if(o.overlayColor&&"transparent"!==o.overlayColor){if(!this.setAnnotationColor(r,o.overlayColor,F.OverlayColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(r,F.OverlayColor))return!1;if(o.strokeColor&&"transparent"!==o.strokeColor){if(!this.setAnnotationColor(r,o.strokeColor,F.Color))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(r,F.Color))return!1;return!!this.setOverlayText(r,o.overlayText)&&(!(void 0!==o.overlayTextRepeat&&!this.setOverlayTextRepeat(r,o.overlayTextRepeat))&&(!!(void 0===o.fontFamily&&void 0===o.fontSize||this.setAnnotationDefaultAppearance(r,o.fontFamily??c.Helvetica,o.fontSize??12,o.fontColor??"#000000"))&&(!(void 0!==o.textAlign&&!this.setAnnotationTextAlignment(r,o.textAlign))&&this.applyBaseAnnotationProperties(e,t,n,r,o))))}addStampContent(e,t,n,r,o,a,i){if(a.icon&&!this.setAnnotationIcon(o,a.icon))return!1;if(a.subject&&!this.setAnnotString(o,"Subj",a.subject))return!1;if(i){for(let e=this.pdfiumModule.FPDFAnnot_GetObjectCount(o)-1;e>=0;e--)this.pdfiumModule.FPDFAnnot_RemoveObject(o,e);if(!this.addImageObject(e,t,n,r,o,a.rect,i))return!1}return!!this.applyBaseAnnotationProperties(e,n,r,o,a)&&!!this.pdfiumModule.EPDFAnnot_UpdateAppearanceToRect(o,P.Cover)}addImageObject(e,t,n,r,o,a,i){const s=i.width*i.height,u=this.memoryManager.malloc(4*s);if(!u)return!1;for(let e=0;e>>0;return 0===t?null:2===t?"":W(this.pdfiumModule.pdfium,(t,n)=>this.pdfiumModule.EPDFCatalog_GetLanguage(e,t,n),this.pdfiumModule.pdfium.UTF16ToString,t)}readMetaText(e,t){if(!!!this.pdfiumModule.EPDF_HasMetaText(e,t))return null;const n=this.pdfiumModule.FPDF_GetMetaText(e,t,0,0);return 2===n?"":W(this.pdfiumModule.pdfium,(n,r)=>this.pdfiumModule.FPDF_GetMetaText(e,t,n,r),this.pdfiumModule.pdfium.UTF16ToString,n)}setMetaText(e,t,n){if(null==n||0===n.length){return!!this.pdfiumModule.EPDF_SetMetaText(e,t,0)}const r=2*(n.length+1),o=this.memoryManager.malloc(r);try{this.pdfiumModule.pdfium.stringToUTF16(n,o,r);return!!this.pdfiumModule.EPDF_SetMetaText(e,t,o)}finally{this.memoryManager.free(o)}}getMetaTrapped(e){const t=Number(this.pdfiumModule.EPDF_GetMetaTrapped(e));switch(t){case _.NotSet:case _.True:case _.False:case _.Unknown:return t;default:return _.Unknown}}setMetaTrapped(e,t){const n=null==t||void 0===t?_.NotSet:t;return!(n!==_.NotSet&&n!==_.True&&n!==_.False&&n!==_.Unknown)&&!!this.pdfiumModule.EPDF_SetMetaTrapped(e,n)}getMetaKeyCount(e,t){return 0|Number(this.pdfiumModule.EPDF_GetMetaKeyCount(e,t))}getMetaKeyName(e,t,n){const r=this.pdfiumModule.EPDF_GetMetaKeyName(e,t,n,0,0);return r?W(this.pdfiumModule.pdfium,(r,o)=>this.pdfiumModule.EPDF_GetMetaKeyName(e,t,n,r,o),this.pdfiumModule.pdfium.UTF8ToString,r):null}readAllMeta(e,t=!0){const n=this.getMetaKeyCount(e,t),r={};for(let o=0;othis.pdfiumModule.FPDFBookmark_GetTitle(t,e,n),this.pdfiumModule.pdfium.UTF16ToString),r=this.readPdfBookmarks(e,t);return{title:n,target:this.readPdfBookmarkTarget(e,()=>this.pdfiumModule.FPDFBookmark_GetAction(t),()=>this.pdfiumModule.FPDFBookmark_GetDest(e,t)),children:r}}readPageTextRects(e,t,n,r){const o=this.pdfiumModule.FPDFText_CountRects(r,0,-1),a=[];for(let t=0;t=0){y=this.pdfiumModule.FPDFText_GetFontSize(r,A);const e=this.pdfiumModule.FPDFText_GetFontInfo(r,A,0,0,0)+1,t=this.memoryManager.malloc(e),n=this.memoryManager.malloc(4);this.pdfiumModule.FPDFText_GetFontInfo(r,A,t,e,n),E=this.pdfiumModule.pdfium.UTF8ToString(t),this.memoryManager.free(t),this.memoryManager.free(n)}const M={content:f,rect:h,font:{family:E,size:y}};a.push(M)}return a}getPageGeometry(e,r){const o="getPageGeometry";this.logger.perf(se,ue,o,"Begin",e.id);const a=this.cache.getContext(e.id);if(!a)return this.logger.perf(se,ue,o,"End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});const i=a.acquirePage(r.index),s=i.getTextPage(),u=this.pdfiumModule.FPDFText_CountChars(s),m=[];for(let e=0;e{if(null===d||null===c||null===_||null===g)return;const t=e-l;if(t<=0)return;const n=this.memoryManager.malloc(2*(t+1));this.pdfiumModule.FPDFText_GetText(s,l,t,n);const r=u(this.pdfiumModule.pdfium.UTF16ToString(n));this.memoryManager.free(n),F.push({text:r,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:c,fontSize:P,color:_,charIndex:l,charCount:t})},D=this.memoryManager.malloc(4),b=this.memoryManager.malloc(4),p=this.memoryManager.malloc(4),f=this.memoryManager.malloc(4),A=this.memoryManager.malloc(16),E=this.memoryManager.malloc(4),y=this.memoryManager.malloc(4),M=this.memoryManager.malloc(4),G=this.memoryManager.malloc(4),S=this.memoryManager.malloc(4);for(let e=0;e.01||a!==_.red||u!==_.green||m!==_.blue)&&(h(e),d=n,c=C,P=o,_={red:a,green:u,blue:m,alpha:F},l=e,g=null),this.pdfiumModule.FPDFText_GetLooseCharBox(s,e,A)){const e=this.pdfiumModule.pdfium.getValue(A,"float"),t=this.pdfiumModule.pdfium.getValue(A+4,"float"),n=this.pdfiumModule.pdfium.getValue(A+8,"float"),o=this.pdfiumModule.pdfium.getValue(A+12,"float");if(e!==n&&t!==o){this.pdfiumModule.FPDF_PageToDevice(i.pagePtr,0,0,r.size.width,r.size.height,0,e,t,E,y),this.pdfiumModule.FPDF_PageToDevice(i.pagePtr,0,0,r.size.width,r.size.height,0,n,o,M,G);const a=this.pdfiumModule.pdfium.getValue(E,"i32"),s=this.pdfiumModule.pdfium.getValue(y,"i32"),u=this.pdfiumModule.pdfium.getValue(M,"i32"),m=this.pdfiumModule.pdfium.getValue(G,"i32"),F=Math.min(a,u),l=Math.min(s,m),d=Math.abs(u-a),c=Math.abs(m-s);null===g?g={minX:F,minY:l,maxX:F+d,maxY:l+c}:(g.minX=Math.min(g.minX,F),g.minY=Math.min(g.minY,l),g.maxX=Math.max(g.maxX,F+d),g.maxY=Math.max(g.maxY,l+c))}}}return h(m),[D,b,p,f,A,E,y,M,G,S].forEach(e=>this.memoryManager.free(e)),i.release(),this.logger.perf(se,ue,o,"End",e.id),t.resolve({runs:F})}readFontInfoFromTextObject(e,t){const n=this.pdfiumModule.FPDFTextObj_GetFont(e);let r="",o="",a=400,i=!1,s=!1,u=!1;if(n){const e=this.pdfiumModule.FPDFFont_GetBaseFontName(n,0,0);if(e>0){const t=this.memoryManager.malloc(e+1);this.pdfiumModule.FPDFFont_GetBaseFontName(n,t,e+1),r=this.pdfiumModule.pdfium.UTF8ToString(t),this.memoryManager.free(t)}const m=this.pdfiumModule.FPDFFont_GetFamilyName(n,0,0);if(m>0){const e=this.memoryManager.malloc(m+1);this.pdfiumModule.FPDFFont_GetFamilyName(n,e,m+1),o=this.pdfiumModule.pdfium.UTF8ToString(e),this.memoryManager.free(e)}if(a=this.pdfiumModule.FPDFFont_GetWeight(n),u=0!==this.pdfiumModule.FPDFFont_GetIsEmbedded(n),this.pdfiumModule.FPDFFont_GetItalicAngle(n,t)){i=0!==this.pdfiumModule.pdfium.getValue(t,"i32")}s=!!(1&this.pdfiumModule.FPDFFont_GetFlags(n))}return{name:r,familyName:o,weight:a,italic:i,monospaced:s,embedded:u}}readGlyphInfo(e,t,n,r){const o=this.memoryManager.malloc(4),a=this.memoryManager.malloc(4),i=this.memoryManager.malloc(4),s=this.memoryManager.malloc(4),u=this.memoryManager.malloc(16),m=this.memoryManager.malloc(8),F=this.memoryManager.malloc(8),l=this.memoryManager.malloc(8),d=this.memoryManager.malloc(8),c=[u,o,a,i,s,m,F,l,d];let P,_,g=0,h=0,D=0,b=0,p=!1;if(this.pdfiumModule.FPDFText_GetLooseCharBox(n,r,u)){const f=this.pdfiumModule.pdfium.getValue(u,"float"),A=this.pdfiumModule.pdfium.getValue(u+4,"float"),E=this.pdfiumModule.pdfium.getValue(u+8,"float"),y=this.pdfiumModule.pdfium.getValue(u+12,"float");if(f===E||A===y)return c.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,f,A,o,a),this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,E,y,i,s);const M=this.pdfiumModule.pdfium.getValue(o,"i32"),G=this.pdfiumModule.pdfium.getValue(a,"i32"),S=this.pdfiumModule.pdfium.getValue(i,"i32"),C=this.pdfiumModule.pdfium.getValue(s,"i32");if(g=Math.min(M,S),h=Math.min(G,C),D=Math.max(1,Math.abs(S-M)),b=Math.max(1,Math.abs(C-G)),this.pdfiumModule.FPDFText_GetCharBox(n,r,m,F,l,d)){const n=this.pdfiumModule.pdfium.getValue(m,"double"),r=this.pdfiumModule.pdfium.getValue(F,"double"),u=this.pdfiumModule.pdfium.getValue(l,"double"),c=this.pdfiumModule.pdfium.getValue(d,"double");this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,n,c,o,a),this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,r,u,i,s);const g=this.pdfiumModule.pdfium.getValue(o,"i32"),h=this.pdfiumModule.pdfium.getValue(a,"i32"),D=this.pdfiumModule.pdfium.getValue(i,"i32"),b=this.pdfiumModule.pdfium.getValue(s,"i32");P={x:Math.min(g,D),y:Math.min(h,b)},_={width:Math.max(1,Math.abs(D-g)),height:Math.max(1,Math.abs(b-h))}}p=32===this.pdfiumModule.FPDFText_GetUnicode(n,r)}return c.forEach(e=>this.memoryManager.free(e)),{origin:{x:g,y:h},size:{width:D,height:b},...P&&{tightOrigin:P},..._&&{tightSize:_},...p&&{isSpace:p}}}getPageGlyphs(e,r){this.logger.debug(se,ue,"getPageGlyphs",e,r),this.logger.perf(se,ue,"getPageGlyphs","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(se,ue,"getPageGlyphs","End",e.id),t.reject({code:n.DocNotOpen,message:"document does not open"});const a=o.acquirePage(r.index),i=a.getTextPage(),s=this.pdfiumModule.FPDFText_CountChars(i),u=new Array(s);for(let e=0;e{const o=this.pdfiumModule.FPDFPage_GetAnnotCount(r.pagePtr),a=[];for(let i=0;i{const i=this.readPageAnnotation(e,t.docPtr,n,o,r);i&&a.push(i)});return a})}readPageAnnotationsRaw(e,t,n){const r=this.pdfiumModule.EPDFPage_GetAnnotCountRaw(t.docPtr,n.index);if(r<=0)return[];const o=[];for(let a=0;a({points:e.points.map(e=>this.rotatePointForSave(e,r,-t))}));return{...n,inkList:o}}case i.LINE:{const n=e;return{...n,linePoints:{start:this.rotatePointForSave(n.linePoints.start,r,-t),end:this.rotatePointForSave(n.linePoints.end,r,-t)}}}case i.POLYGON:{const n=e;return{...n,vertices:n.vertices.map(e=>this.rotatePointForSave(e,r,-t))}}case i.POLYLINE:{const n=e;return{...n,vertices:n.vertices.map(e=>this.rotatePointForSave(e,r,-t))}}default:return e}}readAnnotationColor(e,t=F.Color){const n=this.memoryManager.malloc(4),r=this.memoryManager.malloc(4),o=this.memoryManager.malloc(4);let a;return this.pdfiumModule.EPDFAnnot_GetColor(e,t,n,r,o)&&(a={red:255&this.pdfiumModule.pdfium.getValue(n,"i32"),green:255&this.pdfiumModule.pdfium.getValue(r,"i32"),blue:255&this.pdfiumModule.pdfium.getValue(o,"i32")}),this.memoryManager.free(n),this.memoryManager.free(r),this.memoryManager.free(o),a}getAnnotationColor(e,t=F.Color){const n=this.readAnnotationColor(e,t);return n?g(n):void 0}setAnnotationColor(e,t,n=F.Color){const r=h(t);return this.pdfiumModule.EPDFAnnot_SetColor(e,n,255&r.red,255&r.green,255&r.blue)}getAnnotationOpacity(e){const t=this.memoryManager.malloc(4),n=this.pdfiumModule.EPDFAnnot_GetOpacity(e,t)?this.pdfiumModule.pdfium.getValue(t,"i32"):255;return this.memoryManager.free(t),D(n)}setAnnotationOpacity(e,t){const n=j(t);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 n=this.pdfiumModule.pdfium.getValue(t,"float");return this.memoryManager.free(t),n}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 n=this.pdfiumModule.pdfium.getValue(t,"float");return this.memoryManager.free(t),n}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 n=this.pdfiumModule.pdfium.getValue(t,"float"),r=this.pdfiumModule.pdfium.getValue(t+4,"float"),o=this.pdfiumModule.pdfium.getValue(t+8,"float"),a=this.pdfiumModule.pdfium.getValue(t+12,"float");return this.memoryManager.free(t),0===n&&0===r&&0===o&&0===a?null:{left:n,top:r,right:o,bottom:a}}setAnnotUnrotatedRect(e,t,n,r){const o=Math.floor(r.origin.x),a=Math.floor(r.origin.y),i=Math.floor(r.origin.x+r.size.width),s=Math.floor(r.origin.y+r.size.height),u=this.convertDevicePointToPagePoint(e,t,{x:o,y:a}),m=this.convertDevicePointToPagePoint(e,t,{x:i,y:a}),F=this.convertDevicePointToPagePoint(e,t,{x:i,y:s}),l=this.convertDevicePointToPagePoint(e,t,{x:o,y:s});let d=Math.min(u.x,m.x,F.x,l.x),c=Math.max(u.x,m.x,F.x,l.x),P=Math.min(u.y,m.y,F.y,l.y),_=Math.max(u.y,m.y,F.y,l.y);d>c&&([d,c]=[c,d]),P>_&&([P,_]=[_,P]);const g=this.memoryManager.malloc(16),h=this.pdfiumModule.pdfium;h.setValue(g+0,d,"float"),h.setValue(g+4,_,"float"),h.setValue(g+8,c,"float"),h.setValue(g+12,P,"float");const D=this.pdfiumModule.EPDFAnnot_SetUnrotatedRect(n,g);return this.memoryManager.free(g),!!D}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 n=2*(t+1),r=this.memoryManager.malloc(n);this.pdfiumModule.EPDFAnnot_GetOverlayText(e,r,n);const o=this.pdfiumModule.pdfium.UTF16ToString(r);return this.memoryManager.free(r),o||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 t=this.memoryManager.malloc(4),n=this.memoryManager.malloc(4),r=this.memoryManager.malloc(4),o=this.memoryManager.malloc(4),a=this.memoryManager.malloc(4);if(!!!this.pdfiumModule.EPDFAnnot_GetDefaultAppearance(e,t,n,r,o,a))return void[t,n,r,o,a].forEach(e=>this.memoryManager.free(e));const i=this.pdfiumModule.pdfium,s=i.getValue(t,"i32"),u=i.getValue(n,"float"),m=255&i.getValue(r,"i32"),F=255&i.getValue(o,"i32"),l=255&i.getValue(a,"i32");return[t,n,r,o,a].forEach(e=>this.memoryManager.free(e)),{fontFamily:s,fontSize:u,fontColor:g({red:m,green:F,blue:l})}}setAnnotationDefaultAppearance(e,t,n,r){const o=t===c.Unknown?c.Helvetica:t,{red:a,green:i,blue:s}=h(r);return!!this.pdfiumModule.EPDFAnnot_SetDefaultAppearance(e,o,n,255&a,255&i,255&s)}getBorderStyle(e){const t=this.memoryManager.malloc(4);let n=0,r=l.UNKNOWN,o=!1;return r=this.pdfiumModule.EPDFAnnot_GetBorderStyle(e,t),n=this.pdfiumModule.pdfium.getValue(t,"float"),o=r!==l.UNKNOWN,this.memoryManager.free(t),{ok:o,style:r,width:n}}setBorderStyle(e,t,n){return this.pdfiumModule.EPDFAnnot_SetBorderStyle(e,t,n)}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,t){return this.pdfiumModule.EPDFAnnot_SetReplyType(e,t??b.Unknown)}getBorderEffect(e){const t=this.memoryManager.malloc(4),n=!!this.pdfiumModule.EPDFAnnot_GetBorderEffect(e,t),r=n?this.pdfiumModule.pdfium.getValue(t,"float"):0;return this.memoryManager.free(t),{ok:n,intensity:r}}getRectangleDifferences(e){const t=this.memoryManager.malloc(4),n=this.memoryManager.malloc(4),r=this.memoryManager.malloc(4),o=this.memoryManager.malloc(4),a=!!this.pdfiumModule.EPDFAnnot_GetRectangleDifferences(e,t,n,r,o),i=this.pdfiumModule.pdfium,s=i.getValue(t,"float"),u=i.getValue(n,"float"),m=i.getValue(r,"float"),F=i.getValue(o,"float");return this.memoryManager.free(t),this.memoryManager.free(n),this.memoryManager.free(r),this.memoryManager.free(o),{ok:a,left:s,top:u,right:m,bottom:F}}setRectangleDifferences(e,t){return t?this.pdfiumModule.EPDFAnnot_SetRectangleDifferences(e,t.left,t.top,t.right,t.bottom):this.pdfiumModule.EPDFAnnot_ClearRectangleDifferences(e)}getAnnotationDate(e,t){const n=this.getAnnotString(e,t);return n?r(n):void 0}setAnnotationDate(e,t,n){const r=p(n);return this.setAnnotString(e,t,r)}getAttachmentDate(e,t){const n=this.getAttachmentString(e,t);return n?r(n):void 0}setAttachmentDate(e,t,n){const r=p(n);return this.setAttachmentString(e,t,r)}getBorderDashPattern(e){const t=this.pdfiumModule.EPDFAnnot_GetBorderDashPatternCount(e);if(0===t)return{ok:!1,pattern:[]};const n=this.memoryManager.malloc(4*t),r=!!this.pdfiumModule.EPDFAnnot_GetBorderDashPattern(e,n,t),o=[];if(r){const e=this.pdfiumModule.pdfium;for(let r=0;rNumber.isFinite(e)&&e>0?e:0).filter(e=>e>0);if(0===n.length)return this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(e,0,0);const r=4*n.length,o=this.memoryManager.malloc(r);for(let e=0;e{const r=A(n),a=this.convertDevicePointToPagePoint(e,t,r.p1),s=this.convertDevicePointToPagePoint(e,t,r.p2),u=this.convertDevicePointToPagePoint(e,t,r.p3),m=this.convertDevicePointToPagePoint(e,t,r.p4);o.setValue(i+0,a.x,"float"),o.setValue(i+4,a.y,"float"),o.setValue(i+8,s.x,"float"),o.setValue(i+12,s.y,"float"),o.setValue(i+16,m.x,"float"),o.setValue(i+20,m.y,"float"),o.setValue(i+24,u.x,"float"),o.setValue(i+28,u.y,"float")},u=Math.min(a,r.length);for(let e=0;e{var t,n,r,o;return e&&Number.isFinite(null==(t=e.origin)?void 0:t.x)&&Number.isFinite(null==(n=e.origin)?void 0:n.y)&&Number.isFinite(null==(r=e.size)?void 0:r.width)&&Number.isFinite(null==(o=e.size)?void 0:o.height)&&e.size.width>0&&e.size.height>0});if(0===F.length)return this.logger.perf("PDFiumEngine","Engine",u,"End",`${e.id}-${r.index}`),t.resolve(!1);const l=m.acquirePage(r.index),{ptr:d,count:c}=this.allocFSQuadsBufferFromRects(e,r,F);let P=!1;try{P=!!this.pdfiumModule.EPDFText_RedactInQuads(l.pagePtr,d,c,!!i,!1)}finally{this.memoryManager.free(d)}return P&&(P=!!this.pdfiumModule.FPDFPage_GenerateContent(l.pagePtr)),l.disposeImmediate(),this.logger.perf("PDFiumEngine","Engine",u,"End",`${e.id}-${r.index}`),t.resolve(!!P)}applyRedaction(e,r,o){this.logger.debug(se,ue,"applyRedaction",e.id,r.index,o.id);const a="ApplyRedaction";this.logger.perf(se,ue,a,"Begin",`${e.id}-${r.index}`);const i=this.cache.getContext(e.id);if(!i)return this.logger.perf(se,ue,a,"End",`${e.id}-${r.index}`),t.reject({code:n.DocNotOpen,message:"document does not open"});const s=i.acquirePage(r.index),u=this.getAnnotationByName(s.pagePtr,o.id);if(!u)return s.release(),this.logger.perf(se,ue,a,"End",`${e.id}-${r.index}`),t.reject({code:n.NotFound,message:"annotation not found"});const m=this.pdfiumModule.EPDFAnnot_ApplyRedaction(s.pagePtr,u);return this.pdfiumModule.FPDFPage_CloseAnnot(u),m&&this.pdfiumModule.FPDFPage_GenerateContent(s.pagePtr),s.disposeImmediate(),this.logger.perf(se,ue,a,"End",`${e.id}-${r.index}`),t.resolve(!!m)}applyAllRedactions(e,r){this.logger.debug(se,ue,"applyAllRedactions",e.id,r.index);const o="ApplyAllRedactions";this.logger.perf(se,ue,o,"Begin",`${e.id}-${r.index}`);const a=this.cache.getContext(e.id);if(!a)return this.logger.perf(se,ue,o,"End",`${e.id}-${r.index}`),t.reject({code:n.DocNotOpen,message:"document does not open"});const i=a.acquirePage(r.index),s=this.pdfiumModule.EPDFPage_ApplyRedactions(i.pagePtr);return s&&this.pdfiumModule.FPDFPage_GenerateContent(i.pagePtr),i.disposeImmediate(),this.logger.perf(se,ue,o,"End",`${e.id}-${r.index}`),t.resolve(!!s)}flattenAnnotation(e,r,o){this.logger.debug(se,ue,"flattenAnnotation",e.id,r.index,o.id);const a="FlattenAnnotation";this.logger.perf(se,ue,a,"Begin",`${e.id}-${r.index}`);const i=this.cache.getContext(e.id);if(!i)return this.logger.perf(se,ue,a,"End",`${e.id}-${r.index}`),t.reject({code:n.DocNotOpen,message:"document does not open"});const s=i.acquirePage(r.index),u=this.getAnnotationByName(s.pagePtr,o.id);if(!u)return s.release(),this.logger.perf(se,ue,a,"End",`${e.id}-${r.index}`),t.reject({code:n.NotFound,message:"annotation not found"});const m=this.pdfiumModule.EPDFAnnot_Flatten(s.pagePtr,u);return this.pdfiumModule.FPDFPage_CloseAnnot(u),m&&this.pdfiumModule.FPDFPage_GenerateContent(s.pagePtr),s.disposeImmediate(),this.logger.perf(se,ue,a,"End",`${e.id}-${r.index}`),t.resolve(!!m)}allocFSQuadsBufferFromRects(e,t,n){const r=n.length,o=this.memoryManager.malloc(32*r),a=this.pdfiumModule.pdfium;for(let i=0;i0){const r=this.memoryManager.malloc(8*s);this.pdfiumModule.FPDFAnnot_GetInkListPath(n,i,r,s);for(let n=0;nthis.pdfiumModule.FPDFLink_GetAction(a),()=>this.pdfiumModule.FPDFLink_GetDest(n,a));return{pageIndex:t.index,id:o,type:i.LINK,rect:u,target:_,strokeColor:c,strokeWidth:d,strokeStyle:m,strokeDashArray:P,...this.readBaseAnnotationProperties(e,t,r)}}readPdfWidgetAnno(e,t,n,r,o){const a=this.readPageAnnoRect(n),s=this.convertPageRectToDeviceRect(e,t,a),u=this.readPdfWidgetAnnoField(r,n);return{pageIndex:t.index,id:o,type:i.WIDGET,rect:s,field:u,...this.readBaseAnnotationProperties(e,t,n)}}readPdfFileAttachmentAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o);return{pageIndex:t.index,id:r,type:i.FILEATTACHMENT,rect:a,...this.readBaseAnnotationProperties(e,t,n)}}readPdfInkAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o),s=this.getAnnotationColor(n)??"#FF0000",u=this.getAnnotationOpacity(n),{width:m}=this.getBorderStyle(n),F=this.getInkList(e,t,n),l=this.pdfiumModule.EPDFAnnot_GetBlendMode(n),d=this.getAnnotIntent(n);return{pageIndex:t.index,id:r,type:i.INK,rect:a,...d&&{intent:d},blendMode:l,strokeColor:s,color:s,opacity:u,strokeWidth:0===m?1:m,inkList:F,...this.readBaseAnnotationProperties(e,t,n)}}readPdfPolygonAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o),s=this.readPdfAnnoVertices(e,t,n),u=this.getAnnotationColor(n),m=this.getAnnotationColor(n,F.InteriorColor),d=this.getAnnotationOpacity(n),{style:c,width:P}=this.getBorderStyle(n);let _;if(c===l.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(n);e&&(_=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);return{pageIndex:t.index,id:r,type:i.POLYGON,rect:a,strokeColor:u??"#FF0000",color:m??"transparent",opacity:d,strokeWidth:0===P?1:P,strokeStyle:c,strokeDashArray:_,vertices:s,...g.ok&&{rectangleDifferences:{left:g.left,top:g.top,right:g.right,bottom:g.bottom}},...this.readBaseAnnotationProperties(e,t,n)}}readPdfPolylineAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o),s=this.readPdfAnnoVertices(e,t,n),u=this.getAnnotationColor(n),m=this.getAnnotationColor(n,F.InteriorColor),d=this.getAnnotationOpacity(n),{style:c,width:P}=this.getBorderStyle(n);let _;if(c===l.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(n);e&&(_=t)}const g=this.getLineEndings(n);return{pageIndex:t.index,id:r,type:i.POLYLINE,rect:a,strokeColor:u??"#FF0000",color:m??"transparent",opacity:d,strokeWidth:0===P?1:P,strokeStyle:c,strokeDashArray:_,lineEndings:g,vertices:s,...this.readBaseAnnotationProperties(e,t,n)}}readPdfLineAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o),s=this.getLinePoints(e,t,n),u=this.getLineEndings(n),m=this.getAnnotationColor(n),c=this.getAnnotationColor(n,F.InteriorColor),P=this.getAnnotationOpacity(n),{style:_,width:g}=this.getBorderStyle(n);let h;if(_===l.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(n);e&&(h=t)}return{pageIndex:t.index,id:r,type:i.LINE,rect:a,strokeWidth:0===g?1:g,strokeStyle:_,strokeDashArray:h,strokeColor:m??"#FF0000",color:c??"transparent",opacity:P,linePoints:s||{start:{x:0,y:0},end:{x:0,y:0}},lineEndings:u||{start:d.None,end:d.None},...this.readBaseAnnotationProperties(e,t,n)}}readPdfHighlightAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o),s=this.getQuadPointsAnno(e,t,n),u=this.getAnnotationColor(n)??"#FFFF00",m=this.getAnnotationOpacity(n),F=this.pdfiumModule.EPDFAnnot_GetBlendMode(n);return{pageIndex:t.index,id:r,type:i.HIGHLIGHT,rect:a,blendMode:F,segmentRects:s,strokeColor:u,color:u,opacity:m,...this.readBaseAnnotationProperties(e,t,n)}}readPdfUnderlineAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o),s=this.getQuadPointsAnno(e,t,n),u=this.getAnnotationColor(n)??"#FF0000",m=this.getAnnotationOpacity(n),F=this.pdfiumModule.EPDFAnnot_GetBlendMode(n);return{pageIndex:t.index,id:r,type:i.UNDERLINE,rect:a,blendMode:F,segmentRects:s,strokeColor:u,color:u,opacity:m,...this.readBaseAnnotationProperties(e,t,n)}}readPdfStrikeOutAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o),s=this.getQuadPointsAnno(e,t,n),u=this.getAnnotationColor(n)??"#FF0000",m=this.getAnnotationOpacity(n),F=this.pdfiumModule.EPDFAnnot_GetBlendMode(n);return{pageIndex:t.index,id:r,type:i.STRIKEOUT,rect:a,blendMode:F,segmentRects:s,strokeColor:u,color:u,opacity:m,...this.readBaseAnnotationProperties(e,t,n)}}readPdfSquigglyAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o),s=this.getQuadPointsAnno(e,t,n),u=this.getAnnotationColor(n)??"#FF0000",m=this.getAnnotationOpacity(n),F=this.pdfiumModule.EPDFAnnot_GetBlendMode(n);return{pageIndex:t.index,id:r,type:i.SQUIGGLY,rect:a,blendMode:F,segmentRects:s,strokeColor:u,color:u,opacity:m,...this.readBaseAnnotationProperties(e,t,n)}}readPdfCaretAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o),s=this.getAnnotationColor(n),u=this.getAnnotationOpacity(n),m=this.getAnnotIntent(n),F=this.getRectangleDifferences(n);return{pageIndex:t.index,id:r,type:i.CARET,rect:a,strokeColor:s,opacity:u,intent:m,...F.ok&&{rectangleDifferences:{left:F.left,top:F.top,right:F.right,bottom:F.bottom}},...this.readBaseAnnotationProperties(e,t,n)}}readPdfRedactAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o),s=this.getQuadPointsAnno(e,t,n),u=this.getAnnotationColor(n,F.InteriorColor),m=this.getAnnotationColor(n,F.OverlayColor),l=this.getAnnotationColor(n,F.Color),d=this.getAnnotationOpacity(n),c=this.getOverlayText(n),P=this.getOverlayTextRepeat(n),_=this.getAnnotationDefaultAppearance(n),g=this.getAnnotationTextAlignment(n);return{pageIndex:t.index,id:r,type:i.REDACT,rect:a,segmentRects:s,color:u,overlayColor:m,strokeColor:l,opacity:d,overlayText:c,overlayTextRepeat:P,fontFamily:null==_?void 0:_.fontFamily,fontSize:null==_?void 0:_.fontSize,fontColor:null==_?void 0:_.fontColor,textAlign:g,...this.readBaseAnnotationProperties(e,t,n)}}readPdfStampAnno(e,t,n,r){const o=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,o);return{pageIndex:t.index,id:r,type:i.STAMP,rect:a,...this.readBaseAnnotationProperties(e,t,n)}}readPdfPageObject(e){switch(this.pdfiumModule.FPDFPageObj_GetType(e)){case E.PATH:return this.readPathObject(e);case E.IMAGE:return this.readImageObject(e);case E.FORM:return this.readFormObject(e)}}readPathObject(e){const t=this.pdfiumModule.FPDFPath_CountSegments(e),n=this.memoryManager.malloc(4),r=this.memoryManager.malloc(4),o=this.memoryManager.malloc(4),a=this.memoryManager.malloc(4);this.pdfiumModule.FPDFPageObj_GetBounds(e,n,r,o,a);const i={left:this.pdfiumModule.pdfium.getValue(n,"float"),bottom:this.pdfiumModule.pdfium.getValue(r,"float"),right:this.pdfiumModule.pdfium.getValue(o,"float"),top:this.pdfiumModule.pdfium.getValue(a,"float")};this.memoryManager.free(n),this.memoryManager.free(r),this.memoryManager.free(o),this.memoryManager.free(a);const s=[];for(let n=0;n({points:e.points.map(e=>this.rotatePointForSave(e,r,t))}));return{...n,inkList:o}}case i.LINE:{const n=e;return{...n,linePoints:{start:this.rotatePointForSave(n.linePoints.start,r,t),end:this.rotatePointForSave(n.linePoints.end,r,t)}}}case i.POLYGON:{const n=e;return{...n,vertices:n.vertices.map(e=>this.rotatePointForSave(e,r,t))}}case i.POLYLINE:{const n=e;return{...n,vertices:n.vertices.map(e=>this.rotatePointForSave(e,r,t))}}default:return e}}applyBaseAnnotationProperties(e,t,n,r,o){if(!this.setAnnotString(r,"T",o.author||""))return!1;if(!this.setAnnotString(r,"Contents",o.contents??""))return!1;if(o.modified&&!this.setAnnotationDate(r,"M",o.modified))return!1;if(o.created&&!this.setAnnotationDate(r,"CreationDate",o.created))return!1;if(o.flags&&!this.setAnnotationFlags(r,o.flags))return!1;const a=this.getAnnotCustom(r)??{},i={...a,...o.custom??{}};delete i.unrotatedRect,delete i.rotation;if(Object.keys(i).length>0){if(!this.setAnnotCustom(r,i))return!1}else if(Object.keys(a).length>0&&!this.setAnnotCustom(r,null))return!1;if(void 0!==o.rotation){const e=o.rotation?(360-o.rotation)%360:0;this.setAnnotExtendedRotation(r,e)}return o.unrotatedRect?this.setAnnotUnrotatedRect(e,t,r,o.unrotatedRect):o.rotation&&0!==o.rotation&&this.setAnnotUnrotatedRect(e,t,r,o.rect),!!this.setInReplyToId(n,r,o.inReplyToId)&&!!this.setReplyType(r,o.replyType)}readBaseAnnotationProperties(e,t,n){const r=this.getAnnotString(n,"T"),o=this.getAnnotString(n,"Contents")||"",a=this.getAnnotationDate(n,"M"),i=this.getAnnotationDate(n,"CreationDate"),s=this.getAnnotationFlags(n),u=this.getAnnotCustom(n),m=this.getInReplyToId(n),F=this.getReplyType(n),l=this.getAnnotExtendedRotation(n),d=0!==l?(360-l)%360:0,c=this.readAnnotUnrotatedRect(n),P=c?this.convertPageRectToDeviceRect(e,t,c):void 0;return{author:r,contents:o,modified:a,created:i,flags:s,custom:u,...m&&{inReplyToId:m},...F&&F!==b.Reply&&{replyType:F},...0!==d&&{rotation:d},...void 0!==P&&{unrotatedRect:P}}}getAnnotString(e,t){const n=this.pdfiumModule.FPDFAnnot_GetStringValue(e,t,0,0);if(0===n)return;const r=2*(n+1),o=this.memoryManager.malloc(r);this.pdfiumModule.FPDFAnnot_GetStringValue(e,t,o,r);const a=this.pdfiumModule.pdfium.UTF16ToString(o);return this.memoryManager.free(o),a||void 0}getAttachmentString(e,t){const n=this.pdfiumModule.FPDFAttachment_GetStringValue(e,t,0,0);if(0===n)return;const r=2*(n+1),o=this.memoryManager.malloc(r);this.pdfiumModule.FPDFAttachment_GetStringValue(e,t,o,r);const a=this.pdfiumModule.pdfium.UTF16ToString(o);return this.memoryManager.free(o),a||void 0}getAttachmentNumber(e,t){const n=this.memoryManager.malloc(4);try{if(!this.pdfiumModule.EPDFAttachment_GetIntegerValue(e,t,n))return;return this.pdfiumModule.pdfium.getValue(n,"i32")>>>0}finally{this.memoryManager.free(n)}}getAnnotCustom(e){const t=this.getAnnotString(e,"EPDFCustom");if(t)try{return JSON.parse(t)}catch(e){return console.warn("Failed to parse annotation custom data as JSON:",e),void console.warn("Invalid JSON string:",t)}}setAnnotCustom(e,t){if(null==t)return this.setAnnotString(e,"EPDFCustom","");try{const n=JSON.stringify(t);return this.setAnnotString(e,"EPDFCustom",n)}catch(e){return console.warn("Failed to stringify annotation custom data as JSON:",e),console.warn("Invalid data object:",t),!1}}getAnnotIntent(e){const t=this.pdfiumModule.EPDFAnnot_GetIntent(e,0,0);if(0===t)return;const n=2*(t+1),r=this.memoryManager.malloc(n);this.pdfiumModule.EPDFAnnot_GetIntent(e,r,n);const o=this.pdfiumModule.pdfium.UTF16ToString(r);return this.memoryManager.free(r),o&&"undefined"!==o?o: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 n=2*(t+1),r=this.memoryManager.malloc(n);this.pdfiumModule.EPDFAnnot_GetRichContent(e,r,n);const o=this.pdfiumModule.pdfium.UTF16ToString(r);return this.memoryManager.free(r),o||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,n){return this.withWString(n,n=>this.pdfiumModule.FPDFAnnot_SetStringValue(e,t,n))}setAttachmentString(e,t,n){return this.withWString(n,n=>this.pdfiumModule.FPDFAttachment_SetStringValue(e,t,n))}readPdfAnnoVertices(e,t,n){const r=[],o=this.pdfiumModule.FPDFAnnot_GetVertices(n,0,0),a=this.memoryManager.malloc(8*o);this.pdfiumModule.FPDFAnnot_GetVertices(n,a,o);for(let n=0;n{const i=this.convertDevicePointToPagePoint(e,t,n);o.setValue(a+8*r+0,i.x,"float"),o.setValue(a+8*r+4,i.y,"float")});const i=this.pdfiumModule.EPDFAnnot_SetVertices(n,a,r.length);return this.memoryManager.free(a),i}readPdfBookmarkTarget(e,t,n){const r=t();if(r){return{type:"action",action:this.readPdfAction(e,r)}}{const t=n();if(t){return{type:"destination",destination:this.readPdfDestination(e,t)}}}}readPdfWidgetAnnoField(e,t){const n=this.pdfiumModule.FPDFAnnot_GetFormFieldFlags(e,t),r=this.pdfiumModule.FPDFAnnot_GetFormFieldType(e,t),o=W(this.pdfiumModule.pdfium,(n,r)=>this.pdfiumModule.FPDFAnnot_GetFormFieldName(e,t,n,r),this.pdfiumModule.pdfium.UTF16ToString),a=W(this.pdfiumModule.pdfium,(n,r)=>this.pdfiumModule.FPDFAnnot_GetFormFieldAlternateName(e,t,n,r),this.pdfiumModule.pdfium.UTF16ToString),i=W(this.pdfiumModule.pdfium,(n,r)=>this.pdfiumModule.FPDFAnnot_GetFormFieldValue(e,t,n,r),this.pdfiumModule.pdfium.UTF16ToString),s=[];if(r===G.COMBOBOX||r===G.LISTBOX){const n=this.pdfiumModule.FPDFAnnot_GetOptionCount(e,t);for(let r=0;rthis.pdfiumModule.FPDFAnnot_GetOptionLabel(e,t,r,n,o),this.pdfiumModule.pdfium.UTF16ToString),o=this.pdfiumModule.FPDFAnnot_IsOptionSelected(e,t,r);s.push({label:n,isSelected:o})}}let u=!1;return r!==G.CHECKBOX&&r!==G.RADIOBUTTON||(u=this.pdfiumModule.FPDFAnnot_IsChecked(e,t)),{flag:n,type:r,name:o,alternateName:a,value:i,isChecked:u,options:s}}renderPageAnnotationRaw(e,r,o,a){const{scaleFactor:i=1,rotation:s=C.Degree0,dpr:u=1,mode:m=S.Normal}=a??{};this.logger.debug(se,ue,"renderPageAnnotation",e,r,o,a),this.logger.perf(se,ue,"RenderPageAnnotation","Begin",`${e.id}-${r.index}-${o.id}`);const F=new O,l=this.cache.getContext(e.id);if(!l)return this.logger.perf(se,ue,"RenderPageAnnotation","End",`${e.id}-${r.index}-${o.id}`),t.reject({code:n.DocNotOpen,message:"document does not open"});const d=l.acquirePage(r.index),c=this.getAnnotationByName(d.pagePtr,o.id);if(!c)return this.logger.perf(se,ue,"RenderPageAnnotation","End",`${e.id}-${r.index}-${o.id}`),d.release(),t.reject({code:n.NotFound,message:"annotation not found"});const P=Math.max(.01,i*u),_=!!(null==a?void 0:a.unrotated)&&!!o.unrotatedRect,g=_?o.unrotatedRect:o.rect,h=x(g),D=x(T(r.size,h,s,P)),b=Math.max(1,D.size.width),p=Math.max(1,D.size.height),f=4*b,A=f*p,E=this.memoryManager.malloc(A),y=this.pdfiumModule.FPDFBitmap_CreateEx(b,p,4,E,f);this.pdfiumModule.FPDFBitmap_FillRect(y,0,0,b,p,0);const M=v(h,s,b,p),G=this.memoryManager.malloc(24);new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer,G,6).set([M.a,M.b,M.c,M.d,M.e,M.f]);let R=!1;try{R=_?!!this.pdfiumModule.EPDF_RenderAnnotBitmapUnrotated(y,d.pagePtr,c,m,G,16):!!this.pdfiumModule.EPDF_RenderAnnotBitmap(y,d.pagePtr,c,m,G,16)}finally{this.memoryManager.free(G),this.pdfiumModule.FPDFBitmap_Destroy(y),this.pdfiumModule.FPDFPage_CloseAnnot(c),d.release()}if(!R)return this.memoryManager.free(E),this.logger.perf(se,ue,"RenderPageAnnotation","End",`${e.id}-${r.index}-${o.id}`),t.reject({code:n.Unknown,message:"EPDF_RenderAnnotBitmap failed"});const k=this.pdfiumModule.pdfium.HEAPU8.subarray(E,E+A),w={data:new Uint8ClampedArray(k),width:b,height:p};return F.resolve(w),this.memoryManager.free(E),F}renderPageAnnotationsRaw(e,r,o){const{scaleFactor:a=1,rotation:i=C.Degree0,dpr:s=1}=o??{};this.logger.debug(se,ue,"renderPageAnnotationsRaw",e,r,o),this.logger.perf(se,ue,"RenderPageAnnotationsRaw","Begin",`${e.id}-${r.index}`);const u=this.cache.getContext(e.id);if(!u)return this.logger.perf(se,ue,"RenderPageAnnotationsRaw","End",`${e.id}-${r.index}`),t.reject({code:n.DocNotOpen,message:"document does not open"});const m=u.acquirePage(r.index),F={},l=Math.max(.01,a*s),d=this.pdfiumModule.FPDFPage_GetAnnotCount(m.pagePtr);for(let t=0;tthis.pdfiumModule.EPDFDest_CreateView(o,e,t,n))}finally{this.pdfiumModule.FPDF_ClosePage(o)}}applyBookmarkTarget(e,t,n){if("destination"===n.type){const r=this.createLocalDestPtr(e,n.destination);if(!r)return!1;return!!this.pdfiumModule.EPDFBookmark_SetDest(e,t,r)}const r=n.action;switch(r.type){case B.Goto:{const n=this.createLocalDestPtr(e,r.destination);if(!n)return!1;const o=this.pdfiumModule.EPDFAction_CreateGoTo(e,n);return!!o&&!!this.pdfiumModule.EPDFBookmark_SetAction(e,t,o)}case B.URI:{const n=this.pdfiumModule.EPDFAction_CreateURI(e,r.uri);return!!n&&!!this.pdfiumModule.EPDFBookmark_SetAction(e,t,n)}case B.LaunchAppOrOpenFile:{const n=this.withWString(r.path,t=>this.pdfiumModule.EPDFAction_CreateLaunch(e,t));return!!n&&!!this.pdfiumModule.EPDFBookmark_SetAction(e,t,n)}case B.RemoteGoto:case B.Unsupported:default:return!1}}applyLinkTarget(e,t,n){if("destination"===n.type){const r=this.createLocalDestPtr(e,n.destination);if(!r)return!1;const o=this.pdfiumModule.EPDFAction_CreateGoTo(e,r);return!!o&&!!this.pdfiumModule.EPDFAnnot_SetAction(t,o)}const r=n.action;switch(r.type){case B.Goto:{const n=this.createLocalDestPtr(e,r.destination);if(!n)return!1;const o=this.pdfiumModule.EPDFAction_CreateGoTo(e,n);return!!o&&!!this.pdfiumModule.EPDFAnnot_SetAction(t,o)}case B.URI:{const n=this.pdfiumModule.EPDFAction_CreateURI(e,r.uri);return!!n&&!!this.pdfiumModule.EPDFAnnot_SetAction(t,n)}case B.LaunchAppOrOpenFile:{const n=this.withWString(r.path,t=>this.pdfiumModule.EPDFAction_CreateLaunch(e,t));return!!n&&!!this.pdfiumModule.EPDFAnnot_SetAction(t,n)}case B.RemoteGoto:case B.Unsupported:default:return!1}}readPdfAction(e,t){let n;switch(this.pdfiumModule.FPDFAction_GetType(t)){case B.Unsupported:n={type:B.Unsupported};break;case B.Goto:{const r=this.pdfiumModule.FPDFAction_GetDest(e,t);if(r){const t=this.readPdfDestination(e,r);n={type:B.Goto,destination:t}}else n={type:B.Unsupported}}break;case B.RemoteGoto:n={type:B.Unsupported};break;case B.URI:{const r=W(this.pdfiumModule.pdfium,(n,r)=>this.pdfiumModule.FPDFAction_GetURIPath(e,t,n,r),this.pdfiumModule.pdfium.UTF8ToString);n={type:B.URI,uri:r}}break;case B.LaunchAppOrOpenFile:{const e=W(this.pdfiumModule.pdfium,(e,n)=>this.pdfiumModule.FPDFAction_GetFilePath(t,e,n),this.pdfiumModule.pdfium.UTF8ToString);n={type:B.LaunchAppOrOpenFile,path:e}}}return n}readPdfDestination(e,t){const n=this.pdfiumModule.FPDFDest_GetDestPageIndex(e,t),r=this.memoryManager.malloc(4),o=this.memoryManager.malloc(16),a=this.pdfiumModule.FPDFDest_GetView(t,r,o),i=this.pdfiumModule.pdfium.getValue(r,"i32"),s=[];for(let e=0;ethis.pdfiumModule.FPDFAttachment_GetName(n,e,t),this.pdfiumModule.pdfium.UTF16ToString),o=W(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.EPDFAttachment_GetDescription(n,e,t),this.pdfiumModule.pdfium.UTF16ToString),a=W(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFAttachment_GetSubtype(n,e,t),this.pdfiumModule.pdfium.UTF16ToString),i=this.getAttachmentDate(n,"CreationDate"),s=W(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFAttachment_GetStringValue(n,"Checksum",e,t),this.pdfiumModule.pdfium.UTF16ToString);return{index:t,name:r,description:o,mimeType:a,size:this.getAttachmentNumber(n,"Size"),creationDate:i,checksum:s}}convertDevicePointToPagePoint(e,t,n){const r=t.size.width,o=t.size.height,a=e.normalizedRotation?0:3&t.rotation;return 0===a?{x:n.x,y:o-n.y}:1===a?{x:n.y,y:n.x}:2===a?{x:r-n.x,y:n.y}:{x:o-n.y,y:r-n.x}}convertPagePointToDevicePoint(e,t,n){const r=t.size.width,o=t.size.height,a=e.normalizedRotation?0:3&t.rotation;return 0===a?{x:n.x,y:o-n.y}:1===a?{x:n.y,y:n.x}:2===a?{x:r-n.x,y:n.y}:{x:r-n.y,y:o-n.x}}convertPageRectToDeviceRect(e,t,n){const{x:r,y:o}=this.convertPagePointToDevicePoint(e,t,{x:n.left,y:n.top});return{origin:{x:r,y:o},size:{width:Math.abs(n.right-n.left),height:Math.abs(n.top-n.bottom)}}}readPageAnnoAppearanceStreams(e){return{normal:this.readPageAnnoAppearanceStream(e,S.Normal),rollover:this.readPageAnnoAppearanceStream(e,S.Rollover),down:this.readPageAnnoAppearanceStream(e,S.Down)}}readPageAnnoAppearanceStream(e,t=S.Normal){const n=2*(this.pdfiumModule.FPDFAnnot_GetAP(e,t,0,0)+1),r=this.memoryManager.malloc(n);this.pdfiumModule.FPDFAnnot_GetAP(e,t,r,n);const o=this.pdfiumModule.pdfium.UTF16ToString(r);return this.memoryManager.free(r),o}setPageAnnoAppearanceStream(e,t=S.Normal,n){const r=2*(n.length+1),o=this.memoryManager.malloc(r);try{this.pdfiumModule.pdfium.stringToUTF16(n,o,r);return!!this.pdfiumModule.FPDFAnnot_SetAP(e,t,o)}finally{this.memoryManager.free(o)}}setPageAnnoRect(e,t,n,r){const o=Math.floor(r.origin.x),a=Math.floor(r.origin.y),i=Math.floor(r.origin.x+r.size.width),s=Math.floor(r.origin.y+r.size.height),u=this.convertDevicePointToPagePoint(e,t,{x:o,y:a}),m=this.convertDevicePointToPagePoint(e,t,{x:i,y:a}),F=this.convertDevicePointToPagePoint(e,t,{x:i,y:s}),l=this.convertDevicePointToPagePoint(e,t,{x:o,y:s});let d=Math.min(u.x,m.x,F.x,l.x),c=Math.max(u.x,m.x,F.x,l.x),P=Math.min(u.y,m.y,F.y,l.y),_=Math.max(u.y,m.y,F.y,l.y);d>c&&([d,c]=[c,d]),P>_&&([P,_]=[_,P]);const g=this.memoryManager.malloc(16),h=this.pdfiumModule.pdfium;h.setValue(g+0,d,"float"),h.setValue(g+4,_,"float"),h.setValue(g+8,c,"float"),h.setValue(g+12,P,"float");const D=this.pdfiumModule.FPDFAnnot_SetRect(n,g);return this.memoryManager.free(g),!!D}readPageAnnoRect(e){const t=this.memoryManager.malloc(16),n={left:0,top:0,right:0,bottom:0};return this.pdfiumModule.EPDFAnnot_GetRect(e,t)&&(n.left=this.pdfiumModule.pdfium.getValue(t,"float"),n.top=this.pdfiumModule.pdfium.getValue(t+4,"float"),n.right=this.pdfiumModule.pdfium.getValue(t+8,"float"),n.bottom=this.pdfiumModule.pdfium.getValue(t+12,"float")),this.memoryManager.free(t),n}getHighlightRects(e,t,n,r,o){const a=this.pdfiumModule.FPDFText_CountRects(n,r,o),i=[],s=this.memoryManager.malloc(8),u=this.memoryManager.malloc(8),m=this.memoryManager.malloc(8),F=this.memoryManager.malloc(8);for(let r=0;r{this.logger.perf(se,ue,"GetAnnotationsBatch","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return void r.reject({code:n.DocNotOpen,message:"Document is not open"});const a={},i=t.length;for(let n=0;n{this.logger.perf(se,ue,"SearchBatch","Begin",e.id);const i=this.cache.getContext(e.id);if(!i)return void a.reject({code:n.DocNotOpen,message:"Document is not open"});const s=2*(r.length+1),u=this.memoryManager.malloc(s);this.pdfiumModule.pdfium.stringToUTF16(r,u,s);try{const n={},r=t.length;for(let s=0;s/\\\-"'`"”\u2013\u2014]/;let a=t;for(;a>0&&o.test(e[a-1]);)a--;let i=0;for(;a>0&&i{for(;t>0&&!o.test(e[t-1]);)t--;return t})(a);let s=t+n;for(;s{for(;t0,truncatedRight:s{const a=t.getTextPage(),i=this.pdfiumModule.FPDFText_CountChars(a),s=this.memoryManager.malloc(2*(i+1));this.pdfiumModule.FPDFText_GetText(a,0,i,s);const u=this.pdfiumModule.pdfium.UTF16ToString(s);this.memoryManager.free(s);const m=[],F=this.pdfiumModule.FPDFText_FindStart(a,r,o,0);for(;this.pdfiumModule.FPDFText_FindNext(F);){const t=this.pdfiumModule.FPDFText_GetSchResultIndex(F),r=this.pdfiumModule.FPDFText_GetSchCount(F),o=this.getHighlightRects(e,n,a,t,r),i=this.buildContext(u,t,r);m.push({pageIndex:n.index,charIndex:t,charCount:r,rects:o,context:i})}return this.pdfiumModule.FPDFText_FindClose(F),m})}preparePrintDocument(e,r){const{includeAnnotations:o=!0,pageRange:a=null}=r??{};this.logger.debug(se,ue,"preparePrintDocument",e,r),this.logger.perf(se,ue,"PreparePrintDocument","Begin",e.id);const i=this.cache.getContext(e.id);if(!i)return this.logger.perf(se,ue,"PreparePrintDocument","End",e.id),t.reject({code:n.DocNotOpen,message:"Document is not open"});const s=this.pdfiumModule.FPDF_CreateNewDocument();if(!s)return this.logger.perf(se,ue,"PreparePrintDocument","End",e.id),t.reject({code:n.CantCreateNewDoc,message:"Cannot create print document"});try{const r=this.sanitizePageRange(a,e.pageCount);if(!this.pdfiumModule.FPDF_ImportPages(s,i.docPtr,r??"",0))return this.pdfiumModule.FPDF_CloseDocument(s),this.logger.error(se,ue,"Failed to import pages for printing"),this.logger.perf(se,ue,"PreparePrintDocument","End",e.id),t.reject({code:n.CantImportPages,message:"Failed to import pages for printing"});if(!o){const r=this.removeAnnotationsFromPrintDocument(s);if(!r.success)return this.pdfiumModule.FPDF_CloseDocument(s),this.logger.error(se,ue,`Failed to remove annotations: ${r.error}`),this.logger.perf(se,ue,"PreparePrintDocument","End",e.id),t.reject({code:n.Unknown,message:`Failed to prepare print document: ${r.error}`});this.logger.debug(se,ue,`Removed ${r.annotationsRemoved} annotations from ${r.pagesProcessed} pages`)}const u=this.saveDocument(s);return this.pdfiumModule.FPDF_CloseDocument(s),this.logger.perf(se,ue,"PreparePrintDocument","End",e.id),t.resolve(u)}catch(r){return s&&this.pdfiumModule.FPDF_CloseDocument(s),this.logger.error(se,ue,"preparePrintDocument failed",r),this.logger.perf(se,ue,"PreparePrintDocument","End",e.id),t.reject({code:n.Unknown,message:r instanceof Error?r.message:"Failed to prepare print document"})}}removeAnnotationsFromPrintDocument(e){let t=0,n=0;try{const r=this.pdfiumModule.FPDF_GetPageCount(e);for(let o=0;o=0;n--){this.pdfiumModule.EPDFPage_RemoveAnnotRaw(e,o,n)?(a++,t++):this.logger.warn(se,ue,`Failed to remove annotation ${n} from page ${o}`)}if(a>0){const t=this.pdfiumModule.FPDF_LoadPage(e,o);t&&(this.pdfiumModule.FPDFPage_GenerateContent(t),this.pdfiumModule.FPDF_ClosePage(t))}n++}return{success:!0,annotationsRemoved:t,pagesProcessed:n}}catch(e){return{success:!1,annotationsRemoved:t,pagesProcessed:n,error:e instanceof Error?e.message:"Unknown error during annotation removal"}}}sanitizePageRange(e,t){if(!e||""===e.trim())return null;try{const n=[],r=e.split(",");for(const e of r){const r=e.trim();if(r.includes("-")){const[e,o]=r.split("-").map(e=>e.trim()),a=parseInt(e,10),i=parseInt(o,10);if(isNaN(a)||isNaN(i)){this.logger.warn(se,ue,`Invalid range: ${r}`);continue}const s=Math.max(1,Math.min(a,t)),u=Math.max(1,Math.min(i,t));for(let e=s;e<=u;e++)n.includes(e)||n.push(e)}else{const e=parseInt(r,10);if(isNaN(e)){this.logger.warn(se,ue,`Invalid page number: ${r}`);continue}const o=Math.max(1,Math.min(e,t));n.includes(o)||n.push(o)}}if(0===n.length)return this.logger.warn(se,ue,"No valid pages in range, using all pages"),null;n.sort((e,t)=>e-t);const o=[];let a=n[0],i=n[0];for(let e=1;e "${s}"`),s}catch(e){return this.logger.error(se,ue,`Error sanitizing page range: ${e}`),null}}}async function Fe(e,t){const n=await fetch(e),r=await n.arrayBuffer(),o=await $({wasmBinary:r}),a=new me(o,{logger:null==t?void 0:t.logger,fontFallback:null==t?void 0:t.fontFallback});return new L(a,{imageConverter:N,logger:null==t?void 0:t.logger})}export{Fe as createPdfiumEngine}; diff --git a/src/components/BootstrapBlazor.EmbedPDF/wwwroot/embedpdf-DX_zb2Zx.js b/src/components/BootstrapBlazor.EmbedPDF/wwwroot/embedpdf-DX_zb2Zx.js deleted file mode 100644 index fd96dd52..00000000 --- a/src/components/BootstrapBlazor.EmbedPDF/wwwroot/embedpdf-DX_zb2Zx.js +++ /dev/null @@ -1,3 +0,0 @@ -function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,a=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){s=!0,r=e},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw r}}}}function s(e,t,n){return(t=b(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function l(e){return l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},l(e)}function c(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&f(e,t)}function d(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(d=function(){return!!e})()}function u(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function h(e){for(var t=1;t3?(i=g===o)&&(l=r[(s=r[4])?5:(s=3,3)],r[4]=r[5]=e):r[0]<=m&&((i=n<2&&mo||o>g)&&(r[4]=n,r[5]=o,h.n=g,s=0))}if(i||n>1)return a;throw u=!0,o}return function(i,d,g){if(c>1)throw TypeError("Generator is already running");for(u&&1===d&&m(d,g),s=d,l=g;(t=s<2?e:l)||!u;){r||(s?s<3?(s>1&&(h.n=-1),m(s,l)):h.n=l:h.v=l);try{if(c=2,r){if(s||(i="next"),t=r[i]){if(!(t=t.call(r,l)))throw TypeError("iterator result is not an object");if(!t.done)return t;l=t.value,s<2&&(s=0)}else 1===s&&(t=r.return)&&t.call(r),s<2&&(l=TypeError("The iterator does not provide a '"+i+"' method"),s=1);r=e}else if((t=(u=h.n<0)?l:n.call(o,h))!==a)break}catch(t){r=e,s=1,l=t}finally{c=1}}return{value:t,done:u}}}(n,i,r),!0),c}var a={};function s(){}function l(){}function c(){}t=Object.getPrototypeOf;var d=[][o]?t(t([][o]())):(p(t={},o,function(){return this}),t),u=c.prototype=s.prototype=Object.create(d);function h(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,c):(e.__proto__=c,p(e,i,"GeneratorFunction")),e.prototype=Object.create(u),e}return l.prototype=c,p(u,"constructor",c),p(c,"constructor",l),l.displayName="GeneratorFunction",p(c,i,"GeneratorFunction"),p(u),p(u,i,"Generator"),p(u,o,function(){return this}),p(u,"toString",function(){return"[object Generator]"}),(g=function(){return{w:r,m:h}})()}function p(e,t,n,o){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}p=function(e,t,n,o){function r(t,n){p(e,t,function(e){return this._invoke(t,n,e)})}t?i?i(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(r("next",0),r("throw",1),r("return",2))},p(e,t,n,o)}function f(e,t){return f=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},f(e,t)}function v(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var o,i,r,a,s=[],l=!0,c=!1;try{if(r=(n=n.call(e)).next,0===t);else for(;!(l=(o=r.call(n)).done)&&(s.push(o.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||x(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function y(t){return function(t){if(Array.isArray(t))return e(t)}(t)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(t)||x(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function b(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var o=n.call(e,t);if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function w(e){return w="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},w(e)}function x(t,n){if(t){if("string"==typeof t)return e(t,n);var o={}.toString.call(t).slice(8,-1);return"Object"===o&&t.constructor&&(o=t.constructor.name),"Map"===o||"Set"===o?Array.from(t):"Arguments"===o||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o)?e(t,n):void 0}}var C,I,k,S,M,A,P,D,R,z,T,E,_={},N=[],O=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,L=Array.isArray;function $(e,t){for(var n in t)e[n]=t[n];return e}function j(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function F(e,t,n){var o,i,r,a={};for(r in t)"key"==r?o=t[r]:"ref"==r?i=t[r]:a[r]=t[r];if(arguments.length>2&&(a.children=arguments.length>3?C.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(r in e.defaultProps)void 0===a[r]&&(a[r]=e.defaultProps[r]);return U(e,a,o,i,null)}function U(e,t,n,o,i){var r={type:e,props:t,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==i?++k:i,__i:-1,__u:0};return null==i&&null!=I.vnode&&I.vnode(r),r}function H(e){return e.children}function B(e,t){this.props=e,this.context=t}function W(e,t){if(null==t)return e.__?W(e.__,e.__i+1):null;for(var n;ts&&S.sort(P),e=S.shift(),s=S.length,e.__d&&(n=void 0,o=void 0,i=(o=(t=e).__v).__e,r=[],a=[],t.__P&&((n=$({},o)).__v=o.__v+1,I.vnode&&I.vnode(n),te(t.__P,n,o,t.__n,t.__P.namespaceURI,32&o.__u?[i]:null,r,null==i?W(o):i,!!(32&o.__u),a),n.__v=o.__v,n.__.__k[n.__i]=n,oe(r,n,a),o.__e=o.__=null,n.__e!=i&&q(n)));V.__r=0}function K(e,t,n,o,i,r,a,s,l,c,d){var u,h,m,g,p,f,v,y=o&&o.__k||N,b=t.length;for(l=function(e,t,n,o,i){var r,a,s,l,c,d=n.length,u=d,h=0;for(e.__k=new Array(i),r=0;r0?a=e.__k[r]=U(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):e.__k[r]=a,l=r+h,a.__=e,a.__b=e.__b+1,s=null,-1!=(c=a.__i=X(a,n,l,u))&&(u--,(s=n[c])&&(s.__u|=2)),null==s||null==s.__v?(-1==c&&(i>d?h--:il?h--:h++,a.__u|=4))):e.__k[r]=null;if(u)for(r=0;r(d?1:0))for(i=n-1,r=n+1;i>=0||r=0?i--:r++])&&!(2&c.__u)&&s==c.key&&l==c.type)return a;return-1}function Q(e,t,n){"-"==t[0]?e.setProperty(t,null==n?"":n):e[t]=null==n?"":"number"!=typeof n||O.test(t)?n:n+"px"}function J(e,t,n,o,i){var r,a;e:if("style"==t)if("string"==typeof n)e.style.cssText=n;else{if("string"==typeof o&&(e.style.cssText=o=""),o)for(t in o)n&&t in n||Q(e.style,t,"");if(n)for(t in n)o&&n[t]==o[t]||Q(e.style,t,n[t])}else if("o"==t[0]&&"n"==t[1])r=t!=(t=t.replace(D,"$1")),a=t.toLowerCase(),t=a in e||"onFocusOut"==t||"onFocusIn"==t?a.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+r]=n,n?o?n.u=o.u:(n.u=R,e.addEventListener(t,r?T:z,r)):e.removeEventListener(t,r?T:z,r);else{if("http://www.w3.org/2000/svg"==i)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=t&&"height"!=t&&"href"!=t&&"list"!=t&&"form"!=t&&"tabIndex"!=t&&"download"!=t&&"rowSpan"!=t&&"colSpan"!=t&&"role"!=t&&"popover"!=t&&t in e)try{e[t]=null==n?"":n;break e}catch(e){}"function"==typeof n||(null==n||!1===n&&"-"!=t[4]?e.removeAttribute(t):e.setAttribute(t,"popover"==t&&1==n?"":n))}}function ee(e){return function(t){if(this.l){var n=this.l[t.type+e];if(null==t.t)t.t=R++;else if(t.t0?e:L(e)?e.map(ie):$({},e)}function re(e,t,n,o,i,r,a,s,l){var c,d,u,h,m,g,p,f=n.props||_,v=t.props,y=t.type;if("svg"==y?i="http://www.w3.org/2000/svg":"math"==y?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),null!=r)for(c=0;c=n.__.length&&n.__.push({}),n.__[e]}function Se(e){return pe=1,Me(je,e)}function Me(e,t,n){var o=ke(ue++,2);if(o.t=e,!o.__c&&(o.__=[n?n(t):je(void 0,t),function(e){var t=o.__N?o.__N[0]:o.__[0],n=o.t(t,e);t!==n&&(o.__N=[n,o.__[1]],o.__c.setState({}))}],o.__c=he,!he.__f)){var i=function(e,t,n){if(!o.__c.__H)return!0;var i=o.__c.__H.__.filter(function(e){return!!e.__c});if(i.every(function(e){return!e.__N}))return!r||r.call(this,e,t,n);var a=o.__c.props!==e;return i.forEach(function(e){if(e.__N){var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(a=!0)}}),r&&r.call(this,e,t,n)||a};he.__f=!0;var r=he.shouldComponentUpdate,a=he.componentWillUpdate;he.componentWillUpdate=function(e,t,n){if(this.__e){var o=r;r=void 0,i(e,t,n),r=o}a&&a.call(this,e,t,n)},he.shouldComponentUpdate=i}return o.__N||o.__}function Ae(e,t){var n=ke(ue++,3);!ve.__s&&$e(n.__H,t)&&(n.__=e,n.u=t,he.__H.__h.push(n))}function Pe(e,t){var n=ke(ue++,4);!ve.__s&&$e(n.__H,t)&&(n.__=e,n.u=t,he.__h.push(n))}function De(e){return pe=5,Re(function(){return{current:e}},[])}function Re(e,t){var n=ke(ue++,7);return $e(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function ze(e,t){return pe=8,Re(function(){return e},t)}function Te(e){var t=he.context[e.__c],n=ke(ue++,9);return n.c=e,t?(null==n.__&&(n.__=!0,t.sub(he)),t.props.value):e.__}function Ee(){for(var e;e=fe.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(Oe),e.__H.__h.forEach(Le),e.__H.__h=[]}catch(t){e.__H.__h=[],ve.__e(t,e.__v)}}ve.__b=function(e){he=null,ye&&ye(e)},ve.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Ie&&Ie(e,t)},ve.__r=function(e){be&&be(e),ue=0;var t=(he=e.__c).__H;t&&(me===he?(t.__h=[],he.__h=[],t.__.forEach(function(e){e.__N&&(e.__=e.__N),e.u=e.__N=void 0})):(t.__h.forEach(Oe),t.__h.forEach(Le),t.__h=[],ue=0)),me=he},ve.diffed=function(e){we&&we(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==fe.push(t)&&ge===ve.requestAnimationFrame||((ge=ve.requestAnimationFrame)||Ne)(Ee)),t.__H.__.forEach(function(e){e.u&&(e.__H=e.u),e.u=void 0})),me=he=null},ve.__c=function(e,t){t.some(function(e){try{e.__h.forEach(Oe),e.__h=e.__h.filter(function(e){return!e.__||Le(e)})}catch(n){t.some(function(e){e.__h&&(e.__h=[])}),t=[],ve.__e(n,e.__v)}}),xe&&xe(e,t)},ve.unmount=function(e){Ce&&Ce(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach(function(e){try{Oe(e)}catch(e){t=e}}),n.__H=void 0,t&&ve.__e(t,n.__v))};var _e="function"==typeof requestAnimationFrame;function Ne(e){var t,n=function(){clearTimeout(o),_e&&cancelAnimationFrame(t),setTimeout(e)},o=setTimeout(n,35);_e&&(t=requestAnimationFrame(n))}function Oe(e){var t=he,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),he=t}function Le(e){var t=he;e.__c=e.__(),he=t}function $e(e,t){return!e||e.length!==t.length||t.some(function(t,n){return t!==e[n]})}function je(e,t){return"function"==typeof t?t(e):t}var Fe='/*! tailwindcss v4.1.18 | MIT License | https://tailwindcss.com */\n@layer properties;\n@layer theme, base, components, utilities;\n@layer theme {\n :root, :host {\n --font-sans: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji",\n "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";\n --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono",\n "Courier New", monospace;\n --color-red-500: oklch(63.7% 0.237 25.331);\n --color-yellow-500: oklch(79.5% 0.184 86.047);\n --color-green-500: oklch(72.3% 0.219 149.579);\n --color-teal-500: oklch(70.4% 0.14 182.503);\n --color-blue-500: oklch(62.3% 0.214 259.815);\n --color-indigo-500: oklch(58.5% 0.233 277.117);\n --color-purple-500: oklch(62.7% 0.265 303.9);\n --color-pink-500: oklch(65.6% 0.241 354.308);\n --color-gray-300: oklch(87.2% 0.01 258.338);\n --color-white: #fff;\n --spacing: 0.25rem;\n --container-sm: 24rem;\n --text-xs: 0.75rem;\n --text-xs--line-height: calc(1 / 0.75);\n --text-sm: 0.875rem;\n --text-sm--line-height: calc(1.25 / 0.875);\n --text-base: 1rem;\n --text-base--line-height: calc(1.5 / 1);\n --text-lg: 1.125rem;\n --text-lg--line-height: calc(1.75 / 1.125);\n --text-xl: 1.25rem;\n --text-xl--line-height: calc(1.75 / 1.25);\n --font-weight-medium: 500;\n --font-weight-semibold: 600;\n --font-weight-bold: 700;\n --leading-relaxed: 1.625;\n --radius-md: 0.375rem;\n --radius-lg: 0.5rem;\n --radius-xl: 0.75rem;\n --radius-2xl: 1rem;\n --ease-out: cubic-bezier(0, 0, 0.2, 1);\n --ease-in-out: cubic-bezier(0.4, 0, 0.2, 1);\n --animate-spin: spin 1s linear infinite;\n --animate-pulse: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;\n --default-transition-duration: 150ms;\n --default-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);\n --default-font-family: var(--font-sans);\n --default-mono-font-family: var(--font-mono);\n --color-bg-app: var(--ep-background-app);\n --color-bg-surface: var(--ep-background-surface);\n --color-bg-surface-alt: var(--ep-background-surface-alt);\n --color-bg-elevated: var(--ep-background-elevated);\n --color-bg-overlay: var(--ep-background-overlay);\n --color-bg-input: var(--ep-background-input);\n --color-fg-primary: var(--ep-foreground-primary);\n --color-fg-secondary: var(--ep-foreground-secondary);\n --color-fg-muted: var(--ep-foreground-muted);\n --color-fg-disabled: var(--ep-foreground-disabled);\n --color-fg-on-accent: var(--ep-foreground-on-accent);\n --color-border-default: var(--ep-border-default);\n --color-border-subtle: var(--ep-border-subtle);\n --color-border-strong: var(--ep-border-strong);\n --color-accent: var(--ep-accent-primary);\n --color-accent-hover: var(--ep-accent-primary-hover);\n --color-accent-light: var(--ep-accent-primary-light);\n --color-accent-fg: var(--ep-accent-primary-foreground);\n --color-interactive-hover: var(--ep-interactive-hover);\n --color-interactive-active: var(--ep-interactive-active);\n --color-interactive-selected: var(--ep-interactive-selected);\n --color-interactive-focus-ring: var(--ep-interactive-focus-ring);\n --color-state-error: var(--ep-state-error);\n --color-state-error-light: var(--ep-state-error-light);\n --color-state-warning: var(--ep-state-warning);\n --color-state-warning-light: var(--ep-state-warning-light);\n --color-state-success: var(--ep-state-success);\n --color-state-success-light: var(--ep-state-success-light);\n --color-state-info-light: var(--ep-state-info-light);\n --color-tooltip-bg: var(--ep-tooltip-background);\n --color-tooltip-fg: var(--ep-tooltip-foreground);\n }\n}\n@layer base {\n *, ::after, ::before, ::backdrop, ::file-selector-button {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n border: 0 solid;\n }\n html, :host {\n line-height: 1.5;\n -webkit-text-size-adjust: 100%;\n -moz-tab-size: 4;\n -o-tab-size: 4;\n tab-size: 4;\n font-family: var(--default-font-family, ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");\n font-feature-settings: var(--default-font-feature-settings, normal);\n font-variation-settings: var(--default-font-variation-settings, normal);\n -webkit-tap-highlight-color: transparent;\n }\n hr {\n height: 0;\n color: inherit;\n border-top-width: 1px;\n }\n abbr:where([title]) {\n -webkit-text-decoration: underline dotted;\n text-decoration: underline dotted;\n }\n h1, h2, h3, h4, h5, h6 {\n font-size: inherit;\n font-weight: inherit;\n }\n a {\n color: inherit;\n -webkit-text-decoration: inherit;\n text-decoration: inherit;\n }\n b, strong {\n font-weight: bolder;\n }\n code, kbd, samp, pre {\n font-family: var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);\n font-feature-settings: var(--default-mono-font-feature-settings, normal);\n font-variation-settings: var(--default-mono-font-variation-settings, normal);\n font-size: 1em;\n }\n small {\n font-size: 80%;\n }\n sub, sup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n }\n sub {\n bottom: -0.25em;\n }\n sup {\n top: -0.5em;\n }\n table {\n text-indent: 0;\n border-color: inherit;\n border-collapse: collapse;\n }\n :-moz-focusring {\n outline: auto;\n }\n progress {\n vertical-align: baseline;\n }\n summary {\n display: list-item;\n }\n ol, ul, menu {\n list-style: none;\n }\n img, svg, video, canvas, audio, iframe, embed, object {\n display: block;\n vertical-align: middle;\n }\n img, video {\n max-width: 100%;\n height: auto;\n }\n button, input, select, optgroup, textarea, ::file-selector-button {\n font: inherit;\n font-feature-settings: inherit;\n font-variation-settings: inherit;\n letter-spacing: inherit;\n color: inherit;\n border-radius: 0;\n background-color: transparent;\n opacity: 1;\n }\n :where(select:is([multiple], [size])) optgroup {\n font-weight: bolder;\n }\n :where(select:is([multiple], [size])) optgroup option {\n padding-inline-start: 20px;\n }\n ::file-selector-button {\n margin-inline-end: 4px;\n }\n ::-moz-placeholder {\n opacity: 1;\n }\n ::placeholder {\n opacity: 1;\n }\n @supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) {\n ::-moz-placeholder {\n color: currentcolor;\n @supports (color: color-mix(in lab, red, red)) {\n color: color-mix(in oklab, currentcolor 50%, transparent);\n }\n }\n ::placeholder {\n color: currentcolor;\n @supports (color: color-mix(in lab, red, red)) {\n color: color-mix(in oklab, currentcolor 50%, transparent);\n }\n }\n }\n textarea {\n resize: vertical;\n }\n ::-webkit-search-decoration {\n -webkit-appearance: none;\n }\n ::-webkit-date-and-time-value {\n min-height: 1lh;\n text-align: inherit;\n }\n ::-webkit-datetime-edit {\n display: inline-flex;\n }\n ::-webkit-datetime-edit-fields-wrapper {\n padding: 0;\n }\n ::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field {\n padding-block: 0;\n }\n ::-webkit-calendar-picker-indicator {\n line-height: 1;\n }\n :-moz-ui-invalid {\n box-shadow: none;\n }\n button, input:where([type="button"], [type="reset"], [type="submit"]), ::file-selector-button {\n -webkit-appearance: button;\n -moz-appearance: button;\n appearance: button;\n }\n ::-webkit-inner-spin-button, ::-webkit-outer-spin-button {\n height: auto;\n }\n [hidden]:where(:not([hidden="until-found"])) {\n display: none !important;\n }\n}\n@layer utilities {\n .pointer-events-auto {\n pointer-events: auto;\n }\n .pointer-events-none {\n pointer-events: none;\n }\n .invisible {\n visibility: hidden;\n }\n .visible {\n visibility: visible;\n }\n .absolute {\n position: absolute;\n }\n .fixed {\n position: fixed;\n }\n .relative {\n position: relative;\n }\n .static {\n position: static;\n }\n .sticky {\n position: sticky;\n }\n .inset-0 {\n inset: calc(var(--spacing) * 0);\n }\n .inset-x-0 {\n inset-inline: calc(var(--spacing) * 0);\n }\n .inset-y-0 {\n inset-block: calc(var(--spacing) * 0);\n }\n .top-0 {\n top: calc(var(--spacing) * 0);\n }\n .top-1\\/2 {\n top: calc(1/2 * 100%);\n }\n .top-4 {\n top: calc(var(--spacing) * 4);\n }\n .top-6 {\n top: calc(var(--spacing) * 6);\n }\n .right-0 {\n right: calc(var(--spacing) * 0);\n }\n .right-1 {\n right: calc(var(--spacing) * 1);\n }\n .right-2 {\n right: calc(var(--spacing) * 2);\n }\n .right-4 {\n right: calc(var(--spacing) * 4);\n }\n .bottom-0 {\n bottom: calc(var(--spacing) * 0);\n }\n .left-0 {\n left: calc(var(--spacing) * 0);\n }\n .left-1\\/2 {\n left: calc(1/2 * 100%);\n }\n .z-3 {\n z-index: 3;\n }\n .z-10 {\n z-index: 10;\n }\n .z-40 {\n z-index: 40;\n }\n .z-50 {\n z-index: 50;\n }\n .z-100 {\n z-index: 100;\n }\n .col-start-1 {\n grid-column-start: 1;\n }\n .row-start-1 {\n grid-row-start: 1;\n }\n .container {\n width: 100%;\n @media (width >= 40rem) {\n max-width: 40rem;\n }\n @media (width >= 48rem) {\n max-width: 48rem;\n }\n @media (width >= 64rem) {\n max-width: 64rem;\n }\n @media (width >= 80rem) {\n max-width: 80rem;\n }\n @media (width >= 96rem) {\n max-width: 96rem;\n }\n }\n .mx-4 {\n margin-inline: calc(var(--spacing) * 4);\n }\n .my-2 {\n margin-block: calc(var(--spacing) * 2);\n }\n .my-4 {\n margin-block: calc(var(--spacing) * 4);\n }\n .-mt-1 {\n margin-top: calc(var(--spacing) * -1);\n }\n .mt-0\\.5 {\n margin-top: calc(var(--spacing) * 0.5);\n }\n .mt-1 {\n margin-top: calc(var(--spacing) * 1);\n }\n .mt-2 {\n margin-top: calc(var(--spacing) * 2);\n }\n .mt-3 {\n margin-top: calc(var(--spacing) * 3);\n }\n .mt-4 {\n margin-top: calc(var(--spacing) * 4);\n }\n .mt-5 {\n margin-top: calc(var(--spacing) * 5);\n }\n .mt-6 {\n margin-top: calc(var(--spacing) * 6);\n }\n .-mr-1 {\n margin-right: calc(var(--spacing) * -1);\n }\n .mr-1\\.5 {\n margin-right: calc(var(--spacing) * 1.5);\n }\n .mr-2 {\n margin-right: calc(var(--spacing) * 2);\n }\n .mr-3 {\n margin-right: calc(var(--spacing) * 3);\n }\n .mr-4 {\n margin-right: calc(var(--spacing) * 4);\n }\n .mb-1 {\n margin-bottom: calc(var(--spacing) * 1);\n }\n .mb-1\\.5 {\n margin-bottom: calc(var(--spacing) * 1.5);\n }\n .mb-2 {\n margin-bottom: calc(var(--spacing) * 2);\n }\n .mb-3 {\n margin-bottom: calc(var(--spacing) * 3);\n }\n .mb-4 {\n margin-bottom: calc(var(--spacing) * 4);\n }\n .mb-6 {\n margin-bottom: calc(var(--spacing) * 6);\n }\n .ml-1 {\n margin-left: calc(var(--spacing) * 1);\n }\n .block {\n display: block;\n }\n .contents {\n display: contents;\n }\n .flex {\n display: flex;\n }\n .grid {\n display: grid;\n }\n .hidden {\n display: none;\n }\n .inline {\n display: inline;\n }\n .inline-block {\n display: inline-block;\n }\n .inline-flex {\n display: inline-flex;\n }\n .h-1 {\n height: calc(var(--spacing) * 1);\n }\n .h-1\\.5 {\n height: calc(var(--spacing) * 1.5);\n }\n .h-2 {\n height: calc(var(--spacing) * 2);\n }\n .h-3 {\n height: calc(var(--spacing) * 3);\n }\n .h-3\\.5 {\n height: calc(var(--spacing) * 3.5);\n }\n .h-4 {\n height: calc(var(--spacing) * 4);\n }\n .h-5 {\n height: calc(var(--spacing) * 5);\n }\n .h-6 {\n height: calc(var(--spacing) * 6);\n }\n .h-7 {\n height: calc(var(--spacing) * 7);\n }\n .h-8 {\n height: calc(var(--spacing) * 8);\n }\n .h-9 {\n height: calc(var(--spacing) * 9);\n }\n .h-10 {\n height: calc(var(--spacing) * 10);\n }\n .h-16 {\n height: calc(var(--spacing) * 16);\n }\n .h-18 {\n height: calc(var(--spacing) * 18);\n }\n .h-\\[32px\\] {\n height: 32px;\n }\n .h-full {\n height: 100%;\n }\n .h-px {\n height: 1px;\n }\n .max-h-48 {\n max-height: calc(var(--spacing) * 48);\n }\n .max-h-60 {\n max-height: calc(var(--spacing) * 60);\n }\n .min-h-0 {\n min-height: calc(var(--spacing) * 0);\n }\n .\\!w-full {\n width: 100% !important;\n }\n .w-2 {\n width: calc(var(--spacing) * 2);\n }\n .w-3 {\n width: calc(var(--spacing) * 3);\n }\n .w-3\\.5 {\n width: calc(var(--spacing) * 3.5);\n }\n .w-4 {\n width: calc(var(--spacing) * 4);\n }\n .w-5 {\n width: calc(var(--spacing) * 5);\n }\n .w-6 {\n width: calc(var(--spacing) * 6);\n }\n .w-8 {\n width: calc(var(--spacing) * 8);\n }\n .w-9 {\n width: calc(var(--spacing) * 9);\n }\n .w-10 {\n width: calc(var(--spacing) * 10);\n }\n .w-12 {\n width: calc(var(--spacing) * 12);\n }\n .w-16 {\n width: calc(var(--spacing) * 16);\n }\n .w-18 {\n width: calc(var(--spacing) * 18);\n }\n .w-32 {\n width: calc(var(--spacing) * 32);\n }\n .w-\\[32px\\] {\n width: 32px;\n }\n .w-auto {\n width: auto;\n }\n .w-full {\n width: 100%;\n }\n .w-px {\n width: 1px;\n }\n .max-w-\\[150px\\] {\n max-width: 150px;\n }\n .max-w-\\[240px\\] {\n max-width: 240px;\n }\n .max-w-sm {\n max-width: var(--container-sm);\n }\n .min-w-0 {\n min-width: calc(var(--spacing) * 0);\n }\n .min-w-\\[8rem\\] {\n min-width: 8rem;\n }\n .min-w-\\[32px\\] {\n min-width: 32px;\n }\n .min-w-\\[120px\\] {\n min-width: 120px;\n }\n .min-w-\\[200px\\] {\n min-width: 200px;\n }\n .flex-1 {\n flex: 1;\n }\n .flex-shrink-0 {\n flex-shrink: 0;\n }\n .shrink-0 {\n flex-shrink: 0;\n }\n .-translate-x-1\\/2 {\n --tw-translate-x: calc(calc(1/2 * 100%) * -1);\n translate: var(--tw-translate-x) var(--tw-translate-y);\n }\n .translate-x-\\[1px\\] {\n --tw-translate-x: 1px;\n translate: var(--tw-translate-x) var(--tw-translate-y);\n }\n .-translate-y-1\\/2 {\n --tw-translate-y: calc(calc(1/2 * 100%) * -1);\n translate: var(--tw-translate-x) var(--tw-translate-y);\n }\n .translate-y-\\[1px\\] {\n --tw-translate-y: 1px;\n translate: var(--tw-translate-x) var(--tw-translate-y);\n }\n .scale-95 {\n --tw-scale-x: 95%;\n --tw-scale-y: 95%;\n --tw-scale-z: 95%;\n scale: var(--tw-scale-x) var(--tw-scale-y);\n }\n .scale-100 {\n --tw-scale-x: 100%;\n --tw-scale-y: 100%;\n --tw-scale-z: 100%;\n scale: var(--tw-scale-x) var(--tw-scale-y);\n }\n .rotate-45 {\n rotate: 45deg;\n }\n .transform {\n transform: var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,);\n }\n .animate-pulse {\n animation: var(--animate-pulse);\n }\n .animate-spin {\n animation: var(--animate-spin);\n }\n .cursor-default {\n cursor: default;\n }\n .cursor-grab {\n cursor: grab;\n }\n .cursor-not-allowed {\n cursor: not-allowed;\n }\n .cursor-pointer {\n cursor: pointer;\n }\n .touch-none {\n touch-action: none;\n }\n .resize {\n resize: both;\n }\n .appearance-none {\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n }\n .grid-cols-1 {\n grid-template-columns: repeat(1, minmax(0, 1fr));\n }\n .grid-cols-2 {\n grid-template-columns: repeat(2, minmax(0, 1fr));\n }\n .grid-cols-6 {\n grid-template-columns: repeat(6, minmax(0, 1fr));\n }\n .flex-col {\n flex-direction: column;\n }\n .flex-row {\n flex-direction: row;\n }\n .flex-wrap {\n flex-wrap: wrap;\n }\n .items-center {\n align-items: center;\n }\n .items-end {\n align-items: flex-end;\n }\n .items-start {\n align-items: flex-start;\n }\n .justify-between {\n justify-content: space-between;\n }\n .justify-center {\n justify-content: center;\n }\n .justify-end {\n justify-content: flex-end;\n }\n .justify-start {\n justify-content: flex-start;\n }\n .gap-1 {\n gap: calc(var(--spacing) * 1);\n }\n .gap-2 {\n gap: calc(var(--spacing) * 2);\n }\n .gap-3 {\n gap: calc(var(--spacing) * 3);\n }\n .gap-4 {\n gap: calc(var(--spacing) * 4);\n }\n .space-y-2 {\n :where(& > :not(:last-child)) {\n --tw-space-y-reverse: 0;\n margin-block-start: calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));\n margin-block-end: calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)));\n }\n }\n .space-y-3 {\n :where(& > :not(:last-child)) {\n --tw-space-y-reverse: 0;\n margin-block-start: calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));\n margin-block-end: calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)));\n }\n }\n .space-y-4 {\n :where(& > :not(:last-child)) {\n --tw-space-y-reverse: 0;\n margin-block-start: calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));\n margin-block-end: calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)));\n }\n }\n .space-y-5 {\n :where(& > :not(:last-child)) {\n --tw-space-y-reverse: 0;\n margin-block-start: calc(calc(var(--spacing) * 5) * var(--tw-space-y-reverse));\n margin-block-end: calc(calc(var(--spacing) * 5) * calc(1 - var(--tw-space-y-reverse)));\n }\n }\n .space-y-6 {\n :where(& > :not(:last-child)) {\n --tw-space-y-reverse: 0;\n margin-block-start: calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));\n margin-block-end: calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)));\n }\n }\n .gap-x-1 {\n -moz-column-gap: calc(var(--spacing) * 1);\n column-gap: calc(var(--spacing) * 1);\n }\n .space-x-2 {\n :where(& > :not(:last-child)) {\n --tw-space-x-reverse: 0;\n margin-inline-start: calc(calc(var(--spacing) * 2) * var(--tw-space-x-reverse));\n margin-inline-end: calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-x-reverse)));\n }\n }\n .space-x-3 {\n :where(& > :not(:last-child)) {\n --tw-space-x-reverse: 0;\n margin-inline-start: calc(calc(var(--spacing) * 3) * var(--tw-space-x-reverse));\n margin-inline-end: calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-x-reverse)));\n }\n }\n .gap-y-4 {\n row-gap: calc(var(--spacing) * 4);\n }\n .divide-y {\n :where(& > :not(:last-child)) {\n --tw-divide-y-reverse: 0;\n border-bottom-style: var(--tw-border-style);\n border-top-style: var(--tw-border-style);\n border-top-width: calc(1px * var(--tw-divide-y-reverse));\n border-bottom-width: calc(1px * calc(1 - var(--tw-divide-y-reverse)));\n }\n }\n .divide-border-subtle {\n :where(& > :not(:last-child)) {\n border-color: var(--color-border-subtle);\n }\n }\n .truncate {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n .overflow-auto {\n overflow: auto;\n }\n .overflow-hidden {\n overflow: hidden;\n }\n .overflow-x-auto {\n overflow-x: auto;\n }\n .overflow-y-auto {\n overflow-y: auto;\n }\n .rounded {\n border-radius: 0.25rem;\n }\n .rounded-\\[3px\\] {\n border-radius: 3px;\n }\n .rounded-full {\n border-radius: calc(infinity * 1px);\n }\n .rounded-lg {\n border-radius: var(--radius-lg);\n }\n .rounded-md {\n border-radius: var(--radius-md);\n }\n .rounded-none {\n border-radius: 0;\n }\n .rounded-xl {\n border-radius: var(--radius-xl);\n }\n .rounded-t-2xl {\n border-top-left-radius: var(--radius-2xl);\n border-top-right-radius: var(--radius-2xl);\n }\n .rounded-t-lg {\n border-top-left-radius: var(--radius-lg);\n border-top-right-radius: var(--radius-lg);\n }\n .rounded-l-md {\n border-top-left-radius: var(--radius-md);\n border-bottom-left-radius: var(--radius-md);\n }\n .rounded-r-md {\n border-top-right-radius: var(--radius-md);\n border-bottom-right-radius: var(--radius-md);\n }\n .border {\n border-style: var(--tw-border-style);\n border-width: 1px;\n }\n .border-0 {\n border-style: var(--tw-border-style);\n border-width: 0px;\n }\n .border-2 {\n border-style: var(--tw-border-style);\n border-width: 2px;\n }\n .border-3 {\n border-style: var(--tw-border-style);\n border-width: 3px;\n }\n .border-4 {\n border-style: var(--tw-border-style);\n border-width: 4px;\n }\n .border-t {\n border-top-style: var(--tw-border-style);\n border-top-width: 1px;\n }\n .border-r {\n border-right-style: var(--tw-border-style);\n border-right-width: 1px;\n }\n .border-r-0 {\n border-right-style: var(--tw-border-style);\n border-right-width: 0px;\n }\n .border-b {\n border-bottom-style: var(--tw-border-style);\n border-bottom-width: 1px;\n }\n .border-b-2 {\n border-bottom-style: var(--tw-border-style);\n border-bottom-width: 2px;\n }\n .border-l {\n border-left-style: var(--tw-border-style);\n border-left-width: 1px;\n }\n .border-none {\n --tw-border-style: none;\n border-style: none;\n }\n .border-\\[\\#cfd4da\\] {\n border-color: #cfd4da;\n }\n .border-accent {\n border-color: var(--color-accent);\n }\n .border-border-default {\n border-color: var(--color-border-default);\n }\n .border-border-strong {\n border-color: var(--color-border-strong);\n }\n .border-border-subtle {\n border-color: var(--color-border-subtle);\n }\n .border-gray-300 {\n border-color: var(--color-gray-300);\n }\n .border-state-error {\n border-color: var(--color-state-error);\n }\n .border-transparent {\n border-color: transparent;\n }\n .border-t-accent {\n border-top-color: var(--color-accent);\n }\n .border-r-accent {\n border-right-color: var(--color-accent);\n }\n .border-b-accent {\n border-bottom-color: var(--color-accent);\n }\n .border-b-transparent {\n border-bottom-color: transparent;\n }\n .bg-\\[\\#f8f9fa\\] {\n background-color: #f8f9fa;\n }\n .bg-accent {\n background-color: var(--color-accent);\n }\n .bg-accent-light {\n background-color: var(--color-accent-light);\n }\n .bg-accent\\/10 {\n background-color: var(--color-accent);\n @supports (color: color-mix(in lab, red, red)) {\n background-color: color-mix(in oklab, var(--color-accent) 10%, transparent);\n }\n }\n .bg-bg-app {\n background-color: var(--color-bg-app);\n }\n .bg-bg-elevated {\n background-color: var(--color-bg-elevated);\n }\n .bg-bg-input {\n background-color: var(--color-bg-input);\n }\n .bg-bg-overlay {\n background-color: var(--color-bg-overlay);\n }\n .bg-bg-surface {\n background-color: var(--color-bg-surface);\n }\n .bg-bg-surface-alt {\n background-color: var(--color-bg-surface-alt);\n }\n .bg-bg-surface\\/80 {\n background-color: var(--color-bg-surface);\n @supports (color: color-mix(in lab, red, red)) {\n background-color: color-mix(in oklab, var(--color-bg-surface) 80%, transparent);\n }\n }\n .bg-blue-500 {\n background-color: var(--color-blue-500);\n }\n .bg-border-default {\n background-color: var(--color-border-default);\n }\n .bg-border-subtle {\n background-color: var(--color-border-subtle);\n }\n .bg-green-500 {\n background-color: var(--color-green-500);\n }\n .bg-indigo-500 {\n background-color: var(--color-indigo-500);\n }\n .bg-inherit {\n background-color: inherit;\n }\n .bg-interactive-hover {\n background-color: var(--color-interactive-hover);\n }\n .bg-interactive-selected {\n background-color: var(--color-interactive-selected);\n }\n .bg-pink-500 {\n background-color: var(--color-pink-500);\n }\n .bg-purple-500 {\n background-color: var(--color-purple-500);\n }\n .bg-red-500 {\n background-color: var(--color-red-500);\n }\n .bg-state-error {\n background-color: var(--color-state-error);\n }\n .bg-state-error-light {\n background-color: var(--color-state-error-light);\n }\n .bg-state-info-light {\n background-color: var(--color-state-info-light);\n }\n .bg-state-success-light {\n background-color: var(--color-state-success-light);\n }\n .bg-state-warning-light {\n background-color: var(--color-state-warning-light);\n }\n .bg-teal-500 {\n background-color: var(--color-teal-500);\n }\n .bg-tooltip-bg {\n background-color: var(--color-tooltip-bg);\n }\n .bg-transparent {\n background-color: transparent;\n }\n .bg-white {\n background-color: var(--color-white);\n }\n .bg-yellow-500 {\n background-color: var(--color-yellow-500);\n }\n .p-0 {\n padding: calc(var(--spacing) * 0);\n }\n .p-1 {\n padding: calc(var(--spacing) * 1);\n }\n .p-1\\.5 {\n padding: calc(var(--spacing) * 1.5);\n }\n .p-2 {\n padding: calc(var(--spacing) * 2);\n }\n .p-3 {\n padding: calc(var(--spacing) * 3);\n }\n .p-4 {\n padding: calc(var(--spacing) * 4);\n }\n .p-5 {\n padding: calc(var(--spacing) * 5);\n }\n .p-6 {\n padding: calc(var(--spacing) * 6);\n }\n .p-8 {\n padding: calc(var(--spacing) * 8);\n }\n .p-\\[5px\\] {\n padding: 5px;\n }\n .px-1 {\n padding-inline: calc(var(--spacing) * 1);\n }\n .px-2 {\n padding-inline: calc(var(--spacing) * 2);\n }\n .px-3 {\n padding-inline: calc(var(--spacing) * 3);\n }\n .px-4 {\n padding-inline: calc(var(--spacing) * 4);\n }\n .px-5 {\n padding-inline: calc(var(--spacing) * 5);\n }\n .px-6 {\n padding-inline: calc(var(--spacing) * 6);\n }\n .py-1 {\n padding-block: calc(var(--spacing) * 1);\n }\n .py-1\\.5 {\n padding-block: calc(var(--spacing) * 1.5);\n }\n .py-2 {\n padding-block: calc(var(--spacing) * 2);\n }\n .py-2\\.5 {\n padding-block: calc(var(--spacing) * 2.5);\n }\n .py-3 {\n padding-block: calc(var(--spacing) * 3);\n }\n .py-4 {\n padding-block: calc(var(--spacing) * 4);\n }\n .pt-2 {\n padding-top: calc(var(--spacing) * 2);\n }\n .pt-4 {\n padding-top: calc(var(--spacing) * 4);\n }\n .pr-2 {\n padding-right: calc(var(--spacing) * 2);\n }\n .pr-3 {\n padding-right: calc(var(--spacing) * 3);\n }\n .pr-6 {\n padding-right: calc(var(--spacing) * 6);\n }\n .pr-7 {\n padding-right: calc(var(--spacing) * 7);\n }\n .pr-9 {\n padding-right: calc(var(--spacing) * 9);\n }\n .pr-10 {\n padding-right: calc(var(--spacing) * 10);\n }\n .pb-3 {\n padding-bottom: calc(var(--spacing) * 3);\n }\n .pb-4 {\n padding-bottom: calc(var(--spacing) * 4);\n }\n .pl-2 {\n padding-left: calc(var(--spacing) * 2);\n }\n .pl-3 {\n padding-left: calc(var(--spacing) * 3);\n }\n .pl-4 {\n padding-left: calc(var(--spacing) * 4);\n }\n .pl-6 {\n padding-left: calc(var(--spacing) * 6);\n }\n .pl-8 {\n padding-left: calc(var(--spacing) * 8);\n }\n .text-center {\n text-align: center;\n }\n .text-left {\n text-align: left;\n }\n .text-right {\n text-align: right;\n }\n .text-base {\n font-size: var(--text-base);\n line-height: var(--tw-leading, var(--text-base--line-height));\n }\n .text-lg {\n font-size: var(--text-lg);\n line-height: var(--tw-leading, var(--text-lg--line-height));\n }\n .text-sm {\n font-size: var(--text-sm);\n line-height: var(--tw-leading, var(--text-sm--line-height));\n }\n .text-xl {\n font-size: var(--text-xl);\n line-height: var(--tw-leading, var(--text-xl--line-height));\n }\n .text-xs {\n font-size: var(--text-xs);\n line-height: var(--tw-leading, var(--text-xs--line-height));\n }\n .text-\\[13px\\] {\n font-size: 13px;\n }\n .leading-none {\n --tw-leading: 1;\n line-height: 1;\n }\n .leading-relaxed {\n --tw-leading: var(--leading-relaxed);\n line-height: var(--leading-relaxed);\n }\n .font-bold {\n --tw-font-weight: var(--font-weight-bold);\n font-weight: var(--font-weight-bold);\n }\n .font-medium {\n --tw-font-weight: var(--font-weight-medium);\n font-weight: var(--font-weight-medium);\n }\n .font-semibold {\n --tw-font-weight: var(--font-weight-semibold);\n font-weight: var(--font-weight-semibold);\n }\n .whitespace-nowrap {\n white-space: nowrap;\n }\n .text-accent {\n color: var(--color-accent);\n }\n .text-accent-fg {\n color: var(--color-accent-fg);\n }\n .text-fg-disabled {\n color: var(--color-fg-disabled);\n }\n .text-fg-muted {\n color: var(--color-fg-muted);\n }\n .text-fg-on-accent {\n color: var(--color-fg-on-accent);\n }\n .text-fg-primary {\n color: var(--color-fg-primary);\n }\n .text-fg-secondary {\n color: var(--color-fg-secondary);\n }\n .text-state-error {\n color: var(--color-state-error);\n }\n .text-state-success {\n color: var(--color-state-success);\n }\n .text-state-warning {\n color: var(--color-state-warning);\n }\n .text-tooltip-fg {\n color: var(--color-tooltip-fg);\n }\n .text-white {\n color: var(--color-white);\n }\n .uppercase {\n text-transform: uppercase;\n }\n .italic {\n font-style: italic;\n }\n .underline {\n text-decoration-line: underline;\n }\n .placeholder-fg-muted {\n &::-moz-placeholder {\n color: var(--color-fg-muted);\n }\n &::placeholder {\n color: var(--color-fg-muted);\n }\n }\n .accent-accent {\n accent-color: var(--color-accent);\n }\n .opacity-0 {\n opacity: 0%;\n }\n .opacity-50 {\n opacity: 50%;\n }\n .opacity-100 {\n opacity: 100%;\n }\n .shadow {\n --tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n .shadow-2xl {\n --tw-shadow: 0 25px 50px -12px var(--tw-shadow-color, rgb(0 0 0 / 0.25));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n .shadow-lg {\n --tw-shadow: 0 10px 15px -3px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 4px 6px -4px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n .shadow-md {\n --tw-shadow: 0 4px 6px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 2px 4px -2px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n .shadow-sm {\n --tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n .ring {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n .ring-1 {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n .ring-2 {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n .ring-accent {\n --tw-ring-color: var(--color-accent);\n }\n .ring-border-default {\n --tw-ring-color: var(--color-border-default);\n }\n .ring-interactive-focus-ring {\n --tw-ring-color: var(--color-interactive-focus-ring);\n }\n .outline {\n outline-style: var(--tw-outline-style);\n outline-width: 1px;\n }\n .outline-1 {\n outline-style: var(--tw-outline-style);\n outline-width: 1px;\n }\n .outline-2 {\n outline-style: var(--tw-outline-style);\n outline-width: 2px;\n }\n .-outline-offset-1 {\n outline-offset: calc(1px * -1);\n }\n .outline-offset-2 {\n outline-offset: 2px;\n }\n .outline-accent {\n outline-color: var(--color-accent);\n }\n .outline-border-default {\n outline-color: var(--color-border-default);\n }\n .backdrop-blur {\n --tw-backdrop-blur: blur(8px);\n backdrop-filter: var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);\n }\n .transition {\n transition-property: color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, --tw-gradient-from, --tw-gradient-via, --tw-gradient-to, opacity, box-shadow, transform, translate, scale, rotate, filter, backdrop-filter, display, content-visibility, overlay, pointer-events;\n transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));\n transition-duration: var(--tw-duration, var(--default-transition-duration));\n }\n .transition-\\[height\\] {\n transition-property: height;\n transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));\n transition-duration: var(--tw-duration, var(--default-transition-duration));\n }\n .transition-all {\n transition-property: all;\n transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));\n transition-duration: var(--tw-duration, var(--default-transition-duration));\n }\n .transition-colors {\n transition-property: color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, --tw-gradient-from, --tw-gradient-via, --tw-gradient-to;\n transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));\n transition-duration: var(--tw-duration, var(--default-transition-duration));\n }\n .transition-opacity {\n transition-property: opacity;\n transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));\n transition-duration: var(--tw-duration, var(--default-transition-duration));\n }\n .transition-transform {\n transition-property: transform, translate, scale, rotate;\n transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));\n transition-duration: var(--tw-duration, var(--default-transition-duration));\n }\n .duration-150 {\n --tw-duration: 150ms;\n transition-duration: 150ms;\n }\n .duration-200 {\n --tw-duration: 200ms;\n transition-duration: 200ms;\n }\n .duration-300 {\n --tw-duration: 300ms;\n transition-duration: 300ms;\n }\n .ease-in-out {\n --tw-ease: var(--ease-in-out);\n transition-timing-function: var(--ease-in-out);\n }\n .ease-out {\n --tw-ease: var(--ease-out);\n transition-timing-function: var(--ease-out);\n }\n .outline-none {\n --tw-outline-style: none;\n outline-style: none;\n }\n .select-none {\n -webkit-user-select: none;\n -moz-user-select: none;\n user-select: none;\n }\n .group-hover\\:opacity-100 {\n &:is(:where(.group):hover *) {\n @media (hover: hover) {\n opacity: 100%;\n }\n }\n }\n .peer-checked\\:opacity-100 {\n &:is(:where(.peer):checked ~ *) {\n opacity: 100%;\n }\n }\n .placeholder\\:text-fg-muted {\n &::-moz-placeholder {\n color: var(--color-fg-muted);\n }\n &::placeholder {\n color: var(--color-fg-muted);\n }\n }\n .first\\:mt-0 {\n &:first-child {\n margin-top: calc(var(--spacing) * 0);\n }\n }\n .checked\\:border-accent {\n &:checked {\n border-color: var(--color-accent);\n }\n }\n .checked\\:bg-accent {\n &:checked {\n background-color: var(--color-accent);\n }\n }\n .hover\\:border-accent {\n &:hover {\n @media (hover: hover) {\n border-color: var(--color-accent);\n }\n }\n }\n .hover\\:border-state-error {\n &:hover {\n @media (hover: hover) {\n border-color: var(--color-state-error);\n }\n }\n }\n .hover\\:border-b-accent {\n &:hover {\n @media (hover: hover) {\n border-bottom-color: var(--color-accent);\n }\n }\n }\n .hover\\:border-b-fg-muted {\n &:hover {\n @media (hover: hover) {\n border-bottom-color: var(--color-fg-muted);\n }\n }\n }\n .hover\\:\\!bg-accent-hover {\n &:hover {\n @media (hover: hover) {\n background-color: var(--color-accent-hover) !important;\n }\n }\n }\n .hover\\:bg-accent {\n &:hover {\n @media (hover: hover) {\n background-color: var(--color-accent);\n }\n }\n }\n .hover\\:bg-accent-hover {\n &:hover {\n @media (hover: hover) {\n background-color: var(--color-accent-hover);\n }\n }\n }\n .hover\\:bg-bg-surface {\n &:hover {\n @media (hover: hover) {\n background-color: var(--color-bg-surface);\n }\n }\n }\n .hover\\:bg-border-default {\n &:hover {\n @media (hover: hover) {\n background-color: var(--color-border-default);\n }\n }\n }\n .hover\\:bg-interactive-hover {\n &:hover {\n @media (hover: hover) {\n background-color: var(--color-interactive-hover);\n }\n }\n }\n .hover\\:bg-state-error-light {\n &:hover {\n @media (hover: hover) {\n background-color: var(--color-state-error-light);\n }\n }\n }\n .hover\\:bg-state-error\\/90 {\n &:hover {\n @media (hover: hover) {\n background-color: var(--color-state-error);\n @supports (color: color-mix(in lab, red, red)) {\n background-color: color-mix(in oklab, var(--color-state-error) 90%, transparent);\n }\n }\n }\n }\n .hover\\:bg-transparent {\n &:hover {\n @media (hover: hover) {\n background-color: transparent;\n }\n }\n }\n .hover\\:text-accent-hover {\n &:hover {\n @media (hover: hover) {\n color: var(--color-accent-hover);\n }\n }\n }\n .hover\\:text-fg-on-accent {\n &:hover {\n @media (hover: hover) {\n color: var(--color-fg-on-accent);\n }\n }\n }\n .hover\\:text-fg-primary {\n &:hover {\n @media (hover: hover) {\n color: var(--color-fg-primary);\n }\n }\n }\n .hover\\:text-fg-secondary {\n &:hover {\n @media (hover: hover) {\n color: var(--color-fg-secondary);\n }\n }\n }\n .hover\\:shadow-md {\n &:hover {\n @media (hover: hover) {\n --tw-shadow: 0 4px 6px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 2px 4px -2px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n }\n }\n .hover\\:ring {\n &:hover {\n @media (hover: hover) {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n }\n }\n .hover\\:ring-0 {\n &:hover {\n @media (hover: hover) {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n }\n }\n .hover\\:ring-accent {\n &:hover {\n @media (hover: hover) {\n --tw-ring-color: var(--color-accent);\n }\n }\n }\n .hover\\:ring-transparent {\n &:hover {\n @media (hover: hover) {\n --tw-ring-color: transparent;\n }\n }\n }\n .focus\\:border-accent {\n &:focus {\n border-color: var(--color-accent);\n }\n }\n .focus\\:border-blue-500 {\n &:focus {\n border-color: var(--color-blue-500);\n }\n }\n .focus\\:border-state-error {\n &:focus {\n border-color: var(--color-state-error);\n }\n }\n .focus\\:border-transparent {\n &:focus {\n border-color: transparent;\n }\n }\n .focus\\:ring-1 {\n &:focus {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n }\n .focus\\:ring-2 {\n &:focus {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n }\n .focus\\:ring-accent {\n &:focus {\n --tw-ring-color: var(--color-accent);\n }\n }\n .focus\\:ring-blue-500 {\n &:focus {\n --tw-ring-color: var(--color-blue-500);\n }\n }\n .focus\\:outline-none {\n &:focus {\n --tw-outline-style: none;\n outline-style: none;\n }\n }\n .active\\:cursor-grabbing {\n &:active {\n cursor: grabbing;\n }\n }\n .active\\:bg-interactive-active {\n &:active {\n background-color: var(--color-interactive-active);\n }\n }\n .disabled\\:cursor-not-allowed {\n &:disabled {\n cursor: not-allowed;\n }\n }\n .disabled\\:opacity-40 {\n &:disabled {\n opacity: 40%;\n }\n }\n .disabled\\:opacity-50 {\n &:disabled {\n opacity: 50%;\n }\n }\n .disabled\\:hover\\:bg-transparent {\n &:disabled {\n &:hover {\n @media (hover: hover) {\n background-color: transparent;\n }\n }\n }\n }\n .disabled\\:hover\\:ring-0 {\n &:disabled {\n &:hover {\n @media (hover: hover) {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n }\n }\n }\n .sm\\:grid-cols-2 {\n @media (width >= 40rem) {\n grid-template-columns: repeat(2, minmax(0, 1fr));\n }\n }\n .md\\:flex {\n @media (width >= 48rem) {\n display: flex;\n }\n }\n .md\\:h-auto {\n @media (width >= 48rem) {\n height: auto;\n }\n }\n .md\\:max-h-\\[80vh\\] {\n @media (width >= 48rem) {\n max-height: 80vh;\n }\n }\n .md\\:w-\\[28rem\\] {\n @media (width >= 48rem) {\n width: 28rem;\n }\n }\n .md\\:w-\\[32rem\\] {\n @media (width >= 48rem) {\n width: 32rem;\n }\n }\n .md\\:w-\\[36rem\\] {\n @media (width >= 48rem) {\n width: 36rem;\n }\n }\n .md\\:w-\\[48rem\\] {\n @media (width >= 48rem) {\n width: 48rem;\n }\n }\n .md\\:max-w-\\[90vw\\] {\n @media (width >= 48rem) {\n max-width: 90vw;\n }\n }\n .md\\:flex-none {\n @media (width >= 48rem) {\n flex: none;\n }\n }\n .md\\:items-center {\n @media (width >= 48rem) {\n align-items: center;\n }\n }\n .md\\:justify-center {\n @media (width >= 48rem) {\n justify-content: center;\n }\n }\n .md\\:rounded-lg {\n @media (width >= 48rem) {\n border-radius: var(--radius-lg);\n }\n }\n .md\\:border {\n @media (width >= 48rem) {\n border-style: var(--tw-border-style);\n border-width: 1px;\n }\n }\n .md\\:border-border-subtle {\n @media (width >= 48rem) {\n border-color: var(--color-border-subtle);\n }\n }\n .md\\:shadow-lg {\n @media (width >= 48rem) {\n --tw-shadow: 0 10px 15px -3px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 4px 6px -4px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n }\n}\n@import url(\'https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600&display=swap\');\n:host {\n --tw-translate-x: 0;\n --tw-translate-y: 0;\n --tw-translate-z: 0;\n --tw-rotate-x: rotateX(0);\n --tw-rotate-y: rotateY(0);\n --tw-rotate-z: rotateZ(0);\n --tw-skew-x: skewX(0);\n --tw-skew-y: skewY(0);\n --tw-border-style: solid;\n --tw-gradient-from: #0000;\n --tw-gradient-via: #0000;\n --tw-gradient-to: #0000;\n --tw-gradient-from-position: 0%;\n --tw-gradient-via-position: 50%;\n --tw-gradient-to-position: 100%;\n --tw-shadow: 0 0 #0000;\n --tw-inset-shadow: 0 0 #0000;\n --tw-ring-shadow: 0 0 #0000;\n --tw-inset-ring-shadow: 0 0 #0000;\n --tw-ring-offset-width: 0px;\n --tw-ring-offset-color: #fff;\n --tw-ring-offset-shadow: 0 0 #0000;\n --tw-outline-style: solid;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n width: 100%;\n height: 100%;\n font-family: \'Open Sans\', system-ui, sans-serif;\n color: var(--ep-foreground-primary);\n background-color: var(--ep-background-surface);\n}\n:host *::-webkit-scrollbar {\n width: 8px;\n height: 8px;\n}\n:host *::-webkit-scrollbar-track {\n background: var(--ep-scrollbar-track);\n}\n:host *::-webkit-scrollbar-thumb {\n background: var(--ep-scrollbar-thumb);\n border-radius: 4px;\n}\n:host *::-webkit-scrollbar-thumb:hover {\n background: var(--ep-scrollbar-thumb-hover);\n}\n@property --tw-translate-x {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-translate-y {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-translate-z {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-scale-x {\n syntax: "*";\n inherits: false;\n initial-value: 1;\n}\n@property --tw-scale-y {\n syntax: "*";\n inherits: false;\n initial-value: 1;\n}\n@property --tw-scale-z {\n syntax: "*";\n inherits: false;\n initial-value: 1;\n}\n@property --tw-rotate-x {\n syntax: "*";\n inherits: false;\n}\n@property --tw-rotate-y {\n syntax: "*";\n inherits: false;\n}\n@property --tw-rotate-z {\n syntax: "*";\n inherits: false;\n}\n@property --tw-skew-x {\n syntax: "*";\n inherits: false;\n}\n@property --tw-skew-y {\n syntax: "*";\n inherits: false;\n}\n@property --tw-space-y-reverse {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-space-x-reverse {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-divide-y-reverse {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-border-style {\n syntax: "*";\n inherits: false;\n initial-value: solid;\n}\n@property --tw-leading {\n syntax: "*";\n inherits: false;\n}\n@property --tw-font-weight {\n syntax: "*";\n inherits: false;\n}\n@property --tw-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-shadow-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-shadow-alpha {\n syntax: "";\n inherits: false;\n initial-value: 100%;\n}\n@property --tw-inset-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-inset-shadow-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-inset-shadow-alpha {\n syntax: "";\n inherits: false;\n initial-value: 100%;\n}\n@property --tw-ring-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-ring-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-inset-ring-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-inset-ring-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-ring-inset {\n syntax: "*";\n inherits: false;\n}\n@property --tw-ring-offset-width {\n syntax: "";\n inherits: false;\n initial-value: 0px;\n}\n@property --tw-ring-offset-color {\n syntax: "*";\n inherits: false;\n initial-value: #fff;\n}\n@property --tw-ring-offset-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-outline-style {\n syntax: "*";\n inherits: false;\n initial-value: solid;\n}\n@property --tw-backdrop-blur {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-brightness {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-contrast {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-grayscale {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-hue-rotate {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-invert {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-opacity {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-saturate {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-sepia {\n syntax: "*";\n inherits: false;\n}\n@property --tw-duration {\n syntax: "*";\n inherits: false;\n}\n@property --tw-ease {\n syntax: "*";\n inherits: false;\n}\n@keyframes spin {\n to {\n transform: rotate(360deg);\n }\n}\n@keyframes pulse {\n 50% {\n opacity: 0.5;\n }\n}\n@layer properties {\n @supports ((-webkit-hyphens: none) and (not (margin-trim: inline))) or ((-moz-orient: inline) and (not (color:rgb(from red r g b)))) {\n *, ::before, ::after, ::backdrop {\n --tw-translate-x: 0;\n --tw-translate-y: 0;\n --tw-translate-z: 0;\n --tw-scale-x: 1;\n --tw-scale-y: 1;\n --tw-scale-z: 1;\n --tw-rotate-x: initial;\n --tw-rotate-y: initial;\n --tw-rotate-z: initial;\n --tw-skew-x: initial;\n --tw-skew-y: initial;\n --tw-space-y-reverse: 0;\n --tw-space-x-reverse: 0;\n --tw-divide-y-reverse: 0;\n --tw-border-style: solid;\n --tw-leading: initial;\n --tw-font-weight: initial;\n --tw-shadow: 0 0 #0000;\n --tw-shadow-color: initial;\n --tw-shadow-alpha: 100%;\n --tw-inset-shadow: 0 0 #0000;\n --tw-inset-shadow-color: initial;\n --tw-inset-shadow-alpha: 100%;\n --tw-ring-color: initial;\n --tw-ring-shadow: 0 0 #0000;\n --tw-inset-ring-color: initial;\n --tw-inset-ring-shadow: 0 0 #0000;\n --tw-ring-inset: initial;\n --tw-ring-offset-width: 0px;\n --tw-ring-offset-color: #fff;\n --tw-ring-offset-shadow: 0 0 #0000;\n --tw-outline-style: solid;\n --tw-backdrop-blur: initial;\n --tw-backdrop-brightness: initial;\n --tw-backdrop-contrast: initial;\n --tw-backdrop-grayscale: initial;\n --tw-backdrop-hue-rotate: initial;\n --tw-backdrop-invert: initial;\n --tw-backdrop-opacity: initial;\n --tw-backdrop-saturate: initial;\n --tw-backdrop-sepia: initial;\n --tw-duration: initial;\n --tw-ease: initial;\n }\n }\n}\n',Ue=0;function He(e,t,n,o,i,r){t||(t={});var a,s,l=t;if("ref"in l)for(s in l={},t)"ref"==s?a=t[s]:l[s]=t[s];var c={type:e,props:l,key:n,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Ue,__i:-1,__u:0,__source:i,__self:r};if("function"==typeof e&&(a=e.defaultProps))for(s in a)void 0===l[s]&&(l[s]=a[s]);return I.vnode&&I.vnode(c),c}var Be=(e=>(e[e.Degree0=0]="Degree0",e[e.Degree90=1]="Degree90",e[e.Degree180=2]="Degree180",e[e.Degree270=3]="Degree270",e))(Be||{});function We(e){return{x:Math.floor(e.x),y:Math.floor(e.y)}}function qe(e){return{width:Math.ceil(e.width),height:Math.ceil(e.height)}}function Ge(e){return{origin:We(e.origin),size:qe(e.size)}}function Ve(e){const{width:t,height:n}=e;return{width:n,height:t}}function Ke(e,t,n){return{width:(e=t%2==0?e:Ve(e)).width*n,height:e.height*n}}function Ze(e){const t=[e.p1.x,e.p2.x,e.p3.x,e.p4.x],n=[e.p1.y,e.p2.y,e.p3.y,e.p4.y];return{origin:{x:Math.min(...t),y:Math.min(...n)},size:{width:Math.max(...t)-Math.min(...t),height:Math.max(...n)-Math.min(...n)}}}function Ye(e){return{p1:{x:e.origin.x,y:e.origin.y},p2:{x:e.origin.x+e.size.width,y:e.origin.y},p3:{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height},p4:{x:e.origin.x,y:e.origin.y+e.size.height}}}function Xe(e,t,n){let o=t.x,i=t.y;switch(n){case 0:o=t.x,i=t.y;break;case 1:o=e.height-t.y,i=t.x;break;case 2:o=e.width-t.x,i=e.height-t.y;break;case 3:o=t.y,i=e.width-t.x}return{x:o,y:i}}function Qe(e,t){return{x:e.x*t,y:e.y*t}}function Je(e){if(0===e.length)return{origin:{x:0,y:0},size:{width:0,height:0}};const t=e.map(e=>e.x),n=e.map(e=>e.y),o=Math.min(...t),i=Math.min(...n);return{origin:{x:o,y:i},size:{width:Math.max(...t)-o,height:Math.max(...n)-i}}}function et(e,t){return{origin:{x:e.origin.x-t,y:e.origin.y-t},size:{width:e.size.width+2*t,height:e.size.height+2*t}}}function tt(e,t,n){let o=t.origin.x,i=t.origin.y,r=t.size;switch(n){case 0:break;case 1:o=e.height-t.origin.y-t.size.height,i=t.origin.x,r=Ve(t.size);break;case 2:o=e.width-t.origin.x-t.size.width,i=e.height-t.origin.y-t.size.height;break;case 3:o=t.origin.y,i=e.width-t.origin.x-t.size.width,r=Ve(t.size)}return{origin:{x:o,y:i},size:{width:r.width,height:r.height}}}function nt(e,t){return{origin:{x:e.origin.x*t,y:e.origin.y*t},size:{width:e.size.width*t,height:e.size.height*t}}}function ot(e,t,n,o){return nt(tt(e,t,n),o)}const it={origin:{x:0,y:0},size:{width:0,height:0}};function rt(e){if(0===e.length)return null;let t=e[0].origin.x,n=e[0].origin.y,o=e[0].origin.x+e[0].size.width,i=e[0].origin.y+e[0].size.height;for(const r of e)t=Math.min(t,r.origin.x),n=Math.min(n,r.origin.y),o=Math.max(o,r.origin.x+r.size.width),i=Math.max(i,r.origin.y+r.size.height);return{origin:{x:t,y:n},size:{width:o-t,height:i-n}}}function at(e){const t=e%360;return t<0?t+360:t}function st(e){return{x:e.origin.x+e.size.width/2,y:e.origin.y+e.size.height/2}}function lt(e,t,n){const o=n*Math.PI/180,i=Math.cos(o),r=Math.sin(o),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}}function ct(e,t,n){return e.map(e=>lt(e,t,n))}function dt(e,t,n){return Je(ct([{x:e.origin.x,y:e.origin.y},{x:e.origin.x+e.size.width,y:e.origin.y},{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height},{x:e.origin.x,y:e.origin.y+e.size.height}],n,t))}function ut(e,t){return dt(e,t,st(e))}function ht(e,t,n){const o=n*Math.PI/180,i=Math.cos(o),r=Math.sin(o),a=1-i,s=r,l=-r,c=1-i,d=a*c-s*l,u=st(e);if(Math.abs(d)<1e-10)return u;const h=st(t),m=h.x-(i*u.x-r*u.y),g=h.y-(r*u.x+i*u.y);return{x:(c*m-s*g)/d,y:(-l*m+a*g)/d}}function mt(e,t,n,o){const i=e.origin.x,r=e.origin.y,a=e.size.width,s=e.size.height,l=n/a,c=o/s,d=n/s,u=o/a;switch(t){case 0:return{a:l,b:0,c:0,d:c,e:-l*i,f:-c*r};case 3:return{a:0,b:-u,c:d,d:0,e:-d*r,f:u*(i+a)};case 2:return{a:-l,b:0,c:0,d:-c,e:l*(i+a),f:c*(r+s)};case 1:return{a:0,b:u,c:-d,d:0,e:d*(r+s),f:-u*i}}}class gt{isEnabled(){return!1}debug(){}info(){}warn(){}error(){}perf(){}}class pt{isEnabled(){return!0}debug(e,t,...n){console.debug(`${e}.${t}`,...n)}info(e,t,...n){console.info(`${e}.${t}`,...n)}warn(e,t,...n){console.warn(`${e}.${t}`,...n)}error(e,t,...n){console.error(`${e}.${t}`,...n)}perf(e,t,n,o,...i){console.info(`${e}.${t}.${n}.${o}`,...i)}}class ft{constructor(e,t){this.logger=e,this.level=t}isEnabled(e){return this.level<={debug:0,info:1,warn:2,error:3}[e]}debug(e,t,...n){this.level<=0&&this.logger.debug(e,t,...n)}info(e,t,...n){this.level<=1&&this.logger.info(e,t,...n)}warn(e,t,...n){this.level<=2&&this.logger.warn(e,t,...n)}error(e,t,...n){this.level<=3&&this.logger.error(e,t,...n)}perf(e,t,n,o,...i){this.logger.perf(e,t,n,o,...i)}}class vt{constructor(){this.marks=new Map}isEnabled(){return!1}debug(e,t,...n){}info(e,t,...n){}warn(e,t,...n){}error(e,t,...n){}perf(e,t,n,o,i,...r){const a=`${e}.${t}.${n}.${o}.${i}`;switch(o){case"Begin":globalThis.performance.mark(a,{detail:r}),this.marks.set(`${e}.${t}.${n}.${i}`,Date.now());break;case"End":globalThis.performance.mark(a,{detail:r});const o=`${e}.${t}.${n}.Measure.${i}`,s=`${e}.${t}.${n}.Begin.${i}`;globalThis.performance.measure(o,s,a);const l=this.marks.get(`${e}.${t}.${n}.${i}`);if(l){const o=Date.now()-l;console.info(`⏱️ ${e}.${t}.${n}.${i}: ${o}ms`),this.marks.delete(`${e}.${t}.${n}.${i}`)}}}}class yt{constructor(e){this.loggers=e}isEnabled(e){return this.loggers.some(t=>t.isEnabled(e))}debug(e,t,...n){for(const o of this.loggers)o.debug(e,t,...n)}info(e,t,...n){for(const o of this.loggers)o.info(e,t,...n)}warn(e,t,...n){for(const o of this.loggers)o.warn(e,t,...n)}error(e,t,...n){for(const o of this.loggers)o.error(e,t,...n)}perf(e,t,n,o,...i){for(const r of this.loggers)r.perf(e,t,n,o,...i)}}var bt=(e=>(e[e.Pending=0]="Pending",e[e.Resolved=1]="Resolved",e[e.Rejected=2]="Rejected",e[e.Aborted=3]="Aborted",e))(bt||{});class wt extends Error{constructor(e){super(`Task aborted: ${JSON.stringify(e)}`),this.name="TaskAbortedError",this.reason=e}}class xt extends Error{constructor(e){super(`Task rejected: ${JSON.stringify(e)}`),this.name="TaskRejectedError",this.reason=e}}class Ct{constructor(){this.state={stage:0},this.resolvedCallbacks=[],this.rejectedCallbacks=[],this._promise=null,this.progressCbs=[]}toPromise(){return this._promise||(this._promise=new Promise((e,t)=>{this.wait(t=>e(t),e=>{"abort"===e.type?t(new wt(e.reason)):t(new xt(e.reason))})})),this._promise}wait(e,t){switch(this.state.stage){case 0:this.resolvedCallbacks.push(e),this.rejectedCallbacks.push(t);break;case 1:e(this.state.result);break;case 2:t({type:"reject",reason:this.state.reason});break;case 3:t({type:"abort",reason:this.state.reason})}}resolve(e){if(0===this.state.stage){this.state={stage:1,result:e};for(const t of this.resolvedCallbacks)try{t(e)}catch(e){}this.resolvedCallbacks=[],this.rejectedCallbacks=[]}}reject(e){if(0===this.state.stage){this.state={stage:2,reason:e};for(const t of this.rejectedCallbacks)try{t({type:"reject",reason:e})}catch(e){}this.resolvedCallbacks=[],this.rejectedCallbacks=[]}}abort(e){if(0===this.state.stage){this.state={stage:3,reason:e};for(const t of this.rejectedCallbacks)try{t({type:"abort",reason:e})}catch(e){}this.resolvedCallbacks=[],this.rejectedCallbacks=[]}}fail(e){"abort"===e.type?this.abort(e.reason):this.reject(e.reason)}onProgress(e){this.progressCbs.push(e)}progress(e){for(const t of this.progressCbs)t(e)}static all(e){const t=new Ct;if(0===e.length)return t.resolve([]),t;const n=new Array(e.length);let o=0,i=!1;return e.forEach((r,a)=>{r.wait(r=>{i||(n[a]=r,o++,o===e.length&&(i=!0,t.resolve(n)))},e=>{i||(i=!0,"abort"===e.type?t.abort(e.reason):t.reject(e.reason))})}),t}static allSettled(e){const t=new Ct;if(0===e.length)return t.resolve([]),t;const n=new Array(e.length);let o=0;return e.forEach((i,r)=>{i.wait(i=>{n[r]={status:"resolved",value:i},o++,o===e.length&&t.resolve(n)},i=>{n[r]={status:"abort"===i.type?"aborted":"rejected",reason:i.reason},o++,o===e.length&&t.resolve(n)})}),t}static race(e){const t=new Ct;if(0===e.length)return t.reject("No tasks provided"),t;let n=!1;return e.forEach(e=>{e.wait(e=>{n||(n=!0,t.resolve(e))},e=>{n||(n=!0,"abort"===e.type?t.abort(e.reason):t.reject(e.reason))})}),t}static withProgress(e,t){const n=Ct.all(e);if(t){let n=0;e.forEach(o=>{o.wait(()=>{n++,t(n,e.length)},()=>{n++,t(n,e.length)})})}return n}}const It=Object.freeze(["­","​","⁠","\ufeff","￾","￿"]),kt=new RegExp(`[${It.join("")}]`,"g");function St(e){return e.replace(kt,"")}var Mt=(e=>(e[e.Unknown=0]="Unknown",e[e.XYZ=1]="XYZ",e[e.FitPage=2]="FitPage",e[e.FitHorizontal=3]="FitHorizontal",e[e.FitVertical=4]="FitVertical",e[e.FitRectangle=5]="FitRectangle",e[e.FitBoundingBox=6]="FitBoundingBox",e[e.FitBoundingBoxHorizontal=7]="FitBoundingBoxHorizontal",e[e.FitBoundingBoxVertical=8]="FitBoundingBoxVertical",e))(Mt||{}),At=(e=>(e[e.NotSet=0]="NotSet",e[e.True=1]="True",e[e.False=2]="False",e[e.Unknown=3]="Unknown",e))(At||{}),Pt=(e=>(e[e.Unknown=-1]="Unknown",e[e.Courier=0]="Courier",e[e.Courier_Bold=1]="Courier_Bold",e[e.Courier_BoldOblique=2]="Courier_BoldOblique",e[e.Courier_Oblique=3]="Courier_Oblique",e[e.Helvetica=4]="Helvetica",e[e.Helvetica_Bold=5]="Helvetica_Bold",e[e.Helvetica_BoldOblique=6]="Helvetica_BoldOblique",e[e.Helvetica_Oblique=7]="Helvetica_Oblique",e[e.Times_Roman=8]="Times_Roman",e[e.Times_Bold=9]="Times_Bold",e[e.Times_BoldItalic=10]="Times_BoldItalic",e[e.Times_Italic=11]="Times_Italic",e[e.Symbol=12]="Symbol",e[e.ZapfDingbats=13]="ZapfDingbats",e))(Pt||{}),Dt=(e=>(e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right",e))(Dt||{}),Rt=(e=>(e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom",e))(Rt||{}),zt=(e=>(e[e.Normal=0]="Normal",e[e.Multiply=1]="Multiply",e[e.Screen=2]="Screen",e[e.Overlay=3]="Overlay",e[e.Darken=4]="Darken",e[e.Lighten=5]="Lighten",e[e.ColorDodge=6]="ColorDodge",e[e.ColorBurn=7]="ColorBurn",e[e.HardLight=8]="HardLight",e[e.SoftLight=9]="SoftLight",e[e.Difference=10]="Difference",e[e.Exclusion=11]="Exclusion",e[e.Hue=12]="Hue",e[e.Saturation=13]="Saturation",e[e.Color=14]="Color",e[e.Luminosity=15]="Luminosity",e))(zt||{}),Tt=(e=>(e[e.Contain=0]="Contain",e[e.Cover=1]="Cover",e[e.Stretch=2]="Stretch",e))(Tt||{}),Et=(e=>(e[e.Unsupported=0]="Unsupported",e[e.Goto=1]="Goto",e[e.RemoteGoto=2]="RemoteGoto",e[e.URI=3]="URI",e[e.LaunchAppOrOpenFile=4]="LaunchAppOrOpenFile",e))(Et||{}),_t=(e=>(e[e.UNKNOWN=0]="UNKNOWN",e[e.TEXT=1]="TEXT",e[e.LINK=2]="LINK",e[e.FREETEXT=3]="FREETEXT",e[e.LINE=4]="LINE",e[e.SQUARE=5]="SQUARE",e[e.CIRCLE=6]="CIRCLE",e[e.POLYGON=7]="POLYGON",e[e.POLYLINE=8]="POLYLINE",e[e.HIGHLIGHT=9]="HIGHLIGHT",e[e.UNDERLINE=10]="UNDERLINE",e[e.SQUIGGLY=11]="SQUIGGLY",e[e.STRIKEOUT=12]="STRIKEOUT",e[e.STAMP=13]="STAMP",e[e.CARET=14]="CARET",e[e.INK=15]="INK",e[e.POPUP=16]="POPUP",e[e.FILEATTACHMENT=17]="FILEATTACHMENT",e[e.SOUND=18]="SOUND",e[e.MOVIE=19]="MOVIE",e[e.WIDGET=20]="WIDGET",e[e.SCREEN=21]="SCREEN",e[e.PRINTERMARK=22]="PRINTERMARK",e[e.TRAPNET=23]="TRAPNET",e[e.WATERMARK=24]="WATERMARK",e[e.THREED=25]="THREED",e[e.RICHMEDIA=26]="RICHMEDIA",e[e.XFAWIDGET=27]="XFAWIDGET",e[e.REDACT=28]="REDACT",e))(_t||{}),Nt=(e=>(e[e.Normal=0]="Normal",e[e.Rollover=1]="Rollover",e[e.Down=2]="Down",e))(Nt||{}),Ot=(e=>(e[e.Unknown=-1]="Unknown",e[e.Comment=0]="Comment",e[e.Key=1]="Key",e[e.Note=2]="Note",e[e.Help=3]="Help",e[e.NewParagraph=4]="NewParagraph",e[e.Paragraph=5]="Paragraph",e[e.Insert=6]="Insert",e[e.Graph=7]="Graph",e[e.PushPin=8]="PushPin",e[e.Paperclip=9]="Paperclip",e[e.Tag=10]="Tag",e[e.Speaker=11]="Speaker",e[e.Mic=12]="Mic",e[e.Approved=13]="Approved",e[e.Experimental=14]="Experimental",e[e.NotApproved=15]="NotApproved",e[e.AsIs=16]="AsIs",e[e.Expired=17]="Expired",e[e.NotForPublicRelease=18]="NotForPublicRelease",e[e.Confidential=19]="Confidential",e[e.Final=20]="Final",e[e.Sold=21]="Sold",e[e.Departmental=22]="Departmental",e[e.ForComment=23]="ForComment",e[e.TopSecret=24]="TopSecret",e[e.Draft=25]="Draft",e[e.ForPublicRelease=26]="ForPublicRelease",e))(Ot||{}),Lt=(e=>(e[e.None=0]="None",e[e.Square=1]="Square",e[e.Circle=2]="Circle",e[e.Diamond=3]="Diamond",e[e.OpenArrow=4]="OpenArrow",e[e.ClosedArrow=5]="ClosedArrow",e[e.Butt=6]="Butt",e[e.ROpenArrow=7]="ROpenArrow",e[e.RClosedArrow=8]="RClosedArrow",e[e.Slash=9]="Slash",e[e.Unknown=10]="Unknown",e))(Lt||{}),$t=(e=>(e[e.Unknown=0]="Unknown",e[e.Reply=1]="Reply",e[e.Group=2]="Group",e))($t||{}),jt=(e=>(e[e.UNKNOWN=0]="UNKNOWN",e[e.PUSHBUTTON=1]="PUSHBUTTON",e[e.CHECKBOX=2]="CHECKBOX",e[e.RADIOBUTTON=3]="RADIOBUTTON",e[e.COMBOBOX=4]="COMBOBOX",e[e.LISTBOX=5]="LISTBOX",e[e.TEXTFIELD=6]="TEXTFIELD",e[e.SIGNATURE=7]="SIGNATURE",e[e.XFA=8]="XFA",e[e.XFA_CHECKBOX=9]="XFA_CHECKBOX",e[e.XFA_COMBOBOX=10]="XFA_COMBOBOX",e[e.XFA_IMAGEFIELD=11]="XFA_IMAGEFIELD",e[e.XFA_LISTBOX=12]="XFA_LISTBOX",e[e.XFA_PUSHBUTTON=13]="XFA_PUSHBUTTON",e[e.XFA_SIGNATURE=14]="XFA_SIGNATURE",e[e.XFA_TEXTFIELD=15]="XFA_TEXTFIELD",e))(jt||{}),Ft=(e=>(e[e.Color=0]="Color",e[e.InteriorColor=1]="InteriorColor",e[e.OverlayColor=2]="OverlayColor",e))(Ft||{}),Ut=(e=>(e[e.UNKNOWN=0]="UNKNOWN",e[e.SOLID=1]="SOLID",e[e.DASHED=2]="DASHED",e[e.BEVELED=3]="BEVELED",e[e.INSET=4]="INSET",e[e.UNDERLINE=5]="UNDERLINE",e[e.CLOUDY=6]="CLOUDY",e))(Ut||{}),Ht=(e=>(e[e.UNKNOWN=0]="UNKNOWN",e[e.TEXT=1]="TEXT",e[e.PATH=2]="PATH",e[e.IMAGE=3]="IMAGE",e[e.SHADING=4]="SHADING",e[e.FORM=5]="FORM",e))(Ht||{});const Bt=Object.freeze({1:"invisible",2:"hidden",4:"print",8:"noZoom",16:"noRotate",32:"noView",64:"readOnly",128:"locked",256:"toggleNoView"}),Wt=Object.entries(Bt).reduce((e,[t,n])=>(e[n]=Number(t),e),{});function qt(e){return Object.keys(Bt).filter(t=>0!==(e&t)).map(e=>Bt[e])}function Gt(e){return e.reduce((e,t)=>e|Wt[t],0)}var Vt=(e=>(e[e.Create=0]="Create",e[e.Read=1]="Read",e[e.Update=2]="Update",e[e.Delete=3]="Delete",e))(Vt||{}),Kt=(e=>(e[e.None=0]="None",e[e.MatchCase=1]="MatchCase",e[e.MatchWholeWord=2]="MatchWholeWord",e[e.MatchConsecutive=4]="MatchConsecutive",e))(Kt||{}),Zt=(e=>(e[e.Print=4]="Print",e[e.ModifyContents=8]="ModifyContents",e[e.CopyContents=16]="CopyContents",e[e.ModifyAnnotations=32]="ModifyAnnotations",e[e.FillForms=256]="FillForms",e[e.ExtractForAccessibility=512]="ExtractForAccessibility",e[e.AssembleDocument=1024]="AssembleDocument",e[e.PrintHighQuality=2048]="PrintHighQuality",e[e.AllowAll=3900]="AllowAll",e))(Zt||{});class Yt extends Error{constructor(e,t){const n=e.map(e=>Zt[e]).join(", ");super(`Permission denied. Required: ${n}`),this.requiredFlags=e,this.currentPermissions=t,this.name="PermissionDeniedError"}}var Xt=(e=>(e[e.Display=0]="Display",e[e.Print=1]="Print",e))(Xt||{}),Qt=(e=>(e[e.Ok=0]="Ok",e[e.Unknown=1]="Unknown",e[e.NotFound=2]="NotFound",e[e.WrongFormat=3]="WrongFormat",e[e.Password=4]="Password",e[e.Security=5]="Security",e[e.PageError=6]="PageError",e[e.XFALoad=7]="XFALoad",e[e.XFALayout=8]="XFALayout",e[e.Cancelled=9]="Cancelled",e[e.Initialization=10]="Initialization",e[e.NotReady=11]="NotReady",e[e.NotSupport=12]="NotSupport",e[e.LoadDoc=13]="LoadDoc",e[e.DocNotOpen=14]="DocNotOpen",e[e.CantCloseDoc=15]="CantCloseDoc",e[e.CantCreateNewDoc=16]="CantCreateNewDoc",e[e.CantImportPages=17]="CantImportPages",e[e.CantCreateAnnot=18]="CantCreateAnnot",e[e.CantSetAnnotRect=19]="CantSetAnnotRect",e[e.CantSetAnnotContent=20]="CantSetAnnotContent",e[e.CantRemoveInkList=21]="CantRemoveInkList",e[e.CantAddInkStoke=22]="CantAddInkStoke",e[e.CantReadAttachmentSize=23]="CantReadAttachmentSize",e[e.CantReadAttachmentContent=24]="CantReadAttachmentContent",e[e.CantFocusAnnot=25]="CantFocusAnnot",e[e.CantSelectText=26]="CantSelectText",e[e.CantSelectOption=27]="CantSelectOption",e[e.CantCheckField=28]="CantCheckField",e[e.CantSetAnnotString=29]="CantSetAnnotString",e))(Qt||{});class Jt{static create(){return new Ct}static resolve(e){const t=new Ct;return t.resolve(e),t}static reject(e){const t=new Ct;return t.reject(e),t}static abort(e){const t=new Ct;return t.reject(e),t}}function en(e){const t=e=>(e=>Math.max(0,Math.min(255,e)))(e).toString(16).padStart(2,"0");return`#${t(e.red)}${t(e.green)}${t(e.blue)}`}function tn(e){/^#?[0-9a-f]{3}$/i.test(e)&&(e=e.replace(/^#?([0-9a-f])([0-9a-f])([0-9a-f])$/i,"#$1$1$2$2$3$3").toLowerCase());const[,t,n,o]=/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(e)??(()=>{throw new Error(`Invalid hex colour: "${e}"`)})();return{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(o,16)}}function nn(e){return(e=>Math.max(0,Math.min(255,e)))(e)/255}function on(e){return((e,t=255)=>Math.max(0,Math.min(t,e)))(Math.round(255*e))}function rn(e){if(!(null==e?void 0:e.startsWith("D:"))||e.length<16)return;const t=+e.slice(2,6),n=+e.slice(6,8)-1,o=+e.slice(8,10),i=+e.slice(10,12),r=+e.slice(12,14),a=+e.slice(14,16);return new Date(Date.UTC(t,n,o,i,r,a))}function an(e=new Date){const t=(e,t=2)=>e.toString().padStart(t,"0");return`D:${e.getUTCFullYear()}${t(e.getUTCMonth()+1)}${t(e.getUTCDate())}${t(e.getUTCHours())}${t(e.getUTCMinutes())}${t(e.getUTCSeconds())}`}const sn=Object.freeze([{id:Dt.Left,label:"Left",css:"left"},{id:Dt.Center,label:"Center",css:"center"},{id:Dt.Right,label:"Right",css:"right"}]),ln=sn.reduce((e,t)=>(e[t.id]=t,e),{});function cn(e){return function(e){return ln[e]??ln[Dt.Left]}(e).css}sn.reduce((e,t)=>(e[t.css]=t.id,e),{}),sn.map(e=>({value:e.id,label:e.label}));var dn=(e=>(e.Courier="Courier",e.Helvetica="Helvetica",e.Times="Times",e.Symbol="Symbol",e.ZapfDingbats="ZapfDingbats",e.Unknown="Unknown",e))(dn||{});const un=Pt.Helvetica,hn={id:Pt.Helvetica,family:"Helvetica",bold:!1,italic:!1,label:"Helvetica",css:"Helvetica, Arial, sans-serif"},mn=Object.freeze([{id:Pt.Courier,family:"Courier",bold:!1,italic:!1,label:"Courier",css:"Courier, monospace"},{id:Pt.Courier_Bold,family:"Courier",bold:!0,italic:!1,label:"Courier Bold",css:"Courier, monospace"},{id:Pt.Courier_BoldOblique,family:"Courier",bold:!0,italic:!0,label:"Courier Bold Oblique",css:"Courier, monospace"},{id:Pt.Courier_Oblique,family:"Courier",bold:!1,italic:!0,label:"Courier Oblique",css:"Courier, monospace"},hn,{id:Pt.Helvetica_Bold,family:"Helvetica",bold:!0,italic:!1,label:"Helvetica Bold",css:"Helvetica, Arial, sans-serif"},{id:Pt.Helvetica_BoldOblique,family:"Helvetica",bold:!0,italic:!0,label:"Helvetica Bold Oblique",css:"Helvetica, Arial, sans-serif"},{id:Pt.Helvetica_Oblique,family:"Helvetica",bold:!1,italic:!0,label:"Helvetica Oblique",css:"Helvetica, Arial, sans-serif"},{id:Pt.Times_Roman,family:"Times",bold:!1,italic:!1,label:"Times Roman",css:'"Times New Roman", Times, serif'},{id:Pt.Times_Bold,family:"Times",bold:!0,italic:!1,label:"Times Bold",css:'"Times New Roman", Times, serif'},{id:Pt.Times_BoldItalic,family:"Times",bold:!0,italic:!0,label:"Times Bold Italic",css:'"Times New Roman", Times, serif'},{id:Pt.Times_Italic,family:"Times",bold:!1,italic:!0,label:"Times Italic",css:'"Times New Roman", Times, serif'},{id:Pt.Symbol,family:"Symbol",bold:!1,italic:!1,label:"Symbol",css:"Symbol, serif"},{id:Pt.ZapfDingbats,family:"ZapfDingbats",bold:!1,italic:!1,label:"Zapf Dingbats",css:"ZapfDingbats, serif"}]),gn=mn.reduce((e,t)=>(e[t.id]=t,e),{}),pn=new Map;for(const e of mn)pn.set(`${e.family}_${e.bold}_${e.italic}`,e.id);function fn(e){return gn[e]??hn}function vn(e){return fn(e).family}function yn(e){return fn(e).bold}function bn(e){return fn(e).italic}function wn(e,{bold:t,italic:n}){return pn.get(`${e}_${t}_${n}`)??un}function xn(e){const t=fn(e);return{fontFamily:t.css,fontWeight:t.bold?"bold":"normal",fontStyle:t.italic?"italic":"normal"}}Object.values(dn).filter(e=>"Unknown"!==e).map(e=>({value:e,label:e}));const Cn=[...new Set(mn.map(e=>e.family))];function In(e){switch(e){case"Courier":return"Courier";case"Helvetica":default:return"Helvetica";case"Times":return"Times";case"Symbol":return"Symbol";case"ZapfDingbats":return"ZapfDingbats"}}const kn=Object.freeze([{id:zt.Normal,label:"Normal",css:"normal"},{id:zt.Multiply,label:"Multiply",css:"multiply"},{id:zt.Screen,label:"Screen",css:"screen"},{id:zt.Overlay,label:"Overlay",css:"overlay"},{id:zt.Darken,label:"Darken",css:"darken"},{id:zt.Lighten,label:"Lighten",css:"lighten"},{id:zt.ColorDodge,label:"Color Dodge",css:"color-dodge"},{id:zt.ColorBurn,label:"Color Burn",css:"color-burn"},{id:zt.HardLight,label:"Hard Light",css:"hard-light"},{id:zt.SoftLight,label:"Soft Light",css:"soft-light"},{id:zt.Difference,label:"Difference",css:"difference"},{id:zt.Exclusion,label:"Exclusion",css:"exclusion"},{id:zt.Hue,label:"Hue",css:"hue"},{id:zt.Saturation,label:"Saturation",css:"saturation"},{id:zt.Color,label:"Color",css:"color"},{id:zt.Luminosity,label:"Luminosity",css:"luminosity"}]),Sn=kn.reduce((e,t)=>(e[t.id]=t,e),{});function Mn(e){return function(e){return Sn[e]??Sn[zt.Normal]}(e).css}kn.reduce((e,t)=>(e[t.css]=t.id,e),{}),kn.map(e=>({value:e.id,label:e.label}));const An=kn.map(e=>e.id);function Pn(e){if(e instanceof gt)return{type:"noop"};if(e instanceof pt)return{type:"console"};if(e instanceof vt)return{type:"perf"};if(e instanceof ft){const t=e;return{type:"level",config:{level:t.level,logger:Pn(t.logger)}}}if(e instanceof yt){return{type:"all",config:{loggers:e.loggers.map(Pn)}}}return{type:"noop"}}const Dn=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Rn(e){return Dn.test(e)}function zn(){var e;if("function"==typeof(null==(e=globalThis.crypto)?void 0:e.randomUUID))return globalThis.crypto.randomUUID();const t=function(e){var t;if("function"==typeof(null==(t=globalThis.crypto)?void 0:t.getRandomValues))return globalThis.crypto.getRandomValues(new Uint8Array(e));if("function"==typeof require)try{const{randomBytes:t}=require("crypto");return t(e)}catch{}const n=new Uint8Array(e);for(let t=0;te.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}class Tn extends Ct{constructor(e={}){super(),this.children=new Map,this.childResults=[],this.completedCount=0,this.expectedCount=0,this.isFinalized=!1,this.config={aggregate:e.aggregate??(e=>e),onChildComplete:e.onChildComplete??(()=>{}),failFast:e.failFast??!0}}addChild(e,t){if(this.state.stage!==bt.Pending)return this.state.stage===bt.Aborted&&e.abort(this.state.reason),this;const n=t??this.expectedCount;return this.expectedCount=Math.max(this.expectedCount,n+1),this.children.set(e,n),e.wait(t=>this.handleChildSuccess(e,t,n),t=>this.handleChildError(e,t,n)),this}finalize(){return this.isFinalized||(this.isFinalized=!0,0===this.expectedCount&&this.resolve(this.config.aggregate([]))),this}handleChildSuccess(e,t,n){if(this.state.stage!==bt.Pending)return;this.childResults[n]=t,this.completedCount++,this.children.delete(e);const o=this.config.onChildComplete(this.completedCount,this.expectedCount,t,n);if(void 0!==o&&this.progress(o),this.completedCount===this.expectedCount){const e=this.config.aggregate(this.childResults);this.resolve(e)}}handleChildError(e,t,n){if(this.state.stage===bt.Pending)if(this.children.delete(e),this.config.failFast){for(const[e]of this.children)e.abort("Sibling task failed");this.children.clear(),this.fail(t)}else if(this.childResults[n]=void 0,this.completedCount++,this.completedCount===this.expectedCount){const e=this.config.aggregate(this.childResults);this.resolve(e)}}abort(e){for(const[t]of this.children)t.abort(e);this.children.clear(),super.abort(e)}reject(e){for(const[t]of this.children)t.abort(e);this.children.clear(),super.reject(e)}getPendingCount(){return this.children.size}getCompletedCount(){return this.completedCount}static gather(e){const t=new Tn({aggregate:e=>e,onChildComplete:(e,t)=>({completed:e,total:t})});return e.forEach((e,n)=>t.addChild(e,n)),t.finalize(),t}static gatherIndexed(e){const t=new Tn({aggregate:e=>{const t={};return e.forEach((e,n)=>{t[n]=e}),t},onChildComplete:(e,t,n,o)=>({page:o,result:n})});return e.forEach((e,n)=>t.addChild(e,n)),t.finalize(),t}static gatherFrom(e,t){const n=new Tn(t);return e.forEach((e,t)=>n.addChild(e,t)),n.finalize(),n}static first(e){let t=!1;const n=new Tn({aggregate:e=>e[0],failFast:!1});return n.handleChildSuccess=(e,o)=>{if(!t){t=!0;for(const[t]of n.children)t!==e&&t.abort("Race won by sibling");n.resolve(o)}},e.forEach((e,t)=>n.addChild(e,t)),n.finalize(),n}}function En(){}class _n{constructor(){this.dependencyGraph=new Map}addNode(e,t=[]){this.dependencyGraph.set(e,new Set(t))}hasCircularDependencies(){const e=new Set,t=new Set,n=o=>{e.add(o),t.add(o);const i=this.dependencyGraph.get(o)||new Set;for(const o of i)if(e.has(o)){if(t.has(o))return!0}else if(n(o))return!0;return t.delete(o),!1};for(const t of this.dependencyGraph.keys())if(!e.has(t)&&n(t))return!0;return!1}resolveLoadOrder(){if(this.hasCircularDependencies())throw new Error("Circular dependencies detected");const e=[],t=new Set,n=new Set,o=i=>{if(n.has(i))throw new Error("Circular dependency");if(t.has(i))return;n.add(i);const r=this.dependencyGraph.get(i)||new Set;for(const e of r)o(e);n.delete(i),t.add(i),e.push(i)};for(const e of this.dependencyGraph.keys())t.has(e)||o(e);return e}}class Nn extends Error{constructor(e){super(e),this.name="PluginRegistrationError"}}class On extends Error{constructor(e){super(e),this.name="PluginNotFoundError"}}class Ln extends Error{constructor(e){super(e),this.name="CircularDependencyError"}}class $n extends Error{constructor(e){super(e),this.name="PluginConfigurationError"}}class jn{constructor(e,t){this.store=e,this.pluginId=t}getState(){return this.store.getState().plugins[this.pluginId]}dispatch(e){return this.store.dispatchToPlugin(this.pluginId,e)}subscribeToState(e){return this.store.subscribeToPlugin(this.pluginId,(t,n,o)=>{e(t,n,o)})}onAction(e,t){return this.store.onAction(e,(e,n,o)=>{t(e,n.plugins[this.pluginId],o.plugins[this.pluginId])})}}const Fn="START_LOADING_DOCUMENT",Un="UPDATE_DOCUMENT_LOADING_PROGRESS",Hn="SET_DOCUMENT_LOADED",Bn="SET_DOCUMENT_ERROR",Wn="RETRY_LOADING_DOCUMENT",qn="CLOSE_DOCUMENT",Gn="SET_ACTIVE_DOCUMENT",Vn="REORDER_DOCUMENTS",Kn="MOVE_DOCUMENT",Zn="UPDATE_DOCUMENT_SECURITY",Yn="REFRESH_PAGES",Xn="SET_SCALE",Qn="SET_ROTATION",Jn=[Fn,Un,Hn,qn,Gn,Bn,Wn,"REFRESH_DOCUMENT",Yn,"SET_PAGES",Xn,Qn,"SET_DEFAULT_SCALE","SET_DEFAULT_ROTATION",Vn,Kn,Zn],eo=(e,t,n,o,i,r,a)=>({type:Fn,payload:{documentId:e,name:t,scale:n,rotation:o,passwordProvided:i,autoActivate:r,permissions:a}}),to=(e,t)=>({type:qn,payload:{documentId:e,nextActiveDocumentId:t}}),no=(e,t)=>({type:Yn,payload:{documentId:e,pageIndexes:t}}),oo=(e,t)=>({type:Qn,payload:{rotation:e,documentId:t}});class io{constructor(e,t){this.initialCoreState=t,this.pluginReducers={},this.listeners=[],this.pluginListeners={},this.isDispatching=!1,this.state={core:t,plugins:{}},this.coreReducer=e}addPluginReducer(e,t,n){this.state.plugins[e]=n,this.pluginReducers[e]=t}dispatchToCore(e){if(!this.coreReducer)return this.getState();if(this.isDispatching)throw new Error("Reducers may not dispatch actions. To trigger cascading actions, dispatch from a listener callback instead.");const t=this.getState();try{this.isDispatching=!0,this.state.core=this.coreReducer(this.state.core,e)}finally{this.isDispatching=!1}return this.listeners.forEach(n=>{const o=this.getState();n(e,o,t)}),this.getState()}dispatchToPlugin(e,t,n=!0){if(this.isDispatching)throw new Error("Reducers may not dispatch actions. To trigger cascading actions, dispatch from a listener callback instead.");const o=this.getState(),i=this.pluginReducers[e];if(!i)return o.plugins[e];const r=o.plugins[e];try{this.isDispatching=!0;const n=i(r,t);this.state.plugins[e]=n}finally{this.isDispatching=!1}return n&&this.listeners.forEach(e=>{const n=this.getState();e(t,n,o)}),this.pluginListeners[e]&&this.pluginListeners[e].forEach(n=>{const o=this.getState().plugins[e];n(t,o,r)}),this.getState().plugins[e]}dispatch(e){if(this.isDispatching)throw new Error("Reducers may not dispatch actions. To trigger cascading actions, dispatch from a listener callback instead.");const t=this.getState();try{this.isDispatching=!0,this.isCoreAction(e)&&(this.state.core=this.coreReducer(this.state.core,e));for(const n in this.pluginReducers){const o=this.pluginReducers[n],i=t.plugins[n];o&&(this.state.plugins[n]=o(i,e))}}finally{this.isDispatching=!1}return this.listeners.forEach(n=>{const o=this.getState();n(e,o,t)}),this.getState()}getState(){if(this.isDispatching)throw new Error("You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.");return{core:{...this.state.core},plugins:{...this.state.plugins}}}subscribe(e){if(this.isDispatching)throw new Error("You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state.");return this.listeners.push(e),()=>{if(this.isDispatching)throw new Error("You may not unsubscribe from a store listener while the reducer is executing.");this.listeners=this.listeners.filter(t=>t!==e)}}subscribeToPlugin(e,t){if(!(e in this.state.plugins))throw new Error(`Plugin state not found for plugin "${e}". Did you forget to call addPluginReducer?`);if(this.isDispatching)throw new Error("You may not call store.subscribeToPlugin() while the reducer is executing.");return this.pluginListeners[e]||(this.pluginListeners[e]=[]),this.pluginListeners[e].push(t),()=>{if(this.isDispatching)throw new Error("You may not unsubscribe from a store listener while the reducer is executing.");this.pluginListeners[e]=this.pluginListeners[e].filter(e=>e!==t),0===this.pluginListeners[e].length&&delete this.pluginListeners[e]}}onAction(e,t){return this.subscribe((n,o,i)=>{n.type===e&&t(n,o,i)})}getPluginStore(e){if(!(e in this.state.plugins))throw new Error(`Plugin state not found for plugin "${e}". Did you forget to call addPluginReducer?`);return new jn(this,e)}isCoreAction(e){return Jn.includes(e.type)}destroy(){var e,t;this.listeners.length=0;for(const n in this.pluginListeners)null==(t=null==(e=this.pluginListeners[n])?void 0:e.splice)||t.call(e,0);this.pluginListeners={},this.pluginReducers={},this.state.plugins={},this.state.core={...this.initialCoreState}}}Zt.Print,Zt.ModifyContents,Zt.CopyContents,Zt.ModifyAnnotations,Zt.FillForms,Zt.ExtractForAccessibility,Zt.AssembleDocument,Zt.PrintHighQuality;const ro=[Zt.Print,Zt.ModifyContents,Zt.CopyContents,Zt.ModifyAnnotations,Zt.FillForms,Zt.ExtractForAccessibility,Zt.AssembleDocument,Zt.PrintHighQuality],ao={[Zt.Print]:"print",[Zt.ModifyContents]:"modifyContents",[Zt.CopyContents]:"copyContents",[Zt.ModifyAnnotations]:"modifyAnnotations",[Zt.FillForms]:"fillForms",[Zt.ExtractForAccessibility]:"extractForAccessibility",[Zt.AssembleDocument]:"assembleDocument",[Zt.PrintHighQuality]:"printHighQuality"};function so(e,t){if(!e)return;if(t in e)return e[t];const n=ao[t];return n&&n in e?e[n]:void 0}function lo(e,t,n){var o;const i=e.documents[t],r=null==i?void 0:i.permissions,a=e.globalPermissions,s=(null==(o=null==i?void 0:i.document)?void 0:o.permissions)??Zt.AllowAll,l=so(null==r?void 0:r.overrides,n);if(void 0!==l)return l;const c=so(null==a?void 0:a.overrides,n);if(void 0!==c)return c;return!((null==r?void 0:r.enforceDocumentPermissions)??(null==a?void 0:a.enforceDocumentPermissions)??!0)||0!==(s&n)}function co(e,t){return ro.reduce((n,o)=>lo(e,t,o)?n|o:n,0)}function uo(e,t,n){const o=e.activeDocumentId;if(o!==t)return o;if(void 0!==n)return n&&e.documents[n]?n:null;const i=e.documentOrder.indexOf(t);return-1===i?null:i>0?e.documentOrder[i-1]:i{switch(t.type){case Fn:{const{documentId:n,name:o,scale:i,rotation:r,passwordProvided:a,autoActivate:s=!0,permissions:l}=t.payload,c={id:n,name:o,status:"loading",loadingProgress:0,error:null,document:null,scale:i??e.defaultScale,rotation:r??e.defaultRotation,passwordProvided:a??!1,pageRefreshVersions:{},permissions:l,loadStartedAt:Date.now()};return{...e,documents:{...e.documents,[n]:c},documentOrder:[...e.documentOrder,n],activeDocumentId:s||!e.activeDocumentId?n:e.activeDocumentId}}case Un:{const{documentId:n,progress:o}=t.payload,i=e.documents[n];return i&&"loading"===i.status?{...e,documents:{...e.documents,[n]:{...i,loadingProgress:o}}}:e}case Hn:{const{documentId:n,document:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,status:"loaded",document:o,error:null,errorCode:void 0,errorDetails:void 0,passwordProvided:void 0,loadedAt:Date.now()}}}:e}case Bn:{const{documentId:n,error:o,errorCode:i,errorDetails:r}=t.payload,a=e.documents[n];return a?{...e,documents:{...e.documents,[n]:{...a,status:"error",error:o,errorCode:i,errorDetails:r}}}:e}case Wn:{const{documentId:n,passwordProvided:o}=t.payload,i=e.documents[n];return i&&"error"===i.status?{...e,documents:{...e.documents,[n]:{...i,status:"loading",loadingProgress:0,error:null,errorCode:void 0,errorDetails:void 0,passwordProvided:o??!1,loadStartedAt:Date.now()}}}:e}case qn:{const{documentId:n,nextActiveDocumentId:o}=t.payload,{[n]:i,...r}=e.documents;return{...e,documents:r,documentOrder:e.documentOrder.filter(e=>e!==n),activeDocumentId:uo(e,n,o)}}case Kn:{const{documentId:n,toIndex:o}=t.payload,i=function(e,t,n){const o=e.indexOf(t);if(-1===o)return null;if(n<0||n>=e.length)return null;if(o===n)return null;const i=[...e];return i.splice(o,1),i.splice(n,0,t),i}(e.documentOrder,n,o);return i?{...e,documentOrder:i}:e}case Vn:return{...e,documentOrder:t.payload};case Gn:return{...e,activeDocumentId:t.payload};case Xn:{const{scale:n,documentId:o}=t.payload,i=o??e.activeDocumentId;if(!i)return e;const r=e.documents[i];return r?{...e,documents:{...e.documents,[i]:{...r,scale:n}}}:e}case Qn:{const{rotation:n,documentId:o}=t.payload,i=o??e.activeDocumentId;if(!i)return e;const r=e.documents[i];return r?{...e,documents:{...e.documents,[i]:{...r,rotation:n}}}:e}case Yn:{const{documentId:n,pageIndexes:o}=t.payload,i=e.documents[n];if(!i)return e;const r={...i.pageRefreshVersions};for(const e of o)r[e]=(r[e]||0)+1;return{...e,documents:{...e.documents,[n]:{...i,pageRefreshVersions:r}}}}case Zn:{const{documentId:n,permissions:o,isOwnerUnlocked:i}=t.payload,r=e.documents[n];return(null==r?void 0:r.document)?{...e,documents:{...e.documents,[n]:{...r,document:{...r.document,permissions:o,isOwnerUnlocked:i}}}}:e}default:return e}};class mo{constructor(e,t){this.plugins=new Map,this.manifests=new Map,this.capabilities=new Map,this.status=new Map,this.configurations=new Map,this.initPromise=null,this.pendingRegistrations=[],this.processingRegistrations=[],this.initialized=!1,this.isInitializing=!1,this.pluginsReadyPromise=null,this.destroyed=!1,this.resolver=new _n,this.engine=e,this.initialCoreState=(e=>({documents:{},documentOrder:[],activeDocumentId:null,defaultScale:(null==e?void 0:e.defaultScale)??1,defaultRotation:(null==e?void 0:e.defaultRotation)??Be.Degree0,globalPermissions:null==e?void 0:e.permissions}))(t),this.store=new io(ho,this.initialCoreState),this.logger=(null==t?void 0:t.logger)??new gt}getLogger(){return this.logger}registerPlugin(e,t){if(this.initialized&&!this.isInitializing)throw new Nn("Cannot register plugins after initialization");this.validateManifest(e.manifest),this.store.addPluginReducer(e.manifest.id,e.reducer,"function"==typeof e.initialState?e.initialState(this.initialCoreState,{...e.manifest.defaultConfig,...t}):e.initialState),this.pendingRegistrations.push({package:e,config:t})}getStore(){return this.store}getEngine(){return this.engine}pluginsReady(){return this.pluginsReadyPromise||(this.pluginsReadyPromise=(async()=>{this.initialized||await this.initialize();const e=Array.from(this.plugins.values()).map(e=>"function"==typeof e.ready?e.ready():Promise.resolve());await Promise.all(e)})()),this.pluginsReadyPromise}async initialize(){if(this.destroyed)throw new Nn("Registry has been destroyed");return this.initPromise||(this.initPromise=(async()=>{if(this.initialized)throw new Nn("Registry is already initialized");this.isInitializing=!0;try{if(this.destroyed)return;for(;this.pendingRegistrations.length>0;){if(this.destroyed)return;this.processingRegistrations=[...this.pendingRegistrations],this.pendingRegistrations=[];for(const e of this.processingRegistrations){const t=new Set,n=[...e.package.manifest.requires,...e.package.manifest.optional];for(const e of n){const n=this.processingRegistrations.find(t=>t.package.manifest.provides.includes(e));n&&t.add(n.package.manifest.id)}this.resolver.addNode(e.package.manifest.id,[...t])}const e=this.resolver.resolveLoadOrder();for(const t of e){const e=this.processingRegistrations.find(e=>e.package.manifest.id===t);this.instantiatePlugin(e.package.manifest,e.package.create,e.config)}for(const t of e)await this.runPluginInitialization(t);this.processingRegistrations=[],this.resolver=new _n}this.initialized=!0}catch(e){if(e instanceof Error)throw new Ln(`Failed to resolve plugin dependencies: ${e.message}`);throw e}finally{this.isInitializing=!1}})()),this.initPromise}instantiatePlugin(e,t,n){const o={...e.defaultConfig,...n};this.validateConfig(e.id,o,e.defaultConfig);const i=t(this,o);this.validatePlugin(i);for(const t of e.provides){if(this.capabilities.has(t))throw new Nn(`Capability ${t} is already provided by plugin ${this.capabilities.get(t)}`);this.capabilities.set(t,e.id)}this.plugins.set(e.id,i),this.manifests.set(e.id,e),this.status.set(e.id,"registered"),this.configurations.set(e.id,o)}async runPluginInitialization(e){const t=this.plugins.get(e);if(!t)return;const n=this.manifests.get(e),o=this.configurations.get(e);for(const t of n.requires)if(!this.capabilities.has(t))throw new Nn(`Missing required capability: ${t} for plugin ${e}`);this.logger.debug("PluginRegistry","InitializePlugin",`Initializing plugin ${e}`);try{t.initialize&&await t.initialize(o),this.status.set(e,"active"),this.logger.info("PluginRegistry","PluginInitialized",`Plugin ${e} initialized successfully`)}catch(t){throw this.status.set(e,"error"),this.logger.error("PluginRegistry","InitializationFailed",`Plugin ${e} initialization failed`,{error:t}),t}}getPluginConfig(e){const t=this.configurations.get(e);if(!t)throw new On(`Configuration for plugin ${e} not found`);return t}validateConfig(e,t,n){const o=Object.keys(n).filter(e=>!t.hasOwnProperty(e));if(o.length>0)throw new $n(`Missing required configuration keys for plugin ${e}: ${o.join(", ")}`)}async updatePluginConfig(e,t){const n=this.getPlugin(e);if(!n)throw new On(`Plugin ${e} not found`);const o=this.manifests.get(e),i=this.configurations.get(e);if(!o||!i)throw new On(`Plugin ${e} not found`);const r={...i,...t};this.validateConfig(e,r,o.defaultConfig),this.configurations.set(e,r),n.initialize&&await n.initialize(r)}registerPluginBatch(e){for(const t of e)this.registerPlugin(t.package,t.config)}async unregisterPlugin(e){const t=this.plugins.get(e);if(!t)throw new On(`Plugin ${e} is not registered`);const n=this.manifests.get(e);if(!n)throw new On(`Manifest for plugin ${e} not found`);for(const[t,o]of this.manifests.entries()){if(t===e)continue;if([...o.requires,...o.optional].some(e=>n.provides.includes(e)))throw new Nn(`Cannot unregister plugin ${e}: plugin ${t} depends on it`)}try{t.destroy&&await t.destroy();for(const e of n.provides)this.capabilities.delete(e);this.plugins.delete(e),this.manifests.delete(e),this.status.delete(e)}catch(t){if(t instanceof Error)throw new Error(`Failed to unregister plugin ${e}: ${t.message}`);throw t}}getPlugin(e){const t=this.plugins.get(e);return t||null}getCapabilityProvider(e){const t=this.capabilities.get(e);return t?this.getPlugin(t):null}hasCapability(e){return this.capabilities.has(e)}getAllPlugins(){return Array.from(this.plugins.values())}getPluginStatus(e){const t=this.status.get(e);if(!t)throw new On(`Plugin ${e} not found`);return t}validatePlugin(e){if(!e.id)throw new Nn("Plugin must have an id")}validateManifest(e){if(!e.id)throw new Nn("Manifest must have an id");if(!e.name)throw new Nn("Manifest must have a name");if(!e.version)throw new Nn("Manifest must have a version");if(!Array.isArray(e.provides))throw new Nn("Manifest must have a provides array");if(!Array.isArray(e.requires))throw new Nn("Manifest must have a requires array");if(!Array.isArray(e.optional))throw new Nn("Manifest must have an optional array")}isDestroyed(){return this.destroyed}async destroy(){var e;if(this.destroyed)throw new Nn("Registry has already been destroyed");this.destroyed=!0;try{await this.initPromise}catch{}for(const t of Array.from(this.plugins.values()).reverse())await(null==(e=t.destroy)?void 0:e.call(t));this.store.destroy(),this.plugins.clear(),this.manifests.clear(),this.capabilities.clear(),this.status.clear(),this.pendingRegistrations.length=0,this.processingRegistrations.length=0}}function go(e,t){return{package:e,config:t}}function po(e){return"autoMountElements"in e&&"function"==typeof e.autoMountElements}class fo{constructor(e,t){if(this.id=e,this.registry=t,this.cooldownActions={},this.debouncedTimeouts={},this.unsubscribeFromState=null,this.unsubscribeFromCoreStore=null,this.unsubscribeFromStartLoadingDocument=null,this.unsubscribeFromSetDocumentLoaded=null,this.unsubscribeFromCloseDocument=null,this.unsubscribeFromSetScale=null,this.unsubscribeFromSetRotation=null,e!==this.constructor.id)throw new Error(`Plugin ID mismatch: ${e} !== ${this.constructor.id}`);this.engine=this.registry.getEngine(),this.logger=this.registry.getLogger(),this.coreStore=this.registry.getStore(),this.pluginStore=this.coreStore.getPluginStore(this.id),this.unsubscribeFromState=this.pluginStore.subscribeToState((e,t,n)=>{this.onStoreUpdated(n,t)}),this.unsubscribeFromCoreStore=this.coreStore.subscribe((e,t,n)=>{this.onCoreStoreUpdated(n,t),t.core.activeDocumentId!==n.core.activeDocumentId&&this.onActiveDocumentChanged(n.core.activeDocumentId,t.core.activeDocumentId)}),this.unsubscribeFromStartLoadingDocument=this.coreStore.onAction(Fn,e=>{this.onDocumentLoadingStarted(e.payload.documentId)}),this.unsubscribeFromSetDocumentLoaded=this.coreStore.onAction(Hn,e=>{this.onDocumentLoaded(e.payload.documentId)}),this.unsubscribeFromCloseDocument=this.coreStore.onAction(qn,e=>{this.onDocumentClosed(e.payload.documentId)}),this.unsubscribeFromSetScale=this.coreStore.onAction(Xn,(e,t)=>{const n=e.payload.documentId??t.core.activeDocumentId;n&&this.onScaleChanged(n,e.payload.scale)}),this.unsubscribeFromSetRotation=this.coreStore.onAction(Qn,(e,t)=>{const n=e.payload.documentId??t.core.activeDocumentId;n&&this.onRotationChanged(n,e.payload.rotation)}),this.readyPromise=new Promise(e=>{this.readyResolve=e}),this.readyResolve()}provides(){if(!this._capability){const e=this.buildCapability();this._capability=Object.freeze(e)}return this._capability}get state(){return this.pluginStore.getState()}get coreState(){return this.coreStore.getState()}getState(){return this.pluginStore.getState()}getCoreState(){return this.coreStore.getState()}dispatchCoreAction(e){return this.coreStore.dispatchToCore(e)}dispatchToAllPlugins(e){return this.coreStore.dispatch(e)}dispatch(e){return this.pluginStore.dispatch(e)}cooldownDispatch(e,t=100){const n=Date.now();return n-(this.cooldownActions[e.type]||0)>=t&&(this.cooldownActions[e.type]=n,this.dispatch(e),!0)}debouncedDispatch(e,t=100){const n=e.type;this.debouncedTimeouts[n]&&clearTimeout(this.debouncedTimeouts[n]),this.debouncedTimeouts[n]=setTimeout(()=>{this.dispatch(e),delete this.debouncedTimeouts[n]},t)}cancelDebouncedDispatch(e){this.debouncedTimeouts[e]&&(clearTimeout(this.debouncedTimeouts[e]),delete this.debouncedTimeouts[e])}subscribe(e){return this.pluginStore.subscribeToState(e)}subscribeToCoreStore(e){return this.coreStore.subscribe(e)}onStoreUpdated(e,t){}onCoreStoreUpdated(e,t){}onDocumentLoadingStarted(e){}onDocumentLoaded(e){}onDocumentClosed(e){}onActiveDocumentChanged(e,t){}onScaleChanged(e,t){}onRotationChanged(e,t){}destroy(){Object.values(this.debouncedTimeouts).forEach(e=>{clearTimeout(e)}),this.debouncedTimeouts={},this.unsubscribeFromState&&(this.unsubscribeFromState(),this.unsubscribeFromState=null),this.unsubscribeFromCoreStore&&(this.unsubscribeFromCoreStore(),this.unsubscribeFromCoreStore=null),this.unsubscribeFromStartLoadingDocument&&(this.unsubscribeFromStartLoadingDocument(),this.unsubscribeFromStartLoadingDocument=null),this.unsubscribeFromSetDocumentLoaded&&(this.unsubscribeFromSetDocumentLoaded(),this.unsubscribeFromSetDocumentLoaded=null),this.unsubscribeFromCloseDocument&&(this.unsubscribeFromCloseDocument(),this.unsubscribeFromCloseDocument=null),this.unsubscribeFromSetScale&&(this.unsubscribeFromSetScale(),this.unsubscribeFromSetScale=null),this.unsubscribeFromSetRotation&&(this.unsubscribeFromSetRotation(),this.unsubscribeFromSetRotation=null)}ready(){return this.readyPromise}markReady(){this.readyResolve()}resetReady(){this.readyPromise=new Promise(e=>{this.readyResolve=e})}getActiveDocumentId(){const e=this.coreState.core.activeDocumentId;if(!e)throw new Error("No active document");return e}getActiveDocumentIdOrNull(){return this.coreState.core.activeDocumentId}getCoreDocument(e){const t=e??this.getActiveDocumentIdOrNull();return t?this.coreState.core.documents[t]??null:null}getCoreDocumentOrThrow(e){const t=this.getCoreDocument(e);if(!t)throw new Error(`Document not found: ${e??"active"}`);return t}getDocumentPermissions(e){const t=e??this.coreState.core.activeDocumentId;return t?co(this.coreState.core,t):Zt.AllowAll}checkPermission(e,...t){const n=e??this.coreState.core.activeDocumentId;return!n||t.every(e=>lo(this.coreState.core,n,e))}requirePermission(e,...t){const n=e??this.coreState.core.activeDocumentId;if(!n)return;const o=[];for(const e of t)lo(this.coreState.core,n,e)||o.push(e);if(o.length>0){const e=co(this.coreState.core,n);throw new Yt(o,e)}}}class vo{constructor(e,t){this.handler=e,this.options=t,this.lastRun=0,this.handle=e=>{"debounce"===this.options.mode?this.debounce(e):this.throttle(e)}}debounce(e){this.timeoutId&&window.clearTimeout(this.timeoutId),this.timeoutId=window.setTimeout(()=>{this.handler(e),this.timeoutId=void 0},this.options.wait)}throttle(e){if("debounce"===this.options.mode)return;const t=Date.now(),n=this.options.throttleMode||"leading-trailing";t-this.lastRun>=this.options.wait&&("leading-trailing"===n&&this.handler(e),this.lastRun=t),this.timeoutId&&window.clearTimeout(this.timeoutId),this.timeoutId=window.setTimeout(()=>{this.handler(e),this.lastRun=Date.now(),this.timeoutId=void 0},this.options.wait-(t-this.lastRun))}destroy(){this.timeoutId&&window.clearTimeout(this.timeoutId)}}class yo{constructor(e,t){this.handler=e,this.options=t,this.controls=new Map,this.handle=e=>{const t=String(this.options.keyExtractor(e));let n=this.controls.get(t);n||(n=new vo(this.handler,this.baseOptions),this.controls.set(t,n)),n.handle(e)},this.baseOptions={mode:t.mode,wait:t.wait,..."throttle"===t.mode&&"throttleMode"in t?{throttleMode:t.throttleMode}:{}}}destroy(){for(const e of this.controls.values())e.destroy();this.controls.clear()}}function bo(e){return"keyExtractor"in e}function wo(e,t,n){return en?n:e}function xo(e,t,n){if(e===t)return!0;if(null==e||null==t)return e===t;const o=typeof e;if(o!==typeof t)return!1;if("object"===o){n||(n=new Set);const o=function(e,t){return`${ko(e)}__${ko(t)}`}(e,t);if(n.has(o))return!0;n.add(o);const i=Array.isArray(e),r=Array.isArray(t);return i&&r?function(e,t,n){if(e.length!==t.length)return!1;const o=new Array(t.length).fill(!1);e:for(let i=0;ie.forEach(e=>e(t)),on:t=>(e.add(t),()=>e.delete(t)),off:t=>e.delete(t),clear:()=>e.clear()}}function Mo(e,t=xo){const n=new Set,o=new Map;let i=e;const r=(e,t)=>{let r=e,a=()=>{};if(t){if(bo(t)){const n=new yo(e,t);r=n.handle,a=()=>n.destroy()}else{const n=new vo(e,t);r=n.handle,a=()=>n.destroy()}o.set(e,{wrapped:r,destroy:a})}return void 0!==i&&r(i),n.add(r),()=>{n.delete(r),a(),o.delete(e)}};return{get value(){return i},emit(e=void 0){void 0!==i&&t(i,e)||(i=e,(e=>{n.forEach(t=>t(e))})(e))},on:r,off(e){const t=o.get(e);t?(n.delete(t.wrapped),t.destroy(),o.delete(e)):n.delete(e)},clear(){n.clear(),o.forEach(e=>e.destroy()),o.clear()},select:(e,t=xo)=>(n,o)=>{let a;if(void 0!==i){const t=e(i);a=t,n(t)}return r(o=>{const i=e(o);void 0!==a&&t(a,i)||(a=i,n(i))},o)}}}function Ao(e,t){const n=(null==t?void 0:t.cache)??!0,o=(null==t?void 0:t.equality)??xo,i=new Map,r=new Map,a=new Map,s=new Set,l=new Map,c=e=>String(e);return{emit(t,a){const l=c(t);if(n){const e=i.get(l);if(void 0!==e&&o(e,a))return;i.set(l,a)}const d=r.get(l);d&&d.forEach(e=>e(a));const u=e(t,a);s.forEach(e=>e(u))},forScope(e){const t=c(e);return(e,o)=>{const s=(e=>{let t=r.get(e);return t||(t=new Set,r.set(e,t)),t})(t),l=(e=>{let t=a.get(e);return t||(t=new Map,a.set(e,t)),t})(t);let c=e,d=()=>{};if(o){if(bo(o)){const t=new yo(e,o);c=t.handle,d=()=>t.destroy()}else{const t=new vo(e,o);c=t.handle,d=()=>t.destroy()}l.set(e,{wrapped:c,destroy:d})}if(n){const e=i.get(t);void 0!==e&&c(e)}return s.add(c),()=>{s.delete(c),d(),l.delete(e),0===s.size&&r.delete(t),0===l.size&&a.delete(t)}}},onGlobal:(e,t)=>{let n=e,o=()=>{};if(t){if(bo(t)){const i=new yo(e,t);n=i.handle,o=()=>i.destroy()}else{const i=new vo(e,t);n=i.handle,o=()=>i.destroy()}l.set(e,{wrapped:n,destroy:o})}return s.add(n),()=>{s.delete(n),o(),l.delete(e)}},getValue:e=>n?i.get(c(e)):void 0,getScopes:()=>n?Array.from(i.keys()):Array.from(r.keys()),clearScope(e){const t=c(e);n&&i.delete(t);const o=r.get(t);o&&(o.clear(),r.delete(t));const s=a.get(t);s&&(s.forEach(e=>e.destroy()),s.clear(),a.delete(t))},clear(){n&&i.clear(),r.forEach(e=>e.clear()),r.clear(),a.forEach(e=>{e.forEach(e=>e.destroy()),e.clear()}),a.clear(),s.clear(),l.forEach(e=>e.destroy()),l.clear()}}}class Po{constructor(e){this.autoMountElements=[],this.package=e}addUtility(e){return this.autoMountElements.push({component:e,type:"utility"}),this}addWrapper(e){return this.autoMountElements.push({component:e,type:"wrapper"}),this}build(){return{...this.package,autoMountElements:()=>this.autoMountElements}}}function Do(e){return new Po(e)}const Ro=de({registry:null,coreState:null,isInitializing:!0,pluginsReady:!1,activeDocumentId:null,activeDocument:null,documents:{},documentStates:[]});function zo({plugins:e,children:t}){const{utilities:n,wrappers:o}=Re(()=>{const t=[],n=[];for(const o of e){const e=o.package;if(po(e)){const o=e.autoMountElements()||[];for(const e of o)"utility"===e.type?t.push(e.component):"wrapper"===e.type&&n.push(e.component)}}return{utilities:t,wrappers:n}},[e]),i=He(H,{children:[t,n.map((e,t)=>He(e,{},`utility-${t}`))]});return He(H,{children:o.reduce((e,t)=>He(t,{children:e}),i)})}function To({engine:e,config:t,logger:n,onInitialized:o,plugins:i,children:r,autoMountDomElements:a=!0}){const[s,l]=Se(null),[c,d]=Se(null),[u,h]=Se(!0),[m,g]=Se(!1),p=De(o);Ae(()=>{p.current=o},[o]),Ae(()=>{const o={...t,logger:(null==t?void 0:t.logger)??n},r=new mo(e,o);r.registerPluginBatch(i);let a;return(async()=>{var e;if(await r.initialize(),r.isDestroyed())return;const t=r.getStore();d(t.getState().core);const n=t.subscribe((e,n,o)=>{t.isCoreAction(e)&&n.core!==o.core&&d(n.core)});if(await(null==(e=p.current)?void 0:e.call(p,r)),!r.isDestroyed())return r.pluginsReady().then(()=>{r.isDestroyed()||g(!0)}),l(r),h(!1),n;n()})().then(e=>{a=e}).catch(console.error),()=>{null==a||a(),r.destroy(),l(null),d(null),h(!0),g(!1)}},[e,i]);const f=Re(()=>{const e=(null==c?void 0:c.activeDocumentId)??null,t=(null==c?void 0:c.documents)??{},n=(null==c?void 0:c.documentOrder)??[],o=e&&t[e]?t[e]:null,i=n.map(e=>t[e]).filter(e=>null!=e);return{registry:s,coreState:c,isInitializing:u,pluginsReady:m,activeDocumentId:e,activeDocument:o,documents:t,documentStates:i}},[s,c,u,m]),v="function"==typeof r?r(f):r;return He(Ro.Provider,{value:f,children:m&&a?He(zo,{plugins:i,children:v}):v})}function Eo(e){const{registry:t}=function(){const e=Te(Ro);if(void 0===e)throw new Error("useCapability must be used within a PDFContext.Provider");const{registry:t,isInitializing:n}=e;if(n)return e;if(null===t)throw new Error("PDF registry failed to initialize properly");return e}();if(null===t)return{plugin:null,isLoading:!0,ready:new Promise(()=>{})};const n=t.getPlugin(e);if(!n)throw new Error(`Plugin ${e} not found`);return{plugin:n,isLoading:!1,ready:n.ready()}}function _o(e){const{plugin:t,isLoading:n,ready:o}=Eo(e);if(!t)return{provides:null,isLoading:n,ready:o};if(!t.provides)throw new Error(`Plugin ${e} does not provide a capability`);return{provides:t.provides(),isLoading:n,ready:o}}function No(){const{coreState:e}=Te(Ro);return e}function Oo(e){const t=No();return Re(()=>t&&e?t.documents[e]??null:null,[t,e])}Zt.Print,Zt.ModifyContents,Zt.CopyContents,Zt.ModifyAnnotations,Zt.FillForms,Zt.ExtractForAccessibility,Zt.AssembleDocument,Zt.PrintHighQuality;const Lo=[Zt.Print,Zt.ModifyContents,Zt.CopyContents,Zt.ModifyAnnotations,Zt.FillForms,Zt.ExtractForAccessibility,Zt.AssembleDocument,Zt.PrintHighQuality],$o={[Zt.Print]:"print",[Zt.ModifyContents]:"modifyContents",[Zt.CopyContents]:"copyContents",[Zt.ModifyAnnotations]:"modifyAnnotations",[Zt.FillForms]:"fillForms",[Zt.ExtractForAccessibility]:"extractForAccessibility",[Zt.AssembleDocument]:"assembleDocument",[Zt.PrintHighQuality]:"printHighQuality"};function jo(e,t){if(!e)return;if(t in e)return e[t];const n=$o[t];return n&&n in e?e[n]:void 0}function Fo(e,t,n){var o;const i=e.documents[t],r=null==i?void 0:i.permissions,a=e.globalPermissions,s=(null==(o=null==i?void 0:i.document)?void 0:o.permissions)??Zt.AllowAll,l=jo(null==r?void 0:r.overrides,n);if(void 0!==l)return l;const c=jo(null==a?void 0:a.overrides,n);if(void 0!==c)return c;return!((null==r?void 0:r.enforceDocumentPermissions)??(null==a?void 0:a.enforceDocumentPermissions)??!0)||0!==(s&n)}function Uo(e){const t=No();return Re(()=>{var n,o;if(!t)return{permissions:Zt.AllowAll,pdfPermissions:Zt.AllowAll,hasPermission:()=>!0,hasAllPermissions:()=>!0,canPrint:!0,canModifyContents:!0,canCopyContents:!0,canModifyAnnotations:!0,canFillForms:!0,canExtractForAccessibility:!0,canAssembleDocument:!0,canPrintHighQuality:!0};const i=function(e,t){return Lo.reduce((n,o)=>Fo(e,t,o)?n|o:n,0)}(t,e),r=n=>Fo(t,e,n);return{permissions:i,pdfPermissions:(null==(o=null==(n=t.documents[e])?void 0:n.document)?void 0:o.permissions)??Zt.AllowAll,hasPermission:r,hasAllPermissions:(...n)=>n.every(n=>Fo(t,e,n)),canPrint:r(Zt.Print),canModifyContents:r(Zt.ModifyContents),canCopyContents:r(Zt.CopyContents),canModifyAnnotations:r(Zt.ModifyAnnotations),canFillForms:r(Zt.FillForms),canExtractForAccessibility:r(Zt.ExtractForAccessibility),canAssembleDocument:r(Zt.AssembleDocument),canPrintHighQuality:r(Zt.PrintHighQuality)}},[t,e])}const Ho="https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@2.6.2/dist/pdfium.wasm";de(void 0);const Bo="viewport",Wo={id:Bo,name:"Viewport Plugin",version:"1.0.0",provides:["viewport"],requires:[],optional:[],defaultConfig:{viewportGap:10,scrollEndDelay:300}},qo="INIT_VIEWPORT_STATE",Go="CLEANUP_VIEWPORT_STATE",Vo="REGISTER_VIEWPORT",Ko="UNREGISTER_VIEWPORT",Zo="SET_VIEWPORT_METRICS",Yo="SET_VIEWPORT_SCROLL_METRICS",Xo="SET_VIEWPORT_GAP",Qo="SET_SCROLL_ACTIVITY",Jo="SET_SMOOTH_SCROLL_ACTIVITY",ei="ADD_VIEWPORT_GATE",ti="REMOVE_VIEWPORT_GATE";function ni(e,t){return{type:Jo,payload:{documentId:e,isSmoothScrolling:t}}}const oi={viewportMetrics:{width:0,height:0,scrollTop:0,scrollLeft:0,clientWidth:0,clientHeight:0,scrollWidth:0,scrollHeight:0,clientLeft:0,clientTop:0,relativePosition:{x:0,y:0}},isScrolling:!1,isSmoothScrolling:!1,gates:new Set},ii={viewportGap:0,documents:{},activeViewports:new Set,activeDocumentId:null},ri=class extends fo{constructor(e,t,n){var o;super(e,t),this.id=e,this.viewportResize$=Mo(),this.viewportMetrics$=Mo(),this.scrollMetrics$=Mo(),this.scrollActivity$=Mo(),this.gateState$=Mo(),this.scrollRequests$=new Map,n.viewportGap&&this.dispatch((o=n.viewportGap,{type:Xo,payload:o})),this.scrollEndDelay=n.scrollEndDelay||100}onDocumentLoadingStarted(e){this.dispatch(function(e){return{type:qo,payload:{documentId:e}}}(e)),this.scrollRequests$.set(e,So()),this.logger.debug("ViewportPlugin","DocumentOpened",`Initialized viewport state for document: ${e}`)}onDocumentClosed(e){var t;this.dispatch(function(e){return{type:Go,payload:{documentId:e}}}(e)),null==(t=this.scrollRequests$.get(e))||t.clear(),this.scrollRequests$.delete(e),this.logger.debug("ViewportPlugin","DocumentClosed",`Cleaned up viewport state for document: ${e}`)}buildCapability(){return{getViewportGap:()=>this.state.viewportGap,getMetrics:()=>this.getMetrics(),scrollTo:e=>this.scrollTo(e),isScrolling:()=>this.isScrolling(),isSmoothScrolling:()=>this.isSmoothScrolling(),isGated:e=>this.isGated(e),hasGate:(e,t)=>this.hasGate(e,t),getGates:e=>this.getGates(e),forDocument:e=>this.createViewportScope(e),gate:(e,t)=>this.gate(e,t),releaseGate:(e,t)=>this.releaseGate(e,t),isViewportMounted:e=>this.state.activeViewports.has(e),onViewportChange:this.viewportMetrics$.on,onViewportResize:this.viewportResize$.on,onScrollChange:this.scrollMetrics$.on,onScrollActivity:this.scrollActivity$.on,onGateChange:this.gateState$.on}}createViewportScope(e){return{getMetrics:()=>this.getMetrics(e),scrollTo:t=>this.scrollTo(t,e),isScrolling:()=>this.isScrolling(e),isSmoothScrolling:()=>this.isSmoothScrolling(e),isGated:()=>this.isGated(e),hasGate:t=>this.hasGate(t,e),getGates:()=>this.getGates(e),gate:t=>this.gate(t,e),releaseGate:t=>this.releaseGate(t,e),onViewportChange:t=>this.viewportMetrics$.on(n=>{n.documentId===e&&t(n.metrics)}),onScrollChange:t=>this.scrollMetrics$.on(n=>{n.documentId===e&&t(n.scrollMetrics)}),onScrollActivity:t=>this.scrollActivity$.on(n=>{n.documentId===e&&t(n.activity)}),onGateChange:t=>this.gateState$.on(n=>{(null==n?void 0:n.documentId)===e&&t(n)})}}registerViewport(e){if(!this.state.documents[e])throw new Error(`Cannot register viewport for ${e}: document state not found. Document must be opened before registering viewport.`);this.state.activeViewports.has(e)||(this.dispatch(function(e){return{type:Vo,payload:{documentId:e}}}(e)),this.logger.debug("ViewportPlugin","RegisterViewport",`Registered viewport (DOM mounted) for document: ${e}`))}unregisterViewport(e){this.registry.isDestroyed()||this.state.activeViewports.has(e)&&(this.dispatch(function(e){return{type:Ko,payload:{documentId:e}}}(e)),this.logger.debug("ViewportPlugin","UnregisterViewport",`Unregistered viewport (DOM unmounted) for document: ${e}. State preserved.`))}setViewportResizeMetrics(e,t){if(this.registry.isDestroyed())return;this.dispatch(function(e,t){return{type:Zo,payload:{documentId:e,metrics:t}}}(e,t));const n=this.state.documents[e];n&&this.viewportResize$.emit({documentId:e,metrics:n.viewportMetrics})}setViewportScrollMetrics(e,t){if(this.registry.isDestroyed())return;const n=this.state.documents[e];n&&(t.scrollTop===n.viewportMetrics.scrollTop&&t.scrollLeft===n.viewportMetrics.scrollLeft||(this.dispatch(function(e,t){return{type:Yo,payload:{documentId:e,scrollMetrics:t}}}(e,t)),this.bumpScrollActivity(e),this.scrollMetrics$.emit({documentId:e,scrollMetrics:t})))}onScrollRequest(e,t){const n=this.scrollRequests$.get(e);if(!n)throw new Error(`Cannot subscribe to scroll requests for ${e}: document state not initialized`);return n.on(t)}gate(e,t){const n=this.state.documents[t];n?n.gates.has(e)||(this.dispatch(function(e,t){return{type:ei,payload:{documentId:e,key:t}}}(t,e)),this.logger.debug("ViewportPlugin","GateAdded",`Added gate '${e}' for document: ${t}. Total gates: ${n.gates.size+1}`)):this.logger.warn("ViewportPlugin","GateViewport",`Cannot gate viewport for ${t}: document not found`)}releaseGate(e,t){const n=this.state.documents[t];n?n.gates.has(e)&&(this.dispatch(function(e,t){return{type:ti,payload:{documentId:e,key:t}}}(t,e)),this.logger.debug("ViewportPlugin","GateReleased",`Released gate '${e}' for document: ${t}. Remaining gates: ${n.gates.size-1}`)):this.logger.warn("ViewportPlugin","ReleaseGate",`Cannot release gate for ${t}: document not found`)}getViewportState(e){const t=e??this.getActiveDocumentId(),n=this.state.documents[t];if(!n)throw new Error(`Viewport state not found for document: ${t}`);return n}getMetrics(e){return this.getViewportState(e).viewportMetrics}isScrolling(e){return this.getViewportState(e).isScrolling}isSmoothScrolling(e){return this.getViewportState(e).isSmoothScrolling}isGated(e){return this.getViewportState(e).gates.size>0}hasGate(e,t){return this.getViewportState(t).gates.has(e)}getGates(e){const t=this.getViewportState(e);return Array.from(t.gates)}scrollTo(e,t){const n=t??this.getActiveDocumentId(),o=this.getViewportState(n),{x:i,y:r,alignX:a,alignY:s,behavior:l="auto"}=e;"smooth"===l&&this.dispatch(ni(n,!0));const c=o.viewportMetrics;let d=i,u=r;void 0!==a&&(d=i-c.clientWidth*(a/100)),void 0!==s&&(u=r-c.clientHeight*(s/100));const h=this.scrollRequests$.get(n);h&&h.emit({x:d,y:u,behavior:l})}bumpScrollActivity(e){this.debouncedDispatch(function(e,t){return{type:Qo,payload:{documentId:e,isScrolling:t}}}(e,!1),this.scrollEndDelay),this.debouncedDispatch(ni(e,!1),this.scrollEndDelay)}onStoreUpdated(e,t){for(const n in t.documents){const o=e.documents[n],i=t.documents[n];if(o!==i&&(this.viewportMetrics$.emit({documentId:n,metrics:i.viewportMetrics}),!o||o.isScrolling===i.isScrolling&&o.isSmoothScrolling===i.isSmoothScrolling||this.scrollActivity$.emit({documentId:n,activity:{isScrolling:i.isScrolling,isSmoothScrolling:i.isSmoothScrolling}}),o&&o.gates!==i.gates)){const e=Array.from(o.gates),t=Array.from(i.gates),r=t.find(t=>!e.includes(t)),a=e.find(e=>!t.includes(e));this.gateState$.emit({documentId:n,isGated:i.gates.size>0,gates:t,addedGate:r,removedGate:a}),this.logger.debug("ViewportPlugin","GateStateChanged",`Gate state changed for document ${n}. Gates: [${t.join(", ")}], Gated: ${i.gates.size>0}`)}}}async initialize(e){this.logger.info("ViewportPlugin","Initialize","Viewport plugin initialized")}async destroy(){this.viewportMetrics$.clear(),this.viewportResize$.clear(),this.scrollMetrics$.clear(),this.scrollActivity$.clear(),this.gateState$.clear(),this.scrollRequests$.forEach(e=>e.clear()),this.scrollRequests$.clear(),super.destroy()}};ri.id="viewport";let ai=ri;const si={manifest:Wo,create:(e,t)=>new ai(Bo,e,t),reducer:(e=ii,t)=>{switch(t.type){case qo:{const{documentId:n}=t.payload;return{...e,documents:{...e.documents,[n]:{...oi,gates:new Set}}}}case Go:{const{documentId:n}=t.payload,{[n]:o,...i}=e.documents,r=new Set(e.activeViewports);return r.delete(n),{...e,documents:i,activeViewports:r,activeDocumentId:e.activeDocumentId===n?null:e.activeDocumentId}}case Vo:{const{documentId:n}=t.payload,o=new Set(e.activeViewports);return o.add(n),{...e,activeViewports:o,activeDocumentId:e.activeDocumentId??n}}case Ko:{const{documentId:n}=t.payload,o=new Set(e.activeViewports);return o.delete(n),{...e,activeViewports:o}}case"SET_ACTIVE_VIEWPORT_DOCUMENT":return{...e,activeDocumentId:t.payload};case Xo:return{...e,viewportGap:t.payload};case Zo:{const{documentId:n,metrics:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,viewportMetrics:{width:o.width,height:o.height,scrollTop:o.scrollTop,scrollLeft:o.scrollLeft,clientWidth:o.clientWidth,clientHeight:o.clientHeight,scrollWidth:o.scrollWidth,scrollHeight:o.scrollHeight,clientLeft:o.clientLeft,clientTop:o.clientTop,relativePosition:{x:o.scrollWidth<=o.clientWidth?0:o.scrollLeft/(o.scrollWidth-o.clientWidth),y:o.scrollHeight<=o.clientHeight?0:o.scrollTop/(o.scrollHeight-o.clientHeight)}}}}}:e}case Yo:{const{documentId:n,scrollMetrics:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,viewportMetrics:{...i.viewportMetrics,scrollTop:o.scrollTop,scrollLeft:o.scrollLeft},isScrolling:!0}}}:e}case Qo:{const{documentId:n,isScrolling:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,isScrolling:o}}}:e}case Jo:{const{documentId:n,isSmoothScrolling:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,isSmoothScrolling:o}}}:e}case ei:{const{documentId:n,key:o}=t.payload,i=e.documents[n];if(!i)return e;const r=new Set(i.gates);return r.add(o),{...e,documents:{...e.documents,[n]:{...i,gates:r}}}}case ti:{const{documentId:n,key:o}=t.payload,i=e.documents[n];if(!i)return e;const r=new Set(i.gates);return r.delete(o),{...e,documents:{...e.documents,[n]:{...i,gates:r}}}}default:return e}},initialState:ii},li=de(null),ci=()=>_o(ai.id);function di(e){const{plugin:t}=Eo(ai.id),n=De(null);return Pe(()=>{if(!t)return;const o=n.current;if(!o)return;try{t.registerViewport(e)}catch(t){return void console.error(`Failed to register viewport for document ${e}:`,t)}const i=()=>{t.setViewportScrollMetrics(e,{scrollTop:o.scrollTop,scrollLeft:o.scrollLeft})};o.addEventListener("scroll",i);const r=new ResizeObserver(()=>{t.setViewportResizeMetrics(e,{width:o.offsetWidth,height:o.offsetHeight,clientWidth:o.clientWidth,clientHeight:o.clientHeight,scrollTop:o.scrollTop,scrollLeft:o.scrollLeft,scrollWidth:o.scrollWidth,scrollHeight:o.scrollHeight,clientLeft:o.clientLeft,clientTop:o.clientTop})});r.observe(o);const a=t.onScrollRequest(e,({x:e,y:t,behavior:n="auto"})=>{requestAnimationFrame(()=>{o.scrollTo({left:e,top:t,behavior:n})})});return()=>{t.unregisterViewport(e),r.disconnect(),o.removeEventListener("scroll",i),a()}},[t,e]),n}function ui({children:e,documentId:t,...n}){const[o,i]=Se(0),r=di(t),{provides:a}=ci(),s=(e=>{const{provides:t}=ci(),[n,o]=Se((null==t?void 0:t.isGated(e))??!1);return Ae(()=>{if(t)return o(t.isGated(e)),t.onGateChange(t=>{t.documentId===e&&o(t.isGated)})},[t,e]),n})(t);Ae(()=>{a&&i(a.getViewportGap())},[a]);const{style:l,...c}=n;return He(li.Provider,{value:r,children:He("div",{...c,ref:r,style:{width:"100%",height:"100%",overflow:"auto",..."object"==typeof l?l:{},padding:`${o}px`},children:!s&&e})})}var hi=(e=>(e.Vertical="vertical",e.Horizontal="horizontal",e))(hi||{});class mi{constructor(e){this.pageGap=e.pageGap??20,this.viewportGap=e.viewportGap??20,this.bufferSize=e.bufferSize??2}getVisibleRange(e,t,n){const o=this.getScrollOffset(e),i=o,r=o+this.getClientSize(e);let a=0;for(;ae.pageNumber),l=t.slice(o.start,o.end+1).flatMap(e=>e.index),c=this.determineCurrentPage(a),d=t[o.start],u=t[o.end],h=d?d.offset*n:0,m=u?(t[t.length-1].offset+t[t.length-1].height)*n-(u.offset+u.height)*n:0;return{currentPage:c,visiblePages:s,pageVisibilityMetrics:a,renderedPageIndexes:l,scrollOffset:{x:e.scrollLeft,y:e.scrollTop},startSpacing:h,endSpacing:m}}calculatePageVisibility(e,t,n,o){const i=[],r=o??Math.max(...e.map(e=>e.width));return e.forEach(e=>{const o=e.width{const a=(e.x+o)*n,s=e.y*n,l=a+r.x*n,c=s+r.y*n,d=r.rotatedWidth*n,u=r.rotatedHeight*n,h=t.scrollLeft,m=t.scrollTop,g=h+t.clientWidth,p=m+t.clientHeight,f=Math.max(l,h),v=Math.max(c,m),y=Math.min(l+d,g),b=Math.min(c+u,p);if(fe.visiblePercentage)),n=e.filter(e=>e.visiblePercentage===t);return 1===n.length?n[0].pageNumber:n.sort((e,t)=>e.pageNumber-t.pageNumber)[0].pageNumber}getRectLocationForPage(e,t,n){const o=t.find(t=>t.pageNumbers.includes(e));if(!o)return null;const i=o.pageLayouts.find(t=>t.pageNumber===e);if(!i)return null;let r=0;if(n){const e=n.width;o.width{let o=0;const i=e.map(e=>{const t={pageNumber:e.index+1,pageIndex:e.index,x:o,y:0,width:e.size.width,height:e.size.height,rotatedWidth:e.rotatedSize.width,rotatedHeight:e.rotatedSize.height};return o+=e.rotatedSize.width+this.pageGap,t}),r=e.reduce((t,n,o)=>t+n.rotatedSize.width+(oe.rotatedSize.height)),s={id:`item-${n}`,x:0,y:t,offset:t,width:r,height:a,pageLayouts:i,pageNumbers:e.map(e=>e.index+1),index:n};return t+=a+this.pageGap,s})}getTotalContentSize(e){if(0===e.length)return{width:0,height:0};return{width:Math.max(...e.map(e=>e.width)),height:e[e.length-1].y+e[e.length-1].height}}getScrollOffset(e){return e.scrollTop}getClientSize(e){return e.clientHeight}}class pi extends mi{constructor(e){super(e)}createVirtualItems(e){let t=0;return e.map((e,n)=>{let o=0;const i=e.map(e=>{const t={pageNumber:e.index+1,pageIndex:e.index,x:o,y:0,width:e.size.width,height:e.size.height,rotatedWidth:e.rotatedSize.width,rotatedHeight:e.rotatedSize.height};return o+=e.rotatedSize.width+this.pageGap,t}),r=e.reduce((t,n,o)=>t+n.rotatedSize.width+(oe.rotatedSize.height)),s={id:`item-${n}`,x:t,y:0,offset:t,width:r,height:a,pageLayouts:i,pageNumbers:e.map(e=>e.index+1),index:n};return t+=r+this.pageGap,s})}getTotalContentSize(e){if(0===e.length)return{width:0,height:0};return{width:e[e.length-1].x+e[e.length-1].width,height:Math.max(...e.map(e=>e.height))}}getScrollOffset(e){return e.scrollLeft}getClientSize(e){return e.clientWidth}}const fi="INIT_SCROLL_STATE",vi="CLEANUP_SCROLL_STATE",yi="UPDATE_DOCUMENT_SCROLL_STATE",bi="SET_SCROLL_STRATEGY";function wi(e,t){return{type:yi,payload:{documentId:e,state:t}}}const xi={isChanging:!1,targetPage:1,fromPage:1,startTime:0},Ci=class extends fo{constructor(e,t,n){var o,i,r;super(e,t),this.id=e,this.config=n,this.elevatedPages=new Map,this.strategies=new Map,this.layoutReady=new Set,this.initialLayoutFired=new Set,this.scrollerLayoutEmitters=new Map,this.pageChange$=Mo(),this.scroll$=Mo(),this.layoutChange$=Mo(),this.pageChangeState$=Mo(),this.layoutReady$=Mo(),this.state$=Mo(),this.viewport=this.registry.getPlugin("viewport").provides(),this.spread=(null==(o=this.registry.getPlugin("spread"))?void 0:o.provides())??null,this.viewport.onScrollActivity(e=>{const t=this.getDocumentState(e.documentId);(null==t?void 0:t.pageChangeState.isChanging)&&!e.activity.isSmoothScrolling&&this.completePageChange(e.documentId)}),null==(i=this.spread)||i.onSpreadChange(e=>{this.refreshDocumentLayout(e.documentId)});const a=null==(r=this.registry.getPlugin("interaction-manager"))?void 0:r.provides();a&&a.onPageActivityChange(e=>{let t=this.elevatedPages.get(e.documentId);e.hasActivity?(t||(t=new Set,this.elevatedPages.set(e.documentId,t)),t.add(e.pageIndex)):null==t||t.delete(e.pageIndex),this.pushScrollerLayout(e.documentId)}),this.viewport.onViewportChange(e=>{const t=this.getDocumentState(e.documentId);if(!t)return;const n=this.computeMetrics(e.documentId,e.metrics);this.layoutReady.has(e.documentId)?this.commitMetrics(e.documentId,n):this.commitMetrics(e.documentId,{...n,scrollOffset:t.scrollOffset})})}onDocumentLoadingStarted(e){const t=this.getCoreDocument(e);if(!t)return;const n=this.createDocumentState(t);this.dispatch(function(e,t){return{type:fi,payload:{documentId:e,state:t}}}(e,n));const o=this.createStrategy(n.strategy);this.strategies.set(e,o),this.scrollerLayoutEmitters.set(e,Mo())}onDocumentLoaded(e){var t;const n=this.getCoreDocument(e);n&&(this.dispatch(wi(e,{totalPages:(null==(t=n.document)?void 0:t.pageCount)??0})),this.refreshDocumentLayout(e),this.logger.debug("ScrollPlugin","DocumentOpened",`Initialized scroll state for document: ${e}`))}onDocumentClosed(e){this.strategies.delete(e),this.layoutReady.delete(e),this.initialLayoutFired.delete(e),this.elevatedPages.delete(e);const t=this.scrollerLayoutEmitters.get(e);t&&(t.clear(),this.scrollerLayoutEmitters.delete(e)),this.dispatch(function(e){return{type:vi,payload:e}}(e)),this.logger.debug("ScrollPlugin","DocumentClosed",`Cleaned up scroll state for document: ${e}`)}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const n=this.viewport.forDocument(e),o=this.computeMetrics(e,n.getMetrics());this.commitMetrics(e,o)}onRotationChanged(e){this.refreshDocumentLayout(e)}onScrollerData(e,t){const n=this.scrollerLayoutEmitters.get(e);if(!n)throw new Error(`No scroller layout emitter found for document: ${e}`);return n.on(t)}getScrollerLayout(e){const t=this.getDocumentState(e),n=this.getCoreDocumentOrThrow(e);if(!t||!n)throw new Error(`Cannot get scroller layout for document: ${e}`);return o=t,i=n.scale,r=this.elevatedPages.get(e),{startSpacing:o.startSpacing,endSpacing:o.endSpacing,totalWidth:o.totalContentSize.width*i,totalHeight:o.totalContentSize.height*i,pageGap:o.pageGap*i,strategy:o.strategy,items:o.renderedPageIndexes.map(e=>({...o.virtualItems[e],pageLayouts:o.virtualItems[e].pageLayouts.map(e=>({...e,rotatedWidth:e.rotatedWidth*i,rotatedHeight:e.rotatedHeight*i,width:e.width*i,height:e.height*i,elevated:(null==r?void 0:r.has(e.pageIndex))??!1}))}))};var o,i,r}setLayoutReady(e){if(this.layoutReady.has(e))return;const t=this.getDocumentState(e);if(!t)return;this.layoutReady.add(e);const n=!this.initialLayoutFired.has(e);n&&this.initialLayoutFired.add(e);this.viewport.forDocument(e).scrollTo({...t.scrollOffset,behavior:"instant"}),this.layoutReady$.emit({documentId:e,isInitial:n,pageNumber:t.currentPage,totalPages:t.totalPages})}clearLayoutReady(e){this.layoutReady.delete(e)}buildCapability(){return{getCurrentPage:()=>this.getCurrentPage(),getTotalPages:()=>this.getTotalPages(),getPageChangeState:()=>this.getPageChangeState(),scrollToPage:e=>this.scrollToPage(e),scrollToNextPage:e=>this.scrollToNextPage(e),scrollToPreviousPage:e=>this.scrollToPreviousPage(e),getMetrics:e=>this.getMetrics(e),getLayout:()=>this.getLayout(),getRectPositionForPage:(e,t,n,o)=>this.getRectPositionForPage(e,t,n,o),forDocument:e=>this.createScrollScope(e),setScrollStrategy:(e,t)=>this.setScrollStrategyForDocument(e,t),getPageGap:()=>this.state.defaultPageGap,onPageChange:this.pageChange$.on,onScroll:this.scroll$.on,onLayoutChange:this.layoutChange$.on,onLayoutReady:this.layoutReady$.on,onPageChangeState:this.pageChangeState$.on,onStateChange:this.state$.on}}createScrollScope(e){return{getCurrentPage:()=>this.getCurrentPage(e),getTotalPages:()=>this.getTotalPages(e),getPageChangeState:()=>this.getPageChangeState(e),scrollToPage:t=>this.scrollToPage(t,e),scrollToNextPage:t=>this.scrollToNextPage(t,e),scrollToPreviousPage:t=>this.scrollToPreviousPage(t,e),getSpreadPagesWithRotatedSize:()=>this.getSpreadPagesWithRotatedSize(e),getMetrics:t=>this.getMetrics(t,e),getLayout:()=>this.getLayout(e),getRectPositionForPage:(t,n,o,i)=>this.getRectPositionForPage(t,n,o,i,e),setScrollStrategy:t=>this.setScrollStrategyForDocument(t,e),onPageChange:t=>this.pageChange$.on(n=>{n.documentId===e&&t(n)}),onScroll:t=>this.scroll$.on(n=>{n.documentId===e&&t(n.metrics)}),onLayoutChange:t=>this.layoutChange$.on(n=>{n.documentId===e&&t(n.layout)})}}getDocumentState(e){const t=e??this.getActiveDocumentId();return this.state.documents[t]??null}getDocumentStateOrThrow(e){const t=this.getDocumentState(e);if(!t)throw new Error(`Scroll state not found for document: ${e??"active"}`);return t}getStrategy(e){const t=e??this.getActiveDocumentId(),n=this.strategies.get(t);if(!n)throw new Error(`Strategy not found for document: ${t}`);return n}createStrategy(e){const t={pageGap:this.state.defaultPageGap,viewportGap:this.viewport.getViewportGap(),bufferSize:this.state.defaultBufferSize};return e===hi.Horizontal?new pi(t):new gi(t)}createDocumentState(e){var t;return{virtualItems:[],totalPages:(null==(t=e.document)?void 0:t.pageCount)??0,currentPage:1,totalContentSize:{width:0,height:0},strategy:this.state.defaultStrategy,pageGap:this.state.defaultPageGap,visiblePages:[],pageVisibilityMetrics:[],renderedPageIndexes:[],scrollOffset:{x:0,y:0},startSpacing:0,endSpacing:0,pageChangeState:xi}}startPageChange(e,t,n="smooth"){const o=this.getDocumentState(e);if(!o)return;const i={isChanging:!0,targetPage:t,fromPage:o.currentPage,startTime:Date.now()};this.dispatch(wi(e,{pageChangeState:i})),"instant"===n&&this.completePageChange(e)}completePageChange(e){const t=this.getDocumentState(e);if(!t||!t.pageChangeState.isChanging)return;const n={isChanging:!1,targetPage:t.pageChangeState.targetPage,fromPage:t.pageChangeState.fromPage,startTime:t.pageChangeState.startTime};this.dispatch(wi(e,{pageChangeState:n}))}computeLayout(e,t){const n=this.getStrategy(e),o=n.createVirtualItems(t);return{virtualItems:o,totalContentSize:n.getTotalContentSize(o)}}computeMetrics(e,t,n){const o=this.getCoreDocumentOrThrow(e),i=this.getDocumentState(e),r=this.getStrategy(e);if(!i)throw new Error(`Document state not found: ${e}`);return r.handleScroll(t,n??i.virtualItems,o.scale)}commitMetrics(e,t){const n=this.getDocumentState(e);n&&(this.dispatch(wi(e,t)),this.scroll$.emit({documentId:e,metrics:t}),t.currentPage!==n.currentPage&&this.pageChange$.emit({documentId:e,pageNumber:t.currentPage,totalPages:n.totalPages}),this.pushScrollerLayout(e))}pushScrollerLayout(e){const t=this.scrollerLayoutEmitters.get(e);if(t)try{const n=this.getScrollerLayout(e);t.emit(n)}catch(e){}}refreshDocumentLayout(e){const t=this.coreState.core.documents[e],n=this.getDocumentState(e);if(!t||!n||"loaded"!==t.status)return;const o=this.getSpreadPagesWithRotatedSize(e),i=this.computeLayout(e,o),r=this.viewport.forDocument(e),a=this.computeMetrics(e,r.getMetrics(),i.virtualItems);this.dispatch(wi(e,{...i,...a})),this.layoutChange$.emit({documentId:e,layout:i}),this.pushScrollerLayout(e)}getSpreadPagesWithRotatedSize(e){var t,n;const o=e??this.getActiveDocumentId(),i=this.coreState.core.documents[o];if(!i)throw new Error(`Document ${o} not loaded`);return((null==(t=this.spread)?void 0:t.forDocument(o).getSpreadPages())||(null==(n=i.document)?void 0:n.pages.map(e=>[e]))||[]).map(e=>e.map(e=>{const t=((e.rotation??0)+i.rotation)%4;return{...e,rotatedSize:Ke(e.size,t,1)}}))}getCurrentPage(e){return this.getDocumentStateOrThrow(e).currentPage}getTotalPages(e){return this.getDocumentStateOrThrow(e).totalPages}getPageChangeState(e){return this.getDocumentStateOrThrow(e).pageChangeState}scrollToPage(e,t){var n;const o=t??this.getActiveDocumentId(),i=this.getDocumentStateOrThrow(o),r=this.getStrategy(o),a=this.getCoreDocumentOrThrow(o),{pageNumber:s,behavior:l="smooth",pageCoordinates:c,alignX:d,alignY:u}=e;this.startPageChange(o,s,l);const h=null==(n=a.document)?void 0:n.pages[s-1],m=(((null==h?void 0:h.rotation)??0)+a.rotation)%4,g=r.getScrollPositionForPage(s,i.virtualItems,a.scale,m,c);if(g){this.viewport.forDocument(o).scrollTo({...g,behavior:l,alignX:d,alignY:u})}else this.completePageChange(o)}scrollToNextPage(e="smooth",t){const n=t??this.getActiveDocumentId(),o=this.getDocumentStateOrThrow(n),i=this.getStrategy(n),r=this.getCoreDocumentOrThrow(n),a=o.virtualItems.findIndex(e=>e.pageNumbers.includes(o.currentPage));if(a>=0&&ae.pageNumbers.includes(o.currentPage));if(a>0){const t=o.virtualItems[a-1].pageNumbers[0];this.startPageChange(n,t,e);const s=i.getScrollPositionForPage(t,o.virtualItems,r.scale,r.rotation);if(s){this.viewport.forDocument(n).scrollTo({...s,behavior:e})}else this.completePageChange(n)}}getMetrics(e,t){const n=t??this.getActiveDocumentId();if(e)return this.computeMetrics(n,e);const o=this.viewport.forDocument(n);return this.computeMetrics(n,o.getMetrics())}getLayout(e){const t=this.getDocumentStateOrThrow(e);return{virtualItems:t.virtualItems,totalContentSize:t.totalContentSize}}getRectPositionForPage(e,t,n,o,i){var r;const a=i??this.getActiveDocumentId(),s=this.getDocumentStateOrThrow(a),l=this.getStrategy(a),c=this.getCoreDocumentOrThrow(a);let d=o;if(void 0===d){const t=null==(r=c.document)?void 0:r.pages[e];d=(((null==t?void 0:t.rotation)??0)+c.rotation)%4}return l.getRectPositionForPage(e+1,s.virtualItems,n??c.scale,d,t)}setScrollStrategyForDocument(e,t){const n=t??this.getActiveDocumentId(),o=this.getDocumentState(n);if(!o||o.strategy===e)return;const i=this.createStrategy(e);this.strategies.set(n,i),this.dispatch(function(e,t){return{type:bi,payload:{documentId:e,strategy:t}}}(n,e)),this.refreshDocumentLayout(n)}onStoreUpdated(e,t){for(const n in t.documents){const o=e.documents[n],i=t.documents[n];o!==i&&(this.state$.emit(i),(null==o?void 0:o.pageChangeState)!==i.pageChangeState&&this.pageChangeState$.emit({documentId:n,state:i.pageChangeState}),this.pushScrollerLayout(n))}}async initialize(){this.logger.info("ScrollPlugin","Initialize","Scroll plugin initialized")}async destroy(){this.strategies.clear(),this.layoutReady.clear(),this.initialLayoutFired.clear(),this.elevatedPages.clear();for(const e of this.scrollerLayoutEmitters.values())e.clear();this.scrollerLayoutEmitters.clear(),this.pageChange$.clear(),this.scroll$.clear(),this.layoutChange$.clear(),this.pageChangeState$.clear(),this.layoutReady$.clear(),this.state$.clear(),super.destroy()}};Ci.id="scroll";let Ii=Ci;const ki="scroll",Si={manifest:{id:ki,name:"Scroll Plugin",version:"1.0.0",provides:["scroll"],requires:["viewport"],optional:["spread","interaction-manager"],defaultConfig:{defaultPageGap:10,defaultBufferSize:4,defaultStrategy:hi.Vertical}},create:(e,t)=>new Ii(ki,e,t),reducer:(e,t)=>{switch(t.type){case fi:{const{documentId:n,state:o}=t.payload;return{...e,documents:{...e.documents,[n]:o}}}case vi:{const{[t.payload]:n,...o}=e.documents;return{...e,documents:o}}case yi:{const{documentId:n,state:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,...o}}}:e}case bi:{const{documentId:n,strategy:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,strategy:o}}}:e}default:return e}},initialState:(e,t)=>((e,t)=>({defaultStrategy:t.defaultStrategy??hi.Vertical,defaultPageGap:t.defaultPageGap??10,defaultBufferSize:t.defaultBufferSize??2,documents:{}}))(0,t)},Mi=()=>_o(Ii.id),Ai=e=>{const{provides:t}=Mi(),[n,o]=Se(1),[i,r]=Se(1);return Ae(()=>{if(!t||!e)return;const n=t.forDocument(e);return o(n.getCurrentPage()),r(n.getTotalPages()),t.onPageChange(t=>{t.documentId===e&&(o(t.pageNumber),r(t.totalPages))})},[t,e]),{provides:(null==t?void 0:t.forDocument(e))??null,state:{currentPage:n,totalPages:i}}};function Pi({documentId:e,renderPage:t,...n}){const{plugin:o}=Eo(Ii.id),[i,r]=Se({layout:null,docId:null});Ae(()=>{if(!o||!e)return;const t=o.onScrollerData(e,t=>{r({layout:t,docId:e})});return()=>{t(),r({layout:null,docId:null}),o.clearLayoutReady(e)}},[o,e]);const a=i.docId===e?i.layout:null;return Pe(()=>{o&&e&&a&&o.setLayoutReady(e)},[o,e,a]),a?He("div",{...n,style:{width:`${a.totalWidth}px`,height:`${a.totalHeight}px`,position:"relative",boxSizing:"border-box",margin:"0 auto",...a.strategy===hi.Horizontal&&{display:"flex",flexDirection:"row"}},children:[He("div",{style:{...a.strategy===hi.Horizontal?{width:a.startSpacing,height:"100%",flexShrink:0}:{height:a.startSpacing,width:"100%"}}}),He("div",{style:{gap:a.pageGap,display:"flex",alignItems:"center",position:"relative",boxSizing:"border-box",...a.strategy===hi.Horizontal?{flexDirection:"row",minHeight:"100%"}:{flexDirection:"column",minWidth:"fit-content"}},children:a.items.map(e=>He("div",{style:{display:"flex",justifyContent:"center",gap:a.pageGap},children:e.pageLayouts.map(e=>He("div",{style:{width:`${e.rotatedWidth}px`,height:`${e.rotatedHeight}px`,position:"relative",zIndex:e.elevated?1:void 0},children:t({...e})},e.pageNumber))},e.pageNumbers[0]))}),He("div",{style:{...a.strategy===hi.Horizontal?{width:a.endSpacing,height:"100%",flexShrink:0}:{height:a.endSpacing,width:"100%"}}})]}):null}var Di=(e=>(e.None="none",e.Odd="odd",e.Even="even",e))(Di||{});const Ri="SPREAD/INIT_STATE",zi="SPREAD/CLEANUP_STATE",Ti="SPREAD/SET_SPREAD_MODE",Ei="SPREAD/SET_PAGE_GROUPING";function _i(e,t){return{type:Ei,payload:{documentId:e,grouping:t}}}const Ni=class extends fo{constructor(e,t,n){var o;super(e,t),this.spreadEmitter$=Mo(),this.defaultSpreadMode=n.defaultSpreadMode??Di.None,this.viewport=(null==(o=t.getPlugin("viewport"))?void 0:o.provides())??null}onDocumentLoadingStarted(e){var t;const n={spreadMode:this.defaultSpreadMode};this.dispatch(function(e,t){return{type:Ri,payload:{documentId:e,state:t}}}(e,n)),null==(t=this.viewport)||t.gate("spread",e),this.logger.debug("SpreadPlugin","DocumentOpened",`Initialized spread state for document: ${e}`)}onDocumentLoaded(e){var t;const n=this.coreState.core.documents[e];if(null==n?void 0:n.document){const t=this.calculatePageGrouping(e,n.document.pages.length);this.dispatch(_i(e,t))}null==(t=this.viewport)||t.releaseGate("spread",e)}onDocumentClosed(e){this.dispatch(function(e){return{type:zi,payload:e}}(e)),this.logger.debug("SpreadPlugin","DocumentClosed",`Cleaned up spread state for document: ${e}`)}buildCapability(){return{setSpreadMode:e=>this.setSpreadModeForDocument(e),getSpreadMode:()=>this.getSpreadModeForDocument(),getSpreadPages:()=>this.getSpreadPages(),forDocument:e=>this.createSpreadScope(e),onSpreadChange:this.spreadEmitter$.on}}createSpreadScope(e){return{setSpreadMode:t=>this.setSpreadModeForDocument(t,e),getSpreadMode:()=>this.getSpreadModeForDocument(e),getSpreadPages:()=>this.getSpreadPages(e),onSpreadChange:t=>this.spreadEmitter$.on(n=>{n.documentId===e&&t(n.spreadMode)})}}getDocumentState(e){const t=e??this.getActiveDocumentId();return this.state.documents[t]??null}getDocumentStateOrThrow(e){const t=this.getDocumentState(e);if(!t)throw new Error(`Spread state not found for document: ${e??"active"}`);return t}setSpreadModeForDocument(e,t){const n=t??this.getActiveDocumentId(),o=this.getDocumentStateOrThrow(n),i=this.coreState.core.documents[n];if(!(null==i?void 0:i.document))throw new Error(`Document ${n} not loaded`);if(o.spreadMode!==e){this.dispatch(function(e,t){return{type:Ti,payload:{documentId:e,spreadMode:t}}}(n,e));const t=this.calculatePageGrouping(n,i.document.pages.length);this.dispatch(_i(n,t)),this.spreadEmitter$.emit({documentId:n,spreadMode:e})}}getSpreadModeForDocument(e){return this.getDocumentStateOrThrow(e).spreadMode}calculatePageGrouping(e,t){switch(this.getDocumentStateOrThrow(e).spreadMode){case Di.None:return Array.from({length:t},(e,t)=>[t]);case Di.Odd:return Array.from({length:Math.ceil(t/2)},(e,n)=>{const o=[2*n];return 2*n+1{const o=[1+2*n];return 1+2*n+1[t])}}getSpreadPages(e){const t=e??this.getActiveDocumentId(),n=this.coreState.core.documents[t],o=this.getDocumentStateOrThrow(t);if(!(null==n?void 0:n.document))throw new Error(`Document ${t} not loaded`);const i=o.pageGrouping??[],r=n.document.pages;return i.map(e=>e.map(e=>r[e]).filter(Boolean))}onStoreUpdated(e,t){for(const n in t.documents){const o=e.documents[n],i=t.documents[n];(null==o?void 0:o.spreadMode)!==i.spreadMode&&this.logger.debug("SpreadPlugin","SpreadModeChanged",`Spread mode changed for document ${n}: ${(null==o?void 0:o.spreadMode)??Di.None} -> ${i.spreadMode}`)}}async initialize(e){this.logger.info("SpreadPlugin","Initialize","Spread plugin initialized")}async destroy(){this.spreadEmitter$.clear(),super.destroy()}};Ni.id="spread";let Oi=Ni;const Li="spread",$i={id:Li,name:"Spread Plugin",version:"1.0.0",provides:["spread"],requires:[],optional:["viewport"],defaultConfig:{}};Di.None;const ji={documents:{},activeDocumentId:null},Fi={manifest:$i,create:(e,t)=>new Oi(Li,e,t),reducer:(e=ji,t)=>{switch(t.type){case Ri:{const{documentId:n,state:o}=t.payload;return{...e,documents:{...e.documents,[n]:o},activeDocumentId:e.activeDocumentId??n}}case zi:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i,activeDocumentId:e.activeDocumentId===n?null:e.activeDocumentId}}case"SPREAD/SET_ACTIVE_DOCUMENT":return{...e,activeDocumentId:t.payload};case Ti:{const{documentId:n,spreadMode:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,spreadMode:o}}}:e}case Ei:{const{documentId:n,grouping:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,pageGrouping:o}}}:e}default:return e}},initialState:ji},Ui="ui",Hi={id:Ui,name:"UI Plugin",version:"1.0.0",provides:["ui"],requires:[],optional:["i18n"],defaultConfig:{schema:{id:"empty",version:"1.0.0",toolbars:{},menus:{},sidebars:{},modals:{},selectionMenus:{}}}},Bi="UI/INIT_STATE",Wi="UI/CLEANUP_STATE",qi="UI/SET_ACTIVE_TOOLBAR",Gi="UI/CLOSE_TOOLBAR_SLOT",Vi="UI/SET_ACTIVE_SIDEBAR",Ki="UI/CLOSE_SIDEBAR_SLOT",Zi="UI/SET_SIDEBAR_TAB",Yi="UI/OPEN_MODAL",Xi="UI/CLOSE_MODAL",Qi="UI/CLEAR_MODAL",Ji="UI/OPEN_MENU",er="UI/CLOSE_MENU",tr="UI/CLOSE_ALL_MENUS",nr="UI/SET_OVERLAY_ENABLED",or="UI/SET_DISABLED_CATEGORIES",ir="UI/SET_HIDDEN_ITEMS",rr=(e,t,n,o,i)=>({type:Vi,payload:{documentId:e,placement:t,slot:n,sidebarId:o,activeTab:i}}),ar=(e,t,n)=>({type:Ki,payload:{documentId:e,placement:t,slot:n}}),sr=(e,t)=>({type:Ji,payload:{documentId:e,menuState:t}}),lr=(e,t)=>({type:er,payload:{documentId:e,menuId:t}}),cr=(e,t,n)=>({type:nr,payload:{documentId:e,overlayId:t,enabled:n}}),dr=e=>({type:or,payload:{categories:e}}),ur=e=>({type:ir,payload:{hiddenItems:e}});function hr(e,t){if(!t)return e;const n={...e};for(const[e,o]of Object.entries(t))n[e]?n[e]={...n[e],...o,items:o.items??n[e].items,responsive:o.responsive??n[e].responsive}:n[e]=o;return n}function mr(e,t){if(!t)return e;const n={...e};for(const[e,o]of Object.entries(t))n[e]?n[e]={...n[e],...o,items:o.items??n[e].items}:n[e]=o;return n}function gr(e,t){if(!t)return e;const n={...e};for(const[e,o]of Object.entries(t))n[e]?n[e]={...n[e],...o,content:o.content??n[e].content}:n[e]=o;return n}function pr(e,t){var n;if(!(null==(n=e.responsive)?void 0:n.breakpoints))return null;const o=function(e,t,n){if(!n||!(null==t?void 0:t.groups))return e;const o=t.groups.find(e=>e.locales.includes(n));if(!o)return e;const i={};for(const[t,n]of Object.entries(e)){const e=o.breakpoints[t];e?i[t]={minWidth:n.minWidth,maxWidth:n.maxWidth,hide:e.replaceHide?e.replaceHide:[...n.hide||[],...e.hide||[]],show:e.replaceShow?e.replaceShow:[...n.show||[],...e.show||[]]}:i[t]=n}return i}(e.responsive.breakpoints,e.responsive.localeOverrides,t),i=new Map,r=new Map;for(const[e,t]of Object.entries(o))r.set(e,{minWidth:t.minWidth,maxWidth:t.maxWidth});const a=new Set,s=e=>{e.forEach(e=>{a.add(e.id),"group"===e.type&&e.items&&s(e.items),"tab-group"===e.type&&e.tabs&&s(e.tabs),"section"===e.type&&e.items&&s(e.items)})};s(e.items);for(const e of a){const t=[];let n=!0;const r=Array.from(Object.entries(o)).sort((e,t)=>(e[1].minWidth??0)-(t[1].minWidth??0));r.forEach(([o,i],r)=>{var a,s;const l=null==(a=i.hide)?void 0:a.includes(e),c=null==(s=i.show)?void 0:s.includes(e);(l||c)&&(t.push({breakpointId:o,minWidth:i.minWidth,maxWidth:i.maxWidth,visible:c||!l,priority:r}),0===r&&(n=c||!l))}),t.length>0&&i.set(e,{itemId:e,shouldRender:!0,visibilityRules:t,defaultVisible:n})}return{items:i,breakpoints:r}}const fr="data-epdf",vr="data-epdf-s",yr="data-epdf-i",br="data-epdf-cat",wr="data-epdf-dis",xr="data-epdf-hid",Cr={ROOT:`[${fr}]`,STYLES:`[${vr}]`,ITEM:e=>`[${yr}="${e}"]`,CATEGORIES:e=>`[${br}~="${e}"]`,DISABLED_CATEGORY:e=>`[${wr}~="${e}"]`,HIDDEN_ITEM:e=>`[${xr}~="${e}"]`},Ir={useContainerQueries:!0};function kr(e,t={}){const n={...Ir,...t.config},o=t.locale,i=Mr(e,o),r=[];r.push(function(e){const t=e?` (locale: ${e})`:"";return`/* ═══════════════════════════════════════════════════════════════════════════ */\n/* EmbedPDF UI Stylesheet - Auto-generated${t} */\n/* DO NOT EDIT MANUALLY - This file is generated from your UI schema */\n/* ═══════════════════════════════════════════════════════════════════════════ */`}(o));const a=function(e,t){const n=[],o=t.useContainerQueries?"@container":"@media",i=new Set;return e.responsiveItems.forEach((e,t)=>{if(i.has(t))return;i.add(t);const r=function(e,t,n){if(0===t.visibilityRules.length)return null;const o=[],i=Cr.ITEM(e);t.defaultVisible||o.push(`${i} { display: none; }`);for(const e of t.visibilityRules){const t=[];if(void 0!==e.minWidth&&t.push(`(min-width: ${e.minWidth}px)`),void 0!==e.maxWidth&&t.push(`(max-width: ${e.maxWidth}px)`),t.length>0){const r=e.visible?"flex":"none";o.push(`${n} ${t.join(" and ")} {\n ${i} { display: ${r}; }\n}`)}}return o.length>0?o.join("\n"):null}(t,e,o);r&&n.push(r)}),0===n.length?"":`/* ─── Responsive Visibility Rules ─── */\n/* Items show/hide based on container width */\n\n${n.join("\n\n")}`}(i,n);a&&r.push(a);const s=function(e){if(0===e.categories.size)return"";const t=[],n=Array.from(e.categories).sort();for(const e of n)t.push(`${Cr.ROOT}[${wr}~="${e}"] [${br}~="${e}"] {\n display: none !important;\n}`);return`/* ─── Category Visibility Rules ─── */\n/* Items hide when ANY of their categories is disabled */\n/* Use: data-disabled-categories="category1 category2" on root element */\n\n${t.join("\n\n")}`}(i);s&&r.push(s);const l=function(e,t){if(0===e.dependencies.length)return"";const n=[],o=t.useContainerQueries?"@container":"@media";for(const t of e.dependencies){const i=$r(t,e,o);i.length>0&&n.push(...i)}return 0===n.length?"":`/* ─── Dependency Visibility Rules ─── */\n/* Container elements hide when all their dependencies are hidden */\n\n${n.join("\n\n")}`}(i,n);return l&&r.push(l),r.filter(e=>e.trim()).join("\n\n")}function Sr(e,t){const n=new Set(t),o=[];return e.forEach((e,t)=>{e.some(e=>n.has(e))&&o.push(t)}),o}function Mr(e,t){const n=new Set,o=new Map,i=[],r=new Map,a=new Map;for(const[s,l]of Object.entries(e.menus))Ar(s,l,n,o,i,r,a,t);for(const[r,s]of Object.entries(e.toolbars))zr(r,s,n,o,i,a,t);for(const[t,r]of Object.entries(e.sidebars))_r(t,r,n,o,i);for(const[r,s]of Object.entries(e.selectionMenus||{}))Nr(r,s,n,o,i,a,t);return{categories:n,itemCategories:o,dependencies:i,menuBreakpoints:r,responsiveItems:a}}function Ar(e,t,n,o,i,r,a,s){Lr(e,t.categories,t.visibilityDependsOn,n,o,i),Pr(t.items,n,o,i);const l=pr(t,s);l&&l.items.forEach((e,t)=>{a.set(t,e)});const c=function(e,t,n){var o;const i=[],r=pr(e,n);if((null==(o=e.responsive)?void 0:o.breakpoints)&&r){const e=Array.from(r.breakpoints.entries()).sort((e,t)=>(e[1].minWidth??0)-(t[1].minWidth??0));for(const[n,o]of e){const e=Rr(r,o),n=new Set;for(const o of e){const e=t.get(o);e&&e.forEach(e=>n.add(e))}i.push({minWidth:o.minWidth,maxWidth:o.maxWidth,visibleItemIds:e,visibleCategories:n})}}else{const n=[],o=new Set;Dr(e.items,t,n,o),i.push({visibleItemIds:n,visibleCategories:o})}return i}(t,o,s);r.set(e,c)}function Pr(e,t,n,o){for(const i of e)Lr(i.id,i.categories,i.visibilityDependsOn,t,n,o),"section"===i.type&&Pr(i.items,t,n,o)}function Dr(e,t,n,o){for(const i of e){n.push(i.id);const e=t.get(i.id);e&&e.forEach(e=>o.add(e)),"section"===i.type&&Dr(i.items,t,n,o)}}function Rr(e,t){const n=[];return e.items.forEach((e,o)=>{let i=e.defaultVisible;for(const n of e.visibilityRules){(void 0===n.minWidth||void 0!==t.minWidth&&t.minWidth>=n.minWidth)&&(void 0===n.maxWidth||void 0!==t.maxWidth&&t.maxWidth<=n.maxWidth)&&(i=n.visible)}i&&n.push(o)}),n}function zr(e,t,n,o,i,r,a){Lr(e,t.categories,t.visibilityDependsOn,n,o,i);const s=pr(t,a);s&&s.items.forEach((e,t)=>{r.set(t,e)}),Tr(t.items,n,o,i)}function Tr(e,t,n,o){for(const i of e)Lr(i.id,i.categories,i.visibilityDependsOn,t,n,o),"group"===i.type&&i.items&&Tr(i.items,t,n,o),"tab-group"===i.type&&i.tabs&&Er(i.tabs,t,n,o)}function Er(e,t,n,o){for(const i of e)Lr(i.id,i.categories,i.visibilityDependsOn,t,n,o)}function _r(e,t,n,o,i){if(Lr(e,t.categories,t.visibilityDependsOn,n,o,i),"tabs"===t.content.type)for(const e of t.content.tabs)Lr(e.id,e.categories,e.visibilityDependsOn,n,o,i)}function Nr(e,t,n,o,i,r,a){if(Lr(e,t.categories,t.visibilityDependsOn,n,o,i),t.responsive){const e=pr(t,a);e&&e.items.forEach((e,t)=>{r.set(t,e)})}Or(t.items,n,o,i)}function Or(e,t,n,o){for(const i of e)Lr(i.id,i.categories,i.visibilityDependsOn,t,n,o),"group"===i.type&&i.items&&Or(i.items,t,n,o)}function Lr(e,t,n,o,i,r){var a;(null==t?void 0:t.length)&&(t.forEach(e=>o.add(e)),i.set(e,t)),n&&(n.menuId||(null==(a=n.itemIds)?void 0:a.length))&&r.push({itemId:e,dependsOnMenuId:n.menuId,dependsOnItemIds:n.itemIds})}function $r(e,t,n,o){var i;const r=[];if(e.dependsOnMenuId){const o=t.menuBreakpoints.get(e.dependsOnMenuId);if(o&&o.length>0){r.push(`/* "${e.itemId}" depends on menu "${e.dependsOnMenuId}" */`);for(const t of o){if(0===t.visibleItemIds.length)continue;const o=t.visibleItemIds.sort().map(e=>Cr.HIDDEN_ITEM(e)).join(""),i=`${Cr.ROOT}${o} ${Cr.ITEM(e.itemId)} {\n display: none !important;\n}`,a=[];void 0!==t.minWidth&&a.push(`(min-width: ${t.minWidth}px)`),void 0!==t.maxWidth&&a.push(`(max-width: ${t.maxWidth}px)`),a.length>0?r.push(`${n} ${a.join(" and ")} {\n ${i}\n}`):r.push(i)}}}if(null==(i=e.dependsOnItemIds)?void 0:i.length){r.push(`/* "${e.itemId}" depends on items: ${e.dependsOnItemIds.join(", ")} */`);const t=e.dependsOnItemIds.sort().map(e=>Cr.HIDDEN_ITEM(e)).join("");r.push(`${Cr.ROOT}${t} ${Cr.ITEM(e.itemId)} {\n display: none !important;\n}`)}return r}function jr(e,t){var n;return{[yr]:e.id,[br]:(null==(n=e.categories)?void 0:n.join(" "))||void 0,...t}}const Fr=class extends fo{constructor(e,t,n){var o,i;if(super(e,t),this.cachedStylesheet=null,this.cachedLocale=null,this.i18n=null,this.i18nCleanup=null,this.categoryChanged$=Mo(),this.stylesheetInvalidated$=So(),this.toolbarChanged$=Ao((e,t)=>({documentId:e,...t}),{cache:!1}),this.sidebarChanged$=Ao((e,t)=>({documentId:e,...t}),{cache:!1}),this.modalChanged$=Ao((e,t)=>({documentId:e,...t}),{cache:!1}),this.menuChanged$=Ao((e,t)=>({documentId:e,...t}),{cache:!1}),this.overlayChanged$=Ao((e,t)=>({documentId:e,...t}),{cache:!1}),this.schema=n.schema,this.stylesheetConfig=n.stylesheetConfig||{},this.itemCategories=Mr(this.schema).itemCategories,null==(o=n.disabledCategories)?void 0:o.length){this.dispatch(dr(n.disabledCategories));const e=Sr(this.itemCategories,n.disabledCategories);this.dispatch(ur(e))}this.i18n=(null==(i=t.getPlugin("i18n"))?void 0:i.provides())??null,this.i18n&&(this.i18nCleanup=this.i18n.onLocaleChange(({currentLocale:e})=>{this.handleLocaleChange(e)}),this.cachedLocale=this.i18n.getLocale())}async initialize(){this.logger.info("UIPlugin","Initialize","UI plugin initialized")}async destroy(){this.i18nCleanup&&(this.i18nCleanup(),this.i18nCleanup=null),this.toolbarChanged$.clear(),this.sidebarChanged$.clear(),this.modalChanged$.clear(),this.menuChanged$.clear(),this.overlayChanged$.clear(),this.stylesheetInvalidated$.clear(),super.destroy()}onDocumentLoadingStarted(e){this.dispatch(((e,t)=>({type:Bi,payload:{documentId:e,schema:t}}))(e,this.schema))}onDocumentClosed(e){this.dispatch((e=>({type:Wi,payload:{documentId:e}}))(e)),this.toolbarChanged$.clearScope(e),this.sidebarChanged$.clearScope(e),this.modalChanged$.clearScope(e),this.menuChanged$.clearScope(e),this.overlayChanged$.clearScope(e)}handleLocaleChange(e){this.cachedLocale!==e&&(this.logger.debug("UIPlugin","LocaleChange",`Locale changed: ${this.cachedLocale} -> ${e}`),this.cachedLocale=e,this.invalidateStylesheet(),this.stylesheetInvalidated$.emit())}getStylesheet(){var e;const t=(null==(e=this.i18n)?void 0:e.getLocale())??null;return this.cachedStylesheet&&this.cachedLocale===t||(this.cachedStylesheet=kr(this.schema,{config:this.stylesheetConfig,locale:t??void 0}),this.cachedLocale=t),this.cachedStylesheet}getLocale(){var e;return(null==(e=this.i18n)?void 0:e.getLocale())??null}invalidateStylesheet(){this.cachedStylesheet=null}onStylesheetInvalidated(e){return this.stylesheetInvalidated$.on(e)}disableCategoryImpl(e){const t=new Set(this.state.disabledCategories);if(!t.has(e)){t.add(e);const n=Array.from(t);this.dispatch(dr(n));const o=Sr(this.itemCategories,n);this.dispatch(ur(o)),this.categoryChanged$.emit({disabledCategories:n,hiddenItems:o})}}enableCategoryImpl(e){const t=new Set(this.state.disabledCategories);if(t.has(e)){t.delete(e);const n=Array.from(t);this.dispatch(dr(n));const o=Sr(this.itemCategories,n);this.dispatch(ur(o)),this.categoryChanged$.emit({disabledCategories:n,hiddenItems:o})}}toggleCategoryImpl(e){this.state.disabledCategories.includes(e)?this.enableCategoryImpl(e):this.disableCategoryImpl(e)}setDisabledCategoriesImpl(e){this.dispatch(dr(e));const t=Sr(this.itemCategories,e);this.dispatch(ur(t)),this.categoryChanged$.emit({disabledCategories:e,hiddenItems:t})}buildCapability(){return{setActiveToolbar:(e,t,n,o)=>this.setToolbarForDocument(e,t,n,o),setActiveSidebar:(e,t,n,o,i)=>this.setSidebarForDocument(e,t,n,o,i),toggleSidebar:(e,t,n,o,i)=>this.toggleSidebarForDocument(e,t,n,o,i),openModal:(e,t,n)=>this.openModalForDocument(e,t,n),openMenu:(e,t,n,o)=>this.openMenuForDocument(e,t,n,o),toggleMenu:(e,t,n,o)=>this.toggleMenuForDocument(e,t,n,o),enableOverlay:(e,t)=>this.enableOverlayForDocument(e,t),disableOverlay:(e,t)=>this.disableOverlayForDocument(e,t),toggleOverlay:(e,t)=>this.toggleOverlayForDocument(e,t),forDocument:e=>this.createUIScope(e),getSchema:()=>this.schema,mergeSchema:e=>{var t,n;this.schema=(t=this.schema,n=e,{...t,...n,toolbars:hr(t.toolbars,n.toolbars),menus:mr(t.menus,n.menus),sidebars:gr(t.sidebars,n.sidebars)})},disableCategory:e=>this.disableCategoryImpl(e),enableCategory:e=>this.enableCategoryImpl(e),toggleCategory:e=>this.toggleCategoryImpl(e),setDisabledCategories:e=>this.setDisabledCategoriesImpl(e),getDisabledCategories:()=>this.state.disabledCategories,isCategoryDisabled:e=>this.state.disabledCategories.includes(e),getHiddenItems:()=>this.state.hiddenItems,onToolbarChanged:this.toolbarChanged$.onGlobal,onSidebarChanged:this.sidebarChanged$.onGlobal,onModalChanged:this.modalChanged$.onGlobal,onMenuChanged:this.menuChanged$.onGlobal,onOverlayChanged:this.overlayChanged$.onGlobal,onCategoryChanged:this.categoryChanged$.on}}createUIScope(e){return{setActiveToolbar:(t,n,o)=>this.setToolbarForDocument(t,n,o,e),getActiveToolbar:(t,n)=>this.getToolbarForDocument(t,n,e),closeToolbarSlot:(t,n)=>this.closeToolbarForDocument(t,n,e),isToolbarOpen:(t,n,o)=>this.isToolbarOpenForDocument(t,n,o,e),setActiveSidebar:(t,n,o,i)=>this.setSidebarForDocument(t,n,o,e,i),getActiveSidebar:(t,n)=>this.getSidebarForDocument(t,n,e),closeSidebarSlot:(t,n)=>this.closeSidebarForDocument(t,n,e),toggleSidebar:(t,n,o,i)=>this.toggleSidebarForDocument(t,n,o,e,i),isSidebarOpen:(t,n,o)=>this.isSidebarOpenForDocument(t,n,o,e),setSidebarTab:(t,n)=>this.setSidebarTabForDocument(t,n,e),getSidebarTab:t=>this.getSidebarTabForDocument(t,e),openModal:(t,n)=>this.openModalForDocument(t,n,e),closeModal:()=>this.closeModalForDocument(e),clearModal:()=>this.clearModalForDocument(e),getActiveModal:()=>this.getActiveModalForDocument(e),isModalOpen:()=>this.isModalOpenForDocument(e),openMenu:(t,n,o)=>this.openMenuForDocument(t,n,o,e),closeMenu:t=>this.closeMenuForDocument(t,e),toggleMenu:(t,n,o)=>this.toggleMenuForDocument(t,n,o,e),closeAllMenus:()=>this.closeAllMenusForDocument(e),isMenuOpen:t=>this.isMenuOpenForDocument(t,e),getOpenMenus:()=>this.getOpenMenusForDocument(e),enableOverlay:t=>this.enableOverlayForDocument(t,e),disableOverlay:t=>this.disableOverlayForDocument(t,e),toggleOverlay:t=>this.toggleOverlayForDocument(t,e),isOverlayEnabled:t=>this.isOverlayEnabledForDocument(t,e),getEnabledOverlays:()=>this.getEnabledOverlaysForDocument(e),getSchema:()=>this.schema,getState:()=>this.getDocumentStateOrThrow(e),onToolbarChanged:this.toolbarChanged$.forScope(e),onSidebarChanged:this.sidebarChanged$.forScope(e),onModalChanged:this.modalChanged$.forScope(e),onMenuChanged:this.menuChanged$.forScope(e),onOverlayChanged:this.overlayChanged$.forScope(e)}}getDocumentState(e){const t=e??this.getActiveDocumentId();return this.state.documents[t]??null}getDocumentStateOrThrow(e){const t=this.getDocumentState(e);if(!t)throw new Error(`UI state not found for document: ${e??"active"}`);return t}setToolbarForDocument(e,t,n,o){const i=o??this.getActiveDocumentId();this.dispatch(((e,t,n,o)=>({type:qi,payload:{documentId:e,placement:t,slot:n,toolbarId:o}}))(i,e,t,n)),this.toolbarChanged$.emit(i,{placement:e,slot:t,toolbarId:n})}getToolbarForDocument(e,t,n){const o=`${e}-${t}`,i=this.getDocumentStateOrThrow(n).activeToolbars[o];return(null==i?void 0:i.isOpen)?i.toolbarId:null}closeToolbarForDocument(e,t,n){const o=n??this.getActiveDocumentId();this.dispatch(((e,t,n)=>({type:Gi,payload:{documentId:e,placement:t,slot:n}}))(o,e,t)),this.toolbarChanged$.emit(o,{placement:e,slot:t,toolbarId:""})}isToolbarOpenForDocument(e,t,n,o){const i=`${e}-${t}`,r=this.getDocumentStateOrThrow(o).activeToolbars[i];return!(!r||!r.isOpen)&&(!n||r.toolbarId===n)}setSidebarForDocument(e,t,n,o,i){const r=o??this.getActiveDocumentId();this.dispatch(rr(r,e,t,n,i)),this.sidebarChanged$.emit(r,{placement:e,slot:t,sidebarId:n})}getSidebarForDocument(e,t,n){const o=`${e}-${t}`,i=this.getDocumentStateOrThrow(n).activeSidebars[o];return(null==i?void 0:i.isOpen)?i.sidebarId:null}closeSidebarForDocument(e,t,n){const o=n??this.getActiveDocumentId();this.dispatch(ar(o,e,t)),this.sidebarChanged$.emit(o,{placement:e,slot:t,sidebarId:""})}toggleSidebarForDocument(e,t,n,o,i){const r=o??this.getActiveDocumentId(),a=`${e}-${t}`,s=this.getDocumentStateOrThrow(r).activeSidebars[a];(null==s?void 0:s.sidebarId)===n&&(null==s?void 0:s.isOpen)?(this.dispatch(ar(r,e,t)),this.sidebarChanged$.emit(r,{placement:e,slot:t,sidebarId:""})):(this.dispatch(rr(r,e,t,n,i)),this.sidebarChanged$.emit(r,{placement:e,slot:t,sidebarId:n}))}isSidebarOpenForDocument(e,t,n,o){const i=`${e}-${t}`,r=this.getDocumentStateOrThrow(o).activeSidebars[i];return!(!r||!r.isOpen)&&(!n||r.sidebarId===n)}setSidebarTabForDocument(e,t,n){const o=n??this.getActiveDocumentId();this.dispatch(((e,t,n)=>({type:Zi,payload:{documentId:e,sidebarId:t,tabId:n}}))(o,e,t))}getSidebarTabForDocument(e,t){return this.getDocumentStateOrThrow(t).sidebarTabs[e]??null}openModalForDocument(e,t,n){const o=n??this.getActiveDocumentId();this.dispatch(((e,t,n)=>({type:Yi,payload:{documentId:e,modalId:t,props:n}}))(o,e,t)),this.modalChanged$.emit(o,{modalId:e,isOpen:!0})}closeModalForDocument(e){const t=e??this.getActiveDocumentId(),n=this.getDocumentStateOrThrow(t).activeModal;this.dispatch((e=>({type:Xi,payload:{documentId:e}}))(t)),this.modalChanged$.emit(t,{modalId:(null==n?void 0:n.modalId)??null,isOpen:!1})}clearModalForDocument(e){const t=e??this.getActiveDocumentId();this.dispatch((e=>({type:Qi,payload:{documentId:e}}))(t))}getActiveModalForDocument(e){return this.getDocumentStateOrThrow(e).activeModal}isModalOpenForDocument(e){const t=this.getDocumentStateOrThrow(e).activeModal;return(null==t?void 0:t.isOpen)??!1}openMenuForDocument(e,t,n,o){const i=o??this.getActiveDocumentId();this.dispatch(sr(i,{menuId:e,triggeredByCommandId:t,triggeredByItemId:n})),this.menuChanged$.emit(i,{menuId:e,isOpen:!0})}closeMenuForDocument(e,t){const n=t??this.getActiveDocumentId();this.dispatch(lr(n,e)),this.menuChanged$.emit(n,{menuId:e,isOpen:!1})}toggleMenuForDocument(e,t,n,o){const i=o??this.getActiveDocumentId();!!this.getDocumentStateOrThrow(i).openMenus[e]?(this.dispatch(lr(i,e)),this.menuChanged$.emit(i,{menuId:e,isOpen:!1})):(this.dispatch(sr(i,{menuId:e,triggeredByCommandId:t,triggeredByItemId:n})),this.menuChanged$.emit(i,{menuId:e,isOpen:!0}))}closeAllMenusForDocument(e){const t=e??this.getActiveDocumentId();this.dispatch((e=>({type:tr,payload:{documentId:e}}))(t))}isMenuOpenForDocument(e,t){return!!this.getDocumentStateOrThrow(t).openMenus[e]}getOpenMenusForDocument(e){return Object.values(this.getDocumentStateOrThrow(e).openMenus)}enableOverlayForDocument(e,t){const n=t??this.getActiveDocumentId();this.dispatch(cr(n,e,!0)),this.overlayChanged$.emit(n,{overlayId:e,isEnabled:!0})}disableOverlayForDocument(e,t){const n=t??this.getActiveDocumentId();this.dispatch(cr(n,e,!1)),this.overlayChanged$.emit(n,{overlayId:e,isEnabled:!1})}toggleOverlayForDocument(e,t){const n=t??this.getActiveDocumentId();this.isOverlayEnabledForDocument(e,n)?this.disableOverlayForDocument(e,n):this.enableOverlayForDocument(e,n)}isOverlayEnabledForDocument(e,t){return this.getDocumentStateOrThrow(t).enabledOverlays[e]??!0}getEnabledOverlaysForDocument(e){const t=this.getDocumentStateOrThrow(e).enabledOverlays;return Object.entries(t).filter(([,e])=>e).map(([e])=>e)}};Fr.id="ui";let Ur=Fr;const Hr={activeToolbars:{},activeSidebars:{},activeModal:null,openMenus:{},sidebarTabs:{},enabledOverlays:{}},Br={documents:{},disabledCategories:[],hiddenItems:[]};function Wr(e,t){const n=function(e){return e.ui??null}(e);return(null==n?void 0:n.documents[t])??null}function qr(e,t){return`${e}-${t}`}function Gr(e,t,n,o,i){const r=function(e,t,n,o){const i=Wr(e,t);return i?i.activeToolbars[qr(n,o)]??null:null}(e,t,n,o);return!(!r||!r.isOpen)&&(!i||r.toolbarId===i)}function Vr(e,t,n,o,i){const r=function(e,t,n,o){const i=Wr(e,t);return i?i.activeSidebars[qr(n,o)]??null:null}(e,t,n,o);return!(!r||!r.isOpen)&&(!i||r.sidebarId===i)}const Kr={manifest:Hi,create:(e,t)=>new Ur(Ui,e,t),reducer:(e=Br,t)=>{var n;switch(t.type){case Bi:{const{documentId:n,schema:o}=t.payload,i={};Object.values(o.toolbars).forEach(e=>{if(e.permanent&&e.position){const t=`${e.position.placement}-${e.position.slot}`;i[t]={toolbarId:e.id,isOpen:!0}}});const r={};return o.overlays&&Object.values(o.overlays).forEach(e=>{r[e.id]=e.defaultEnabled??!0}),{...e,documents:{...e.documents,[n]:{...Hr,activeToolbars:i,enabledOverlays:r}}}}case Wi:{const{documentId:n}=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i}}case qi:{const{documentId:n,placement:o,slot:i,toolbarId:r}=t.payload,a=e.documents[n]||Hr,s=`${o}-${i}`;return{...e,documents:{...e.documents,[n]:{...a,activeToolbars:{...a.activeToolbars,[s]:{toolbarId:r,isOpen:!0}}}}}}case Gi:{const{documentId:n,placement:o,slot:i}=t.payload,r=e.documents[n];if(!r)return e;const a=`${o}-${i}`,s=r.activeToolbars[a];return s?{...e,documents:{...e.documents,[n]:{...r,activeToolbars:{...r.activeToolbars,[a]:{...s,isOpen:!1}}}}}:e}case Vi:{const{documentId:n,placement:o,slot:i,sidebarId:r,activeTab:a}=t.payload,s=e.documents[n]||Hr,l=`${o}-${i}`;return{...e,documents:{...e.documents,[n]:{...s,activeSidebars:{...s.activeSidebars,[l]:{sidebarId:r,isOpen:!0}},...a&&{sidebarTabs:{...s.sidebarTabs,[r]:a}}}}}}case Ki:{const{documentId:n,placement:o,slot:i}=t.payload,r=e.documents[n];if(!r)return e;const a=`${o}-${i}`,s=r.activeSidebars[a];return s?{...e,documents:{...e.documents,[n]:{...r,activeSidebars:{...r.activeSidebars,[a]:{...s,isOpen:!1}}}}}:e}case Zi:{const{documentId:n,sidebarId:o,tabId:i}=t.payload,r=e.documents[n]||Hr;return{...e,documents:{...e.documents,[n]:{...r,sidebarTabs:{...r.sidebarTabs,[o]:i}}}}}case Yi:{const{documentId:n,modalId:o,props:i}=t.payload,r=e.documents[n]||Hr;return{...e,documents:{...e.documents,[n]:{...r,activeModal:{modalId:o,isOpen:!0,props:i},openMenus:{}}}}}case Xi:{const{documentId:n}=t.payload,o=e.documents[n];return(null==o?void 0:o.activeModal)?{...e,documents:{...e.documents,[n]:{...o,activeModal:{...o.activeModal,isOpen:!1}}}}:e}case Qi:{const{documentId:o}=t.payload,i=e.documents[o];return i?(null==(n=i.activeModal)?void 0:n.isOpen)?e:{...e,documents:{...e.documents,[o]:{...i,activeModal:null}}}:e}case Ji:{const{documentId:n,menuState:o}=t.payload,i=e.documents[n]||Hr;return{...e,documents:{...e.documents,[n]:{...i,openMenus:{[o.menuId]:o}}}}}case er:{const{documentId:n,menuId:o}=t.payload,i=e.documents[n];if(!i)return e;const{[o]:r,...a}=i.openMenus;return{...e,documents:{...e.documents,[n]:{...i,openMenus:a}}}}case tr:{const{documentId:n}=t.payload,o=e.documents[n];return o?{...e,documents:{...e.documents,[n]:{...o,openMenus:{}}}}:e}case nr:{const{documentId:n,overlayId:o,enabled:i}=t.payload,r=e.documents[n]||Hr;return{...e,documents:{...e.documents,[n]:{...r,enabledOverlays:{...r.enabledOverlays,[o]:i}}}}}case or:return{...e,disabledCategories:t.payload.categories};case ir:return{...e,hiddenItems:t.payload.hiddenItems};default:return e}},initialState:Br},Zr=()=>_o(Ur.id),Yr=e=>{const{provides:t}=Zr(),[n,o]=Se(null);return Ae(()=>{if(!t)return;const n=t.forDocument(e);o(n.getState());const i=n.onToolbarChanged(()=>o(n.getState())),r=n.onSidebarChanged(()=>o(n.getState())),a=n.onModalChanged(()=>o(n.getState())),s=n.onMenuChanged(()=>o(n.getState())),l=n.onOverlayChanged(()=>o(n.getState()));return()=>{i(),r(),a(),s(),l()}},[t,e]),n},Xr=de(null);function Qr(){const e=Te(Xr);if(!e)throw new Error("useUIContainer must be used within a UIProvider");return e}const Jr=de(null);function ea({children:e}){const t=De(new Map),n={register:ze((e,n,o)=>{const i=`${e}:${n}`;t.current.set(i,o)},[]),unregister:ze((e,n)=>{const o=`${e}:${n}`;t.current.delete(o)},[]),getAnchor:ze((e,n)=>{const o=`${e}:${n}`;return t.current.get(o)||null},[])};return He(Jr.Provider,{value:n,children:e})}function ta(){const e=Te(Jr);if(!e)throw new Error("useAnchorRegistry must be used within UIProvider");return e}function na(e,t){const n=ta(),o=De(null),i=De(e),r=De(t);return i.current=e,r.current=t,ze(e=>{const t=o.current;o.current=e,e?e!==t&&n.register(i.current,r.current,e):t&&n.unregister(i.current,r.current)},[n])}const oa=de(null);function ia({children:e,initialComponents:t={}}){const n=De(new Map(Object.entries(t))),o={register:ze((e,t)=>{n.current.set(e,t)},[]),unregister:ze(e=>{n.current.delete(e)},[]),get:ze(e=>n.current.get(e),[]),has:ze(e=>n.current.has(e),[]),getRegisteredIds:ze(()=>Array.from(n.current.keys()),[])};return He(oa.Provider,{value:o,children:e})}function ra(){const e=function(){const e=Te(oa);if(!e)throw new Error("useComponentRegistry must be used within UIProvider");return e}();return{renderCustomComponent:(t,n,o)=>{const i=e.get(t);return i?He(i,{documentId:n,...o||{}}):(console.error(`Component "${t}" not found in registry`),null)}}}const aa=de(null);function sa({children:e,renderers:t}){return He(aa.Provider,{value:t,children:e})}function la(){const e=Te(aa);if(!e)throw new Error("useRenderers must be used within UIProvider");return e}function ca(e,t){var n;const{provides:o}=Zr(),i=la(),r=ze(n=>{var r;const a=null==o?void 0:o.getSchema(),s=null==(r=null==a?void 0:a.selectionMenus)?void 0:r[e];if(!s)return null;if(!n.selected)return null;return He(i.selectionMenu,{schema:s,documentId:t,props:n})},[o,i,e,t]),a=null==o?void 0:o.getSchema();if(null==(n=null==a?void 0:a.selectionMenus)?void 0:n[e])return r}function da({container:e,documentId:t}){const n=Yr(t),{provides:o}=Zr(),i=ta(),r=la(),[a,s]=Se(null),l=(null==n?void 0:n.openMenus)||{},c=null==o?void 0:o.getSchema();Ae(()=>{const e=Object.keys(l);if(e.length>0){const n=e[0];if(!n)return void s(null);const o=l[n];if(o&&o.triggeredByItemId){const e=i.getAnchor(t,o.triggeredByItemId);s({menuId:n,anchorEl:e})}else s(null)}else s(null)},[l,i,t]);if(!a||!c)return null;const d=c.menus[a.menuId];if(!d)return console.warn(`Menu "${a.menuId}" not found in schema`),null;return He(r.menu,{schema:d,documentId:t,anchorEl:a.anchorEl,onClose:()=>{a&&(null==o||o.forDocument(t).closeMenu(a.menuId))},container:e})}function ua({children:e,style:t,...n}){const{plugin:o}=Eo(Ur.id),{provides:i}=Zr(),[r,a]=Se([]),[s,l]=Se([]),c=De(null),d=De(null),u=De(null),h=De(null),m=Re(()=>({containerRef:h,getContainer:()=>h.current}),[]),g=ze(e=>{const t=u.current;if(u.current=e,h.current=e,e&&e!==t&&o){const t=function(e){const t=e.getRootNode();return t instanceof ShadowRoot?t:document.head}(e);d.current=t;const n=t.querySelector(Cr.STYLES);if(n)return c.current=n,void(n.textContent=o.getStylesheet());const i=o.getStylesheet(),r=document.createElement("style");r.setAttribute(vr,""),r.textContent=i,t instanceof ShadowRoot?t.insertBefore(r,t.firstChild):t.appendChild(r),c.current=r}},[o]);Ae(()=>()=>{var e;(null==(e=c.current)?void 0:e.parentNode)&&!u.current&&c.current.remove(),c.current=null,d.current=null},[]),Ae(()=>{if(o)return o.onStylesheetInvalidated(()=>{c.current&&(c.current.textContent=o.getStylesheet())})},[o]),Ae(()=>{if(i)return a(i.getDisabledCategories()),l(i.getHiddenItems()),i.onCategoryChanged(({disabledCategories:e,hiddenItems:t})=>{a(e),l(t)})},[i]);const p=Re(()=>r.length>0?r.join(" "):void 0,[r]),f=Re(()=>s.length>0?s.join(" "):void 0,[s]),v=Re(()=>{const e={containerType:"inline-size"};return t&&"object"==typeof t?{...e,...t}:e},[t]),y={[fr]:"",[wr]:p,[xr]:f};return He(Xr.Provider,{value:m,children:He("div",{ref:g,...y,...n,style:v,children:e})})}function ha({children:e,documentId:t,components:n={},renderers:o,menuContainer:i,...r}){return He(ea,{children:He(ia,{initialComponents:n,children:He(sa,{renderers:o,children:He(ua,{...r,children:[e,He(da,{documentId:t,container:i})]})})})})}const ma=class extends fo{constructor(e,t,n){super(e,t),this.id=e,this.documentOpened$=Mo(),this.documentClosed$=Mo(),this.activeDocumentChanged$=Mo(),this.documentError$=Mo(),this.documentOrderChanged$=Mo(),this.openFileRequest$=So(),this.loadOptions=new Map,this.maxDocuments=null==n?void 0:n.maxDocuments}buildCapability(){return{openFileDialog:e=>this.openFileDialog(e),openDocumentUrl:e=>this.openDocumentUrl(e),openDocumentBuffer:e=>this.openDocumentBuffer(e),retryDocument:(e,t)=>this.retryDocument(e,t),closeDocument:e=>this.closeDocument(e),closeAllDocuments:()=>this.closeAllDocuments(),setActiveDocument:e=>{if(!this.isDocumentOpen(e))throw new Error(`Cannot set active document: ${e} is not open`);this.dispatchCoreAction((e=>({type:Gn,payload:e}))(e))},getActiveDocumentId:()=>this.coreState.core.activeDocumentId,getActiveDocument:()=>{var e;const t=this.coreState.core.activeDocumentId;return t?(null==(e=this.coreState.core.documents[t])?void 0:e.document)??null:null},getDocumentOrder:()=>this.coreState.core.documentOrder,moveDocument:(e,t)=>{this.dispatchCoreAction(((e,t)=>({type:Kn,payload:{documentId:e,toIndex:t}}))(e,t))},swapDocuments:(e,t)=>{const n=this.coreState.core.documentOrder,o=n.indexOf(e),i=n.indexOf(t);if(-1===o||-1===i)throw new Error("One or both documents not found in order");const r=[...n];[r[o],r[i]]=[r[i],r[o]],this.dispatchCoreAction((e=>({type:Vn,payload:e}))(r))},getDocument:e=>{var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.document)??null},getDocumentState:e=>this.coreState.core.documents[e]??null,getOpenDocuments:()=>this.coreState.core.documentOrder.map(e=>this.coreState.core.documents[e]).filter(e=>null!==e),isDocumentOpen:e=>this.isDocumentOpen(e),getDocumentCount:()=>Object.keys(this.coreState.core.documents).length,getDocumentIndex:e=>this.coreState.core.documentOrder.indexOf(e),setDocumentEncryption:(e,t)=>this.setDocumentEncryption(e,t),unlockOwnerPermissions:(e,t)=>this.unlockOwnerPermissions(e,t),removeEncryption:e=>this.removeEncryption(e),onDocumentOpened:this.documentOpened$.on,onDocumentClosed:this.documentClosed$.on,onDocumentError:this.documentError$.on,onActiveDocumentChanged:this.activeDocumentChanged$.on,onDocumentOrderChanged:this.documentOrderChanged$.on}}isDocumentOpen(e){return!!this.coreState.core.documents[e]}onDocumentLoaded(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&(this.loadOptions.delete(e),this.documentOpened$.emit(t),this.logger.info("DocumentManagerPlugin","DocumentOpened",`Document ${e} opened successfully`,{name:t.name}))}onDocumentClosed(e){this.loadOptions.delete(e),this.documentClosed$.emit(e),this.logger.info("DocumentManagerPlugin","DocumentClosed",`Document ${e} closed`)}onActiveDocumentChanged(e,t){this.activeDocumentChanged$.emit({previousDocumentId:e,currentDocumentId:t}),this.logger.info("DocumentManagerPlugin","ActiveDocumentChanged",`Active document changed from ${e} to ${t}`)}onCoreStoreUpdated(e,t){e.core.documentOrder!==t.core.documentOrder&&this.documentOrderChanged$.emit({order:t.core.documentOrder})}onOpenFileRequest(e){return this.openFileRequest$.on(e)}openDocumentUrl(e){const t=new Ct,n=e.documentId||this.generateDocumentId(),o=this.checkDocumentLimit();if(o)return t.reject(o),t;const i=e.name??this.extractNameFromUrl(e.url);this.loadOptions.set(n,e),this.dispatchCoreAction(eo(n,i,e.scale,e.rotation,!!e.password,e.autoActivate,e.permissions)),this.logger.info("DocumentManagerPlugin","OpenDocumentUrl",`Starting to load document from URL: ${e.url}`,{documentId:n,passwordProvided:!!e.password});const r={id:n,url:e.url},a=this.engine.openDocumentUrl(r,{password:e.password,mode:e.mode,requestOptions:e.requestOptions,normalizeRotation:!0});return t.resolve({documentId:n,task:a}),this.handleLoadTask(n,a,"OpenDocumentUrl"),t}openDocumentBuffer(e){const t=new Ct,n=this.checkDocumentLimit();if(n)return t.reject(n),t;const o=e.documentId||this.generateDocumentId();this.loadOptions.set(o,e),this.dispatchCoreAction(eo(o,e.name,e.scale,e.rotation,!!e.password,e.autoActivate,e.permissions)),this.logger.info("DocumentManagerPlugin","OpenDocumentBuffer",`Starting to load document from buffer: ${e.name}`,{documentId:o,passwordProvided:!!e.password});const i={id:o,content:e.buffer},r=this.engine.openDocumentBuffer(i,{password:e.password,normalizeRotation:!0});return t.resolve({documentId:o,task:r}),this.handleLoadTask(o,r,"OpenDocumentBuffer"),t}retryDocument(e,t){const n=new Ct,o=this.validateRetry(e);if(!o.valid)return n.reject(o.error),n;const i={...this.loadOptions.get(e),...(null==t?void 0:t.password)&&{password:t.password}};this.loadOptions.set(e,i),this.dispatchCoreAction(((e,t)=>({type:Wn,payload:{documentId:e,passwordProvided:t}}))(e,!!(null==t?void 0:t.password))),this.logger.info("DocumentManagerPlugin","RetryDocument",`Retrying to load document ${e}`,{passwordProvided:!!(null==t?void 0:t.password)});const r="url"in i?this.retryUrlDocument(e,i):this.retryBufferDocument(e,i);return n.resolve({documentId:e,task:r}),this.handleLoadTask(e,r,"RetryDocument"),n}openFileDialog(e){const t=new Ct;return this.openFileRequest$.emit({task:t,options:e}),t}closeDocument(e){const t=new Ct,n=this.coreState.core.documents[e];return n?("loaded"===n.status&&n.document?this.engine.closeDocument(n.document).wait(()=>{this.dispatchCoreAction(to(e)),t.resolve()},n=>{this.logger.error("DocumentManagerPlugin","CloseDocument",`Failed to close document ${e}`,n),t.fail(n)}):(this.logger.info("DocumentManagerPlugin","CloseDocument",`Closing document ${e} in ${n.status} state (skipping engine close)`),this.dispatchCoreAction(to(e)),t.resolve()),t):(this.logger.warn("DocumentManagerPlugin","CloseDocument",`Cannot close document ${e}: not found in state`),t.resolve(),t)}closeAllDocuments(){const e=Object.keys(this.coreState.core.documents),t=e.map(e=>this.closeDocument(e));return this.logger.info("DocumentManagerPlugin","CloseAllDocuments",`Closing ${e.length} documents`),Ct.all(t)}setDocumentEncryption(e,t){const n=new Ct,o=this.coreState.core.documents[e];if(!(null==o?void 0:o.document))return n.reject({code:Qt.DocNotOpen,message:`Document ${e} is not open`}),n;this.logger.info("DocumentManagerPlugin","SetDocumentEncryption",`Setting encryption on document ${e}`,{hasUserPassword:!!t.userPassword,allowedFlags:t.allowedFlags});return this.engine.setDocumentEncryption(o.document,t.userPassword??"",t.ownerPassword,t.allowedFlags).wait(t=>{t&&this.logger.info("DocumentManagerPlugin","SetDocumentEncryption",`Encryption set successfully on document ${e}`),n.resolve(t)},t=>{this.logger.error("DocumentManagerPlugin","SetDocumentEncryption",`Failed to set encryption on document ${e}`,t),n.fail(t)}),n}unlockOwnerPermissions(e,t){const n=new Ct,o=this.coreState.core.documents[e];if(!(null==o?void 0:o.document))return n.reject({code:Qt.DocNotOpen,message:`Document ${e} is not open`}),n;const i=o.document;this.logger.info("DocumentManagerPlugin","UnlockOwnerPermissions",`Attempting to unlock owner permissions on document ${e}`);return this.engine.unlockOwnerPermissions(i,t).wait(t=>{if(t){this.logger.info("DocumentManagerPlugin","UnlockOwnerPermissions",`Owner permissions unlocked on document ${e}`);const t=4294967295;this.dispatchCoreAction(((e,t,n)=>({type:Zn,payload:{documentId:e,permissions:t,isOwnerUnlocked:n}}))(e,t,!0))}n.resolve(t)},t=>{this.logger.error("DocumentManagerPlugin","UnlockOwnerPermissions",`Failed to unlock owner permissions on document ${e}`,t),n.fail(t)}),n}removeEncryption(e){const t=new Ct,n=this.coreState.core.documents[e];if(!(null==n?void 0:n.document))return t.reject({code:Qt.DocNotOpen,message:`Document ${e} is not open`}),t;this.logger.info("DocumentManagerPlugin","RemoveEncryption",`Marking document ${e} for encryption removal on save`);return this.engine.removeEncryption(n.document).wait(n=>{n&&this.logger.info("DocumentManagerPlugin","RemoveEncryption",`Document ${e} marked for encryption removal`),t.resolve(n)},n=>{this.logger.error("DocumentManagerPlugin","RemoveEncryption",`Failed to mark document ${e} for encryption removal`,n),t.fail(n)}),t}checkDocumentLimit(){return this.maxDocuments&&Object.keys(this.coreState.core.documents).length>=this.maxDocuments?{code:Qt.Unknown,message:`Maximum number of documents (${this.maxDocuments}) reached`}:null}validateRetry(e){const t=this.coreState.core.documents[e];return t?"loaded"===t.status?{valid:!1,error:{code:Qt.Unknown,message:`Document ${e} is already loaded successfully`}}:"error"!==t.status?{valid:!1,error:{code:Qt.Unknown,message:`Document ${e} is not in error state (current state: ${t.status})`}}:this.loadOptions.has(e)?{valid:!0}:{valid:!1,error:{code:Qt.Unknown,message:`No retry information available for document ${e}`}}:{valid:!1,error:{code:Qt.NotFound,message:`Document ${e} not found`}}}retryUrlDocument(e,t){const n={id:e,url:t.url};return this.engine.openDocumentUrl(n,{password:t.password,mode:t.mode,requestOptions:t.requestOptions})}retryBufferDocument(e,t){const n={id:e,content:t.buffer};return this.engine.openDocumentBuffer(n,{password:t.password,normalizeRotation:!0})}handleLoadTask(e,t,n){t.wait(t=>{this.dispatchCoreAction(((e,t)=>({type:Hn,payload:{documentId:e,document:t}}))(e,t))},t=>{this.handleLoadError(e,t,n)})}handleLoadError(e,t,n){var o,i,r;const a=(null==(o=t.reason)?void 0:o.message)||"Failed to load document";this.logger.error("DocumentManagerPlugin",n,"Failed to load document",t),this.dispatchCoreAction(((e,t,n,o)=>({type:Bn,payload:{documentId:e,error:t,errorCode:n,errorDetails:o}}))(e,a,null==(i=t.reason)?void 0:i.code,t.reason)),this.documentError$.emit({documentId:e,message:a,code:null==(r=t.reason)?void 0:r.code,reason:t.reason})}generateDocumentId(){return`doc-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}extractNameFromUrl(e){try{const t=new URL(e),n=t.pathname.split("/").pop();if(!n)return;let o=decodeURIComponent(n);return o.toLowerCase().endsWith(".pdf")||(o+=".pdf"),o}catch{return}}async initialize(e){var t;if(this.logger.info("DocumentManagerPlugin","Initialize","Document Manager Plugin initialized",{maxDocuments:this.maxDocuments,initialDocumentsCount:(null==(t=e.initialDocuments)?void 0:t.length)??0}),e.initialDocuments&&e.initialDocuments.length>0)for(const t of e.initialDocuments)try{"buffer"in t?this.openDocumentBuffer(t):"url"in t&&this.openDocumentUrl(t)}catch(e){this.logger.error("DocumentManagerPlugin","Initialize","Failed to initiate initial document load",e)}}async destroy(){await this.closeAllDocuments().toPromise(),this.loadOptions.clear(),this.documentOpened$.clear(),this.documentClosed$.clear(),this.activeDocumentChanged$.clear(),this.documentOrderChanged$.clear(),this.documentError$.clear(),super.destroy()}};ma.id="document-manager";let ga=ma;const pa="document-manager";function fa({documentId:e,children:t}){const n=Oo(e);if(!n)return null;return He(H,{children:t({documentState:n,isLoading:"loading"===n.status,isError:"error"===n.status,isLoaded:"loaded"===n.status})})}const va=()=>_o(ga.id);const ya=Do({manifest:{id:pa,name:"Document Manager Plugin",version:"1.0.0",provides:["document-manager"],requires:[],optional:[],defaultConfig:{maxDocuments:10}},create:(e,t)=>new ga(pa,e,t),reducer:e=>e,initialState:{}}).addUtility(function(){const{plugin:e}=Eo(ga.id),{provides:t}=va(),n=De(null),o=De(null),i=De(void 0);return Ae(()=>{if(!(null==e?void 0:e.onOpenFileRequest))return;return e.onOpenFileRequest(({task:e,options:t})=>{var r;o.current=e,i.current=t,null==(r=n.current)||r.click()})},[e]),He("input",{ref:n,type:"file",accept:"application/pdf",style:{display:"none"},onChange:async e=>{var n,r,a,s,l;const c=null==(n=e.currentTarget.files)?void 0:n[0];if(!c||!t)return;const d=await c.arrayBuffer();t.openDocumentBuffer({name:c.name,buffer:d,documentId:null==(r=i.current)?void 0:r.documentId,scale:null==(a=i.current)?void 0:a.scale,rotation:null==(s=i.current)?void 0:s.rotation,autoActivate:null==(l=i.current)?void 0:l.autoActivate}).wait(e=>{var t;null==(t=o.current)||t.resolve(e)},e=>{var t;null==(t=o.current)||t.fail(e)})}})}).build(),ba="commands",wa={id:ba,name:"Commands Plugin",version:"1.0.0",provides:["commands"],requires:[],optional:["i18n","ui"],defaultConfig:{commands:{}}},xa="COMMANDS/SET_DISABLED_CATEGORIES",Ca=e=>({type:xa,payload:e}),Ia=class extends fo{constructor(e,t,n){var o;super(e,t),this.commands=new Map,this.i18n=null,this.shortcutMap=new Map,this.commandExecuted$=So(),this.commandStateChanged$=So(),this.shortcutExecuted$=So(),this.categoryChanged$=Mo(),this.previousStates=new Map;const i=t.getPlugin("i18n");this.i18n=(null==i?void 0:i.provides())??null,(null==(o=n.disabledCategories)?void 0:o.length)&&this.dispatch(Ca(n.disabledCategories)),Object.values(n.commands).forEach(e=>{this.registerCommand(e)}),this.registry.getStore().subscribe((e,t)=>{this.onGlobalStoreChange(t)})}onDocumentClosed(e){this.previousStates.delete(e),this.logger.debug("CommandsPlugin","DocumentClosed",`Cleaned up command state cache for document: ${e}`)}async initialize(){this.logger.info("CommandsPlugin","Initialize","Commands plugin initialized")}async destroy(){this.commandExecuted$.clear(),this.commandStateChanged$.clear(),this.shortcutExecuted$.clear(),this.categoryChanged$.clear(),this.commands.clear(),this.shortcutMap.clear(),this.previousStates.clear(),super.destroy()}disableCategoryImpl(e){const t=new Set(this.state.disabledCategories);t.has(e)||(t.add(e),this.dispatch(Ca(Array.from(t))),this.categoryChanged$.emit({disabledCategories:Array.from(t)}))}enableCategoryImpl(e){const t=new Set(this.state.disabledCategories);t.has(e)&&(t.delete(e),this.dispatch(Ca(Array.from(t))),this.categoryChanged$.emit({disabledCategories:Array.from(t)}))}toggleCategoryImpl(e){this.state.disabledCategories.includes(e)?this.enableCategoryImpl(e):this.disableCategoryImpl(e)}setDisabledCategoriesImpl(e){this.dispatch(Ca(e)),this.categoryChanged$.emit({disabledCategories:e})}isCommandCategoryDisabled(e){var t;return!!(null==(t=e.categories)?void 0:t.length)&&e.categories.some(e=>this.state.disabledCategories.includes(e))}buildCapability(){return{resolve:(e,t)=>this.resolve(e,t),execute:(e,t,n="ui")=>this.execute(e,t,n),getAllCommands:e=>this.getAllCommands(e),getCommandsByCategory:(e,t)=>this.getCommandsByCategory(e,t),getCommandByShortcut:e=>this.getCommandByShortcut(e),getAllShortcuts:()=>new Map(this.shortcutMap),forDocument:e=>this.createCommandScope(e),registerCommand:e=>this.registerCommand(e),unregisterCommand:e=>this.unregisterCommand(e),disableCategory:e=>this.disableCategoryImpl(e),enableCategory:e=>this.enableCategoryImpl(e),toggleCategory:e=>this.toggleCategoryImpl(e),setDisabledCategories:e=>this.setDisabledCategoriesImpl(e),getDisabledCategories:()=>this.state.disabledCategories,isCategoryDisabled:e=>this.state.disabledCategories.includes(e),onCommandExecuted:this.commandExecuted$.on,onCommandStateChanged:this.commandStateChanged$.on,onShortcutExecuted:this.shortcutExecuted$.on,onCategoryChanged:this.categoryChanged$.on}}createCommandScope(e){return{resolve:t=>this.resolve(t,e),execute:(t,n="ui")=>this.execute(t,e,n),getAllCommands:()=>this.getAllCommands(e),getCommandsByCategory:t=>this.getCommandsByCategory(t,e),onCommandStateChanged:t=>this.commandStateChanged$.on(n=>{if(n.documentId===e){const{documentId:e,...o}=n;t(o)}})}}resolve(e,t){const n=t??this.getActiveDocumentId(),o=this.commands.get(e);if(!o)throw new Error(`Command not found: ${e}`);const i=this.registry.getStore().getState(),r=this.resolveLabel(o,i,n),a=o.shortcuts?Array.isArray(o.shortcuts)?o.shortcuts:[o.shortcuts]:void 0,s=this.resolveDynamic(o.disabled,i,n)??!1,l=this.isCommandCategoryDisabled(o),c=s||l;return{id:o.id,label:r,icon:this.resolveDynamic(o.icon,i,n),iconProps:this.resolveDynamic(o.iconProps,i,n),active:this.resolveDynamic(o.active,i,n)??!1,disabled:c,visible:this.resolveDynamic(o.visible,i,n)??!0,shortcuts:a,shortcutLabel:o.shortcutLabel,categories:o.categories,description:o.description,execute:()=>o.action({registry:this.registry,state:i,documentId:n,logger:this.logger})}}resolveLabel(e,t,n){const o=this.resolveDynamic(e.labelKey,t,n);if(o&&this.i18n){const i=this.resolveDynamic(e.labelParams,t,n);return this.i18n.t(o,{params:i,documentId:n})}return e.label?e.label:e.id}resolveDynamic(e,t,n){if(void 0!==e)return"function"==typeof e?e({registry:this.registry,state:t,documentId:n,logger:this.logger}):e}execute(e,t,n="ui"){const o=t??this.getActiveDocumentId(),i=this.resolve(e,o);i.disabled?this.logger.warn("CommandsPlugin","ExecutionBlocked",`Command '${e}' is disabled for document '${o}'`):i.visible?(i.execute(),this.commandExecuted$.emit({commandId:e,documentId:o,source:n}),this.logger.debug("CommandsPlugin","CommandExecuted",`Command '${e}' executed for document '${o}' (source: ${n})`)):this.logger.warn("CommandsPlugin","ExecutionBlocked",`Command '${e}' is not visible for document '${o}'`)}registerCommand(e){if(this.commands.has(e.id)&&this.logger.warn("CommandsPlugin","CommandOverwrite",`Command '${e.id}' already exists and will be overwritten`),this.commands.set(e.id,e),e.shortcuts){(Array.isArray(e.shortcuts)?e.shortcuts:[e.shortcuts]).forEach(t=>{const n=this.normalizeShortcut(t);this.shortcutMap.set(n,e.id)})}this.logger.debug("CommandsPlugin","CommandRegistered",`Command '${e.id}' registered`)}unregisterCommand(e){const t=this.commands.get(e);if(t){if(t.shortcuts){(Array.isArray(t.shortcuts)?t.shortcuts:[t.shortcuts]).forEach(e=>{const t=this.normalizeShortcut(e);this.shortcutMap.delete(t)})}this.commands.delete(e),this.logger.debug("CommandsPlugin","CommandUnregistered",`Command '${e}' unregistered`)}}getCommandByShortcut(e){const t=this.normalizeShortcut(e),n=this.shortcutMap.get(t);return n?this.commands.get(n)??null:null}normalizeShortcut(e){return e.toLowerCase().split("+").sort().join("+")}getAllCommands(e){const t=e??this.getActiveDocumentId();return Array.from(this.commands.keys()).map(e=>this.resolve(e,t))}getCommandsByCategory(e,t){const n=t??this.getActiveDocumentId();return Array.from(this.commands.values()).filter(t=>{var n;return null==(n=t.categories)?void 0:n.includes(e)}).map(e=>this.resolve(e.id,n))}onGlobalStoreChange(e){Object.keys(e.core.documents).forEach(t=>{this.detectCommandChanges(t,e)})}detectCommandChanges(e,t){const n=t.core.documents[e];if(!n||"loaded"!==n.status)return;const o=this.previousStates.get(e)??new Map;this.commands.forEach((t,n)=>{const i=this.resolve(n,e),r=o.get(n);if(!r)return void o.set(n,i);const a={};r.active!==i.active&&(a.active=i.active),r.disabled!==i.disabled&&(a.disabled=i.disabled),r.visible!==i.visible&&(a.visible=i.visible),r.label!==i.label&&(a.label=i.label),r.icon!==i.icon&&(a.icon=i.icon),xo(r.iconProps,i.iconProps)||(a.iconProps=i.iconProps),Object.keys(a).length>0&&(o.set(n,i),this.commandStateChanged$.emit({commandId:n,documentId:e,changes:a}))}),this.previousStates.set(e,o)}};Ia.id="commands";let ka=Ia;const Sa={disabledCategories:[]},Ma=()=>_o(ka.id),Aa=(e,t)=>{const{provides:n}=Ma(),[o,i]=Se(()=>n?n.resolve(e,t):null);return Ae(()=>{if(!n)return void i(null);i(n.resolve(e,t));return n.onCommandStateChanged(o=>{o.commandId===e&&o.documentId===t&&i(n.resolve(e,t))})},[n,e,t]),o};const Pa=Do({manifest:wa,create:(e,t)=>new ka(ba,e,t),reducer:(e=Sa,t)=>t.type===xa?{...e,disabledCategories:t.payload}:e,initialState:Sa}).addUtility(function(){const{provides:e}=Ma();return Ae(()=>{if(!e)return;const t=function(e){return t=>{const n=t.composedPath()[0]||t.target;if("INPUT"===n.tagName||"TEXTAREA"===n.tagName||n.isContentEditable)return;const o=function(e){const t=[];e.ctrlKey&&t.push("ctrl"),e.shiftKey&&t.push("shift"),e.altKey&&t.push("alt"),e.metaKey&&t.push("meta");const n=e.key.toLowerCase();return["control","shift","alt","meta"].includes(n)?null:[...t,n].sort().join("+")}(t);if(!o)return;const i=e.getCommandByShortcut(o);if(!i)return;const r=e.resolve(i.id);!r.disabled&&r.visible&&(t.preventDefault(),t.stopPropagation(),e.execute(i.id,void 0,"keyboard"))}}(e);return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[e]),null}).build(),Da="i18n",Ra={id:Da,name:"I18n Plugin",version:"1.0.0",provides:["i18n"],requires:[],optional:[],defaultConfig:{defaultLocale:"en",locales:[{code:"en",name:"English",translations:{commands:{zoom:{in:"Zoom In",out:"Zoom Out",fitWidth:"Fit to Width",fitPage:"Fit to Page",automatic:"Automatic",level:"Zoom Level ({level}%)",inArea:"Zoom In Area"},fullscreen:{enter:"Enter Full Screen",exit:"Exit Full Screen"},rotate:{clockwise:"Rotate Clockwise",counterclockwise:"Rotate Counter-Clockwise"},menu:"Menu",sidebar:"Sidebar",search:"Search",comment:"Comment",download:"Download",print:"Print",openFile:"Open PDF",save:"Save",settings:"Settings",view:"View",annotate:"Annotate",shapes:"Shapes",redact:"Redact",fillAndSign:"Fill and Sign",form:"Form",pan:"Pan",pointer:"Pointer",undo:"Undo",redo:"Redo",copy:"Copy",screenshot:"Screenshot",nextPage:"Next Page",previousPage:"Previous Page"}}},{code:"es",name:"Español",translations:{commands:{zoom:{in:"Acercar",out:"Alejar",fitWidth:"Ajustar al ancho",fitPage:"Ajustar a la página",automatic:"Automático",level:"Nivel de zoom ({level}%)",inArea:"Acercar área"},fullscreen:{enter:"Pantalla completa",exit:"Salir de pantalla completa"},rotate:{clockwise:"Girar a la derecha",counterclockwise:"Girar a la izquierda"},menu:"Menú",sidebar:"Barra lateral",search:"Buscar",comment:"Comentario",download:"Descargar",print:"Imprimir",openFile:"Abrir PDF",save:"Guardar",settings:"Configuración",view:"Ver",annotate:"Anotar",shapes:"Formas",redact:"Redactar",fillAndSign:"Rellenar y firmar",form:"Formulario",pan:"Desplazar",pointer:"Puntero",undo:"Deshacer",redo:"Rehacer",copy:"Copiar",screenshot:"Captura de pantalla",nextPage:"Página siguiente",previousPage:"Página anterior"}}}]}},za="I18N/SET_LOCALE",Ta="I18N/REGISTER_LOCALE",Ea=e=>({type:za,payload:e}),_a=e=>({type:Ta,payload:e}),Na=class extends fo{constructor(e,t,n){super(e,t),this.locales=new Map,this.paramResolvers=new Map,this.paramsCache=new Map,this.localeChange$=So(),this.paramsChanged$=Ao((e,t)=>({documentId:e,...t}),{cache:!1}),this.config=n,n.locales.forEach(e=>{this.locales.set(e.code,e),this.dispatch(_a(e.code))}),n.paramResolvers&&Object.entries(n.paramResolvers).forEach(([e,t])=>{this.paramResolvers.set(e,t)}),this.dispatch(Ea(n.defaultLocale)),this.registry.getStore().subscribe((e,t)=>{this.detectParamChanges(t)})}async initialize(){this.logger.info("I18nPlugin","Initialize","I18n plugin initialized")}async destroy(){this.localeChange$.clear(),this.paramsChanged$.clear(),this.paramResolvers.clear(),this.paramsCache.clear(),super.destroy()}onDocumentClosed(e){this.paramsCache.delete(e),this.paramsChanged$.clearScope(e),this.logger.debug("I18nPlugin","DocumentClosed",`Cleaned up params cache for document: ${e}`)}buildCapability(){return{t:(e,t)=>this.translate(e,t),forDocument:e=>this.createI18nScope(e),registerParamResolver:(e,t)=>this.registerParamResolver(e,t),unregisterParamResolver:e=>this.unregisterParamResolver(e),setLocale:e=>this.setLocale(e),getLocale:()=>this.state.currentLocale,getAvailableLocales:()=>[...this.state.availableLocales],getLocaleInfo:e=>this.locales.get(e)??null,registerLocale:e=>this.registerLocale(e),hasLocale:e=>this.locales.has(e),onLocaleChange:this.localeChange$.on,onParamsChanged:this.paramsChanged$.onGlobal}}createI18nScope(e){return{t:(t,n)=>this.translate(t,{documentId:e,...n}),onParamsChanged:this.paramsChanged$.forScope(e)}}translate(e,t){const n=this.locales.get(this.state.currentLocale),o=this.config.fallbackLocale?this.locales.get(this.config.fallbackLocale):null;let i=this.getNestedValue(null==n?void 0:n.translations,e);if(!i&&o&&(i=this.getNestedValue(o.translations,e)),!i){if(!(null==t?void 0:t.fallback))return this.logger.warn("I18nPlugin","MissingTranslation",`Translation not found for key: ${e}`),e;i=t.fallback}let r=null==t?void 0:t.params;return!r&&this.paramResolvers.has(e)&&(r=this.resolveParams(e,null==t?void 0:t.documentId)),this.interpolate(i,r)}resolveParams(e,t){const n=this.paramResolvers.get(e);if(!n)return;const o=this.registry.getStore().getState();try{return n({state:o,documentId:t})}catch(t){return void this.logger.error("I18nPlugin","ParamResolverError",`Error resolving params for key "${e}":`,t)}}getNestedValue(e,t){if(!e)return;const n=t.split(".");let o=e;for(const e of n){if(null==o)return;o=o[e]}return"string"==typeof o?o:void 0}interpolate(e,t){return t?e.replace(/\{(\w+)\}/g,(e,n)=>{const o=t[n];return void 0!==o?String(o):e}):e}detectParamChanges(e){Object.keys(e.core.documents).forEach(t=>{this.detectDocumentParamChanges(t,e)})}detectDocumentParamChanges(e,t){const n=this.paramsCache.get(e),o=[];this.paramResolvers.forEach((i,r)=>{try{const a=i({state:t,documentId:e});xo(null==n?void 0:n.get(r),a)||(o.push(r),this.paramsCache.has(e)||this.paramsCache.set(e,new Map),this.paramsCache.get(e).set(r,a))}catch(e){this.logger.error("I18nPlugin","ParamDetectionError",`Error detecting param changes for key "${r}":`,e)}}),o.length>0&&(this.paramsChanged$.emit(e,{changedKeys:o}),this.logger.debug("I18nPlugin","ParamsChanged",`Translation params changed for document ${e}:`,o))}registerParamResolver(e,t){this.paramResolvers.has(e)&&this.logger.warn("I18nPlugin","ResolverOverwrite",`Param resolver for "${e}" already exists and will be overwritten`),this.paramResolvers.set(e,t),this.paramsCache.forEach(t=>{t.delete(e)}),this.logger.debug("I18nPlugin","ResolverRegistered",`Param resolver registered for: ${e}`)}unregisterParamResolver(e){this.paramResolvers.delete(e)&&(this.paramsCache.forEach(t=>{t.delete(e)}),this.logger.debug("I18nPlugin","ResolverUnregistered",`Param resolver unregistered for: ${e}`))}setLocale(e){if(!this.locales.has(e))return void this.logger.warn("I18nPlugin","LocaleNotFound",`Locale '${e}' is not registered`);const t=this.state.currentLocale;t!==e&&(this.dispatch(Ea(e)),this.localeChange$.emit({previousLocale:t,currentLocale:e}),this.logger.info("I18nPlugin","LocaleChanged",`Locale changed to: ${e}`))}registerLocale(e){this.locales.has(e.code)?this.logger.warn("I18nPlugin","LocaleAlreadyRegistered",`Locale '${e.code}' is already registered`):(this.locales.set(e.code,e),this.dispatch(_a(e.code)),this.logger.info("I18nPlugin","LocaleRegistered",`Locale registered: ${e.code}`))}};Na.id="i18n";let Oa=Na;const La={currentLocale:"en",availableLocales:[]},$a={manifest:Ra,create:(e,t)=>new Oa(Da,e,t),reducer:(e=La,t)=>{switch(t.type){case za:{const n=t.payload;return e.availableLocales.includes(n)?{...e,currentLocale:n}:(console.warn(`I18nPlugin: Locale '${n}' not available`),e)}case Ta:{const n=t.payload;return e.availableLocales.includes(n)?e:{...e,availableLocales:[...e.availableLocales,n]}}default:return e}},initialState:La},ja=e=>{const{provides:t}=_o(Oa.id),[,n]=Me(e=>e+1,0),o=ze((n,o)=>t?t.t(n,{documentId:e,params:null==o?void 0:o.params,fallback:null==o?void 0:o.fallback}):(null==o?void 0:o.fallback)??n,[t,e]);return Ae(()=>{if(!t)return;const o=t.onLocaleChange(()=>{n()}),i=e?t.forDocument(e).onParamsChanged(()=>{n()}):t.onParamsChanged(()=>{n()});return()=>{o(),i()}},[t,e]),{translate:o,locale:(null==t?void 0:t.getLocale())??"en"}};var Fa=(e=>(e.Automatic="automatic",e.FitPage="fit-page",e.FitWidth="fit-width",e))(Fa||{}),Ua=(e=>(e[e.Center=0]="Center",e[e.Top=1]="Top",e))(Ua||{});const Ha="zoom",Ba={id:Ha,name:"Zoom Plugin",version:"1.0.0",provides:["zoom"],requires:["viewport","scroll"],optional:["interaction-manager","spread"],defaultConfig:{defaultZoomLevel:Fa.Automatic,minZoom:.2,maxZoom:60,zoomStep:.1,zoomRanges:[{min:.2,max:.5,step:.05},{min:.5,max:1,step:.1},{min:1,max:2,step:.2},{min:2,max:4,step:.4},{min:4,max:10,step:.8},{min:10,max:20,step:1.6},{min:20,max:40,step:3.2},{min:40,max:60,step:6.4}],presets:[{name:"Fit Page",value:Fa.FitPage},{name:"Fit Width",value:Fa.FitWidth},{name:"Automatic",value:Fa.Automatic},{name:"25%",value:.25},{name:"50%",value:.5},{name:"100%",value:1},{name:"125%",value:1.25},{name:"150%",value:1.5},{name:"200%",value:2},{name:"400%",value:4},{name:"800%",value:8},{name:"1600%",value:16}]}},Wa="ZOOM/INIT_STATE",qa="ZOOM/CLEANUP_STATE",Ga="ZOOM/SET_ZOOM_LEVEL",Va="ZOOM/SET_MARQUEE_ZOOM_ACTIVE";const Ka={zoomLevel:Fa.Automatic,currentZoomLevel:1,isMarqueeZoomActive:!1},Za={documents:{},activeDocumentId:null};const Ya=class extends fo{constructor(e,t,n){var o,i,r;super(e,t),this.zoom$=So(),this.state$=Mo(),this.viewportPlugin=t.getPlugin("viewport"),this.viewport=this.viewportPlugin.provides(),this.scroll=t.getPlugin("scroll").provides();const a=t.getPlugin("interaction-manager");this.interactionManager=(null==a?void 0:a.provides())??null;const s=t.getPlugin("spread");this.spread=(null==s?void 0:s.provides())??null,this.minZoom=n.minZoom??.25,this.maxZoom=n.maxZoom??10,this.zoomStep=n.zoomStep??.1,this.defaultZoomLevel=n.defaultZoomLevel,this.presets=n.presets??[],this.zoomRanges=this.normalizeRanges(n.zoomRanges??[]),this.viewport.onViewportResize(e=>this.recalcAuto(e.documentId,Ua.Top),{mode:"debounce",wait:150,keyExtractor:e=>e.documentId}),null==(o=this.spread)||o.onSpreadChange(e=>{this.recalcAuto(e.documentId,Ua.Top)}),null==(i=this.interactionManager)||i.registerMode({id:"marqueeZoom",scope:"page",exclusive:!0,cursor:"zoom-in"}),null==(r=this.interactionManager)||r.onModeChange(e=>{const t="marqueeZoom"===e.activeMode,n=this.getDocumentState(e.documentId);var o;n&&n.isMarqueeZoomActive!==t&&this.dispatch((o=e.documentId,{type:Va,payload:{documentId:o,isActive:t}}))})}onDocumentLoadingStarted(e){this.viewport.gate("zoom",e);const t={...Ka,zoomLevel:this.defaultZoomLevel};this.dispatch(function(e,t){return{type:Wa,payload:{documentId:e,state:t}}}(e,t)),this.logger.debug("ZoomPlugin","DocumentOpened",`Initialized zoom state for document: ${e}`)}onDocumentLoaded(e){this.recalcAuto(e,Ua.Top)}onDocumentClosed(e){this.dispatch(function(e){return{type:qa,payload:e}}(e)),this.logger.debug("ZoomPlugin","DocumentClosed",`Cleaned up zoom state for document: ${e}`)}onRotationChanged(e){this.recalcAuto(e,Ua.Top)}buildCapability(){return{requestZoom:(e,t)=>this.requestZoom(e,t),requestZoomBy:(e,t)=>this.requestZoomBy(e,t),zoomIn:()=>this.zoomIn(),zoomOut:()=>this.zoomOut(),zoomToArea:(e,t)=>this.zoomToArea(e,t),enableMarqueeZoom:()=>this.enableMarqueeZoom(),disableMarqueeZoom:()=>this.disableMarqueeZoom(),toggleMarqueeZoom:()=>this.toggleMarqueeZoom(),isMarqueeZoomActive:()=>this.isMarqueeZoomActive(),getState:()=>this.getDocumentStateOrThrow(),forDocument:e=>this.createZoomScope(e),registerMarqueeOnPage:e=>this.registerMarqueeOnPage(e),getPresets:()=>this.presets,onZoomChange:this.zoom$.on,onStateChange:this.state$.on}}createZoomScope(e){return{requestZoom:(t,n)=>this.requestZoom(t,n,e),requestZoomBy:(t,n)=>this.requestZoomBy(t,n,e),zoomIn:()=>this.zoomIn(e),zoomOut:()=>this.zoomOut(e),zoomToArea:(t,n)=>this.zoomToArea(t,n,e),enableMarqueeZoom:()=>this.enableMarqueeZoom(e),disableMarqueeZoom:()=>this.disableMarqueeZoom(e),toggleMarqueeZoom:()=>this.toggleMarqueeZoom(e),isMarqueeZoomActive:()=>this.isMarqueeZoomActive(e),getState:()=>this.getDocumentStateOrThrow(e),onZoomChange:t=>this.zoom$.on(n=>{n.documentId===e&&t(n)}),onStateChange:t=>this.state$.on(n=>{n.documentId===e&&t(n.state)})}}getDocumentState(e){const t=e??this.getActiveDocumentId();return this.state.documents[t]??null}getDocumentStateOrThrow(e){const t=this.getDocumentState(e);if(!t)throw new Error(`Zoom state not found for document: ${e??"active"}`);return t}requestZoom(e,t,n){this.handleRequest({level:e,center:t},n)}requestZoomBy(e,t,n){const o=n??this.getActiveDocumentId(),i=this.getDocumentStateOrThrow(o).currentZoomLevel,r=this.toZoom(i+e);this.handleRequest({level:r,center:t},o)}zoomIn(e){const t=e??this.getActiveDocumentId(),n=this.getDocumentStateOrThrow(t).currentZoomLevel;this.handleRequest({level:n,delta:this.stepFor(n)},t)}zoomOut(e){const t=e??this.getActiveDocumentId(),n=this.getDocumentStateOrThrow(t).currentZoomLevel;this.handleRequest({level:n,delta:-this.stepFor(n)},t)}zoomToArea(e,t,n){const o=n??this.getActiveDocumentId();this.handleZoomToArea(o,e,t)}enableMarqueeZoom(e){var t;const n=e??this.getActiveDocumentId();null==(t=this.interactionManager)||t.forDocument(n).activate("marqueeZoom")}disableMarqueeZoom(e){var t;const n=e??this.getActiveDocumentId();null==(t=this.interactionManager)||t.forDocument(n).activateDefaultMode()}toggleMarqueeZoom(e){var t;const n=e??this.getActiveDocumentId(),o=null==(t=this.interactionManager)?void 0:t.forDocument(n);"marqueeZoom"===(null==o?void 0:o.getActiveMode())?o.activateDefaultMode():null==o||o.activate("marqueeZoom")}isMarqueeZoomActive(e){var t;const n=e??this.getActiveDocumentId();return"marqueeZoom"===(null==(t=this.interactionManager)?void 0:t.forDocument(n).getActiveMode())}handleRequest({level:e,delta:t=0,center:n,focus:o=Ua.Center,align:i="keep"},r){const a=r??this.getActiveDocumentId(),s=this.getDocumentStateOrThrow(a);if(!this.coreState.core.documents[a])return;const l=this.viewport.forDocument(a),c=l.getMetrics(),d=s.currentZoomLevel;if(0===c.clientWidth||0===c.clientHeight)return;const u="number"==typeof e?e:this.computeZoomForMode(a,e,c);if(!1===u)return;const h=wo(u+t,this.minZoom,this.maxZoom),m=Math.floor(1e3*h)/1e3,g=n??{vx:c.clientWidth/2,vy:o===Ua.Top?0:c.clientHeight/2},{desiredScrollLeft:p,desiredScrollTop:f}=this.computeScrollForZoomChange(a,c,d,m,g,i);isNaN(p)||isNaN(f)||this.viewportPlugin.setViewportScrollMetrics(a,{scrollLeft:p,scrollTop:f}),this.dispatch(function(e,t,n){return{type:Ga,payload:{documentId:e,zoomLevel:t,currentZoomLevel:n}}}(a,"number"==typeof e?m:e,m)),this.dispatchCoreAction(((e,t)=>({type:Xn,payload:{scale:e,documentId:t}}))(m,a)),this.viewport.isGated(a)&&this.viewport.releaseGate("zoom",a),l.scrollTo({x:p,y:f,behavior:"instant"});const v={documentId:a,oldZoom:d,newZoom:m,level:e,center:g,desiredScrollLeft:p,desiredScrollTop:f,viewport:c};this.zoom$.emit(v)}computeZoomForMode(e,t,n){if(!this.coreState.core.documents[e])return!1;const o=this.scroll.forDocument(e),i=o?this.scroll.getPageGap():0,r=this.viewport.getViewportGap(),a=o.getSpreadPagesWithRotatedSize();if(!a.length)return!1;if(0===n.clientWidth||0===n.clientHeight)return!1;const s=n.clientWidth-2*r,l=n.clientHeight-2*r;if(s<=0||l<=0)return!1;let c=0,d=0;switch(a.forEach(e=>{const t=e.reduce((e,t,n)=>e+t.rotatedSize.width+(n?i:0),0),n=Math.max(...e.map(e=>e.rotatedSize.height));c=Math.max(c,t),d=Math.max(d,n)}),t){case Fa.FitWidth:return s/c;case Fa.FitPage:return Math.min(s/c,l/d);case Fa.Automatic:return Math.min(s/c,1);default:return 1}}computeScrollForZoomChange(e,t,n,o,i,r="keep"){const a=this.scroll.forDocument(e).getLayout(),s=this.viewport.getViewportGap(),l=a.totalContentSize.width,c=a.totalContentSize.height,d=t.clientWidth-2*s,u=t.clientHeight-2*s,h=(e,t,n)=>t*ne.pageLayouts.some(e=>e.pageIndex===t));if(!u)return;const h=u.pageLayouts.find(e=>e.pageIndex===t),m=tt({width:h.width,height:h.height},n,i),g=this.toZoom(Math.min(l/m.size.width,c/m.size.height)),p=u.x+h.x,f=u.y+h.y,v=p+m.origin.x+m.size.width/2,y=f+m.origin.y+m.size.height/2,b=(e,t,n)=>t*ne.step>0&&e.max>e.min).sort((e,t)=>e.min-t.min)}stepFor(e){const t=this.zoomRanges.find(t=>e>=t.min&&e{};const t=this.coreState.core.documents[e.documentId];if(!t||!t.document)return this.logger.warn("ZoomPlugin","DocumentNotFound","Document not found"),()=>{};const n=t.document.pages[e.pageIndex];if(!n)return this.logger.warn("ZoomPlugin","PageNotFound",`Page ${e.pageIndex} not found`),()=>{};const o=function(e){const{pageSize:t,scale:n,minDragPx:o=5,onPreview:i,onCommit:r,onSmallDrag:a}=e;let s=null,l=null;return{onPointerDown:(e,t)=>{var n;s=e,l={origin:{x:e.x,y:e.y},size:{width:0,height:0}},null==i||i(l),null==(n=t.setPointerCapture)||n.call(t)},onPointerMove:e=>{if(!s)return;const n=wo(e.x,0,t.width),o=wo(e.y,0,t.height);l={origin:{x:Math.min(s.x,n),y:Math.min(s.y,o)},size:{width:Math.abs(n-s.x),height:Math.abs(o-s.y)}},null==i||i(l)},onPointerUp:(e,t)=>{var c;l&&(Math.max(l.size.width,l.size.height)*n>o?null==r||r(l):null==a||a()),s=null,l=null,null==i||i(null),null==(c=t.releasePointerCapture)||c.call(t)},onPointerCancel:(e,t)=>{var n;s=null,l=null,null==i||i(null),null==(n=t.releasePointerCapture)||n.call(t)}}}({pageSize:n.size,scale:e.scale,onPreview:e.callback.onPreview,onCommit:t=>{var n,o;this.zoomToArea(e.pageIndex,t,e.documentId),null==(o=(n=e.callback).onCommit)||o.call(n,t)},onSmallDrag:()=>{var t,n;this.zoomIn(e.documentId),null==(n=(t=e.callback).onSmallDrag)||n.call(t)}});return this.interactionManager.registerHandlers({documentId:e.documentId,modeId:"marqueeZoom",handlers:o,pageIndex:e.pageIndex})}onStoreUpdated(e,t){for(const n in t.documents){const o=e.documents[n],i=t.documents[n];o&&i&&(o.currentZoomLevel!==i.currentZoomLevel||o.zoomLevel!==i.zoomLevel||o.isMarqueeZoomActive!==i.isMarqueeZoomActive)&&this.state$.emit({documentId:n,state:i})}}async initialize(){this.logger.info("ZoomPlugin","Initialize","Zoom plugin initialized")}async destroy(){this.zoom$.clear(),this.state$.clear(),super.destroy()}};Ya.id="zoom";let Xa=Ya;const Qa={manifest:Ba,create:(e,t)=>new Xa(Ha,e,t),reducer:(e=Za,t)=>{switch(t.type){case Wa:{const{documentId:n,state:o}=t.payload;return{...e,documents:{...e.documents,[n]:o},activeDocumentId:e.activeDocumentId??n}}case qa:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i,activeDocumentId:e.activeDocumentId===n?null:e.activeDocumentId}}case"ZOOM/SET_ACTIVE_DOCUMENT":return{...e,activeDocumentId:t.payload};case Ga:{const{documentId:n,zoomLevel:o,currentZoomLevel:i}=t.payload,r=e.documents[n];return r?{...e,documents:{...e.documents,[n]:{...r,zoomLevel:o,currentZoomLevel:i}}}:e}case Va:{const{documentId:n,isActive:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,isMarqueeZoomActive:o}}}:e}default:return e}},initialState:Za},Ja=()=>_o(Xa.id);function es(e){const[t,n]=[e[0],e[1]],o=n.clientX-t.clientX,i=n.clientY-t.clientY;return Math.hypot(o,i)}function ts(e,t={}){const{provides:n}=_o("viewport"),{provides:o}=Ja(),i=Te(li),r=De(null);return Pe(()=>{const a=r.current,s=null==i?void 0:i.current;if(a&&s&&o)return function({element:e,container:t,documentId:n,zoomProvides:o,viewportGap:i=0,options:r={}}){const{enablePinch:a=!0,enableWheel:s=!0}=r;if("undefined"==typeof window)return()=>{};const l=o.forDocument(n),c=()=>l.getState();let d=0,u=1,h=!1,m=0,g=null,p=1,f=0,v=0,y=0,b=0,w=0,x=0,C=0,I=0,k=0,S=0,M=0,A=0,P=0;const D=(e,t,n)=>Math.min(Math.max(e,t),n),R=()=>{const n=t.clientWidth-2*i,o=e.offsetWidth,r=o{const t=f*e,n=v*e;let o=k*(1-e);const i=I-t/2-y,r=S-P*e-y,a=Math.max(0,t-C),s=.3*C,l=Math.min(1,a/s);let c=i+(r-i)*l;return n>x-2*A&&(o=D(b+o,x-A-n,A)-b),t>w-2*A&&(c=D(y+c,w-A-t,A)-y),{tx:c,ty:o,blend:l,finalWidth:t}},T=t=>{u=t;const{tx:n,ty:o}=z(t);e.style.transformOrigin="0 0",e.style.transform=`translate(${n}px, ${o}px) scale(${t})`},E=()=>{e.style.transform="none",e.style.transformOrigin="0 0",u=1},_=()=>{const{tx:e,finalWidth:t}=z(u),n=(u-1)*d;let o,i=M;if(t<=C)o=I;else{const t=1-u;o=Math.abs(t)>.001?y+e/t:S}l.requestZoomBy(n,{vx:o,vy:i}),E(),d=0},N=(n,o)=>{const r=t.getBoundingClientRect(),a=e.getBoundingClientRect();A=i,f=a.width,v=a.height,y=a.left-r.left,b=a.top-r.top,w=r.width,x=r.height,C=t.clientWidth,I=t.clientLeft+C/2;const s=n-a.left;k=o-a.top,S=n-r.left,M=o-r.top,P=f{if(2!==e.touches.length)return;h=!0,d=c().currentZoomLevel,m=es(e.touches);const t=function(e){const[t,n]=[e[0],e[1]];return{x:(t.clientX+n.clientX)/2,y:(t.clientY+n.clientY)/2}}(e.touches);N(t.x,t.y),e.preventDefault()},L=e=>{if(!h||2!==e.touches.length)return;const t=es(e.touches);T(t/m),e.preventDefault()},$=e=>{h&&(e.touches.length>=2||(h=!1,_()))},j=e=>{if(!e.ctrlKey&&!e.metaKey)return;e.preventDefault(),null===g?(d=c().currentZoomLevel,p=1,N(e.clientX,e.clientY)):clearTimeout(g);const t=1-.01*e.deltaY;p*=t,p=Math.max(.1,Math.min(10,p)),T(p),g=setTimeout(()=>{g=null,_(),p=1},150)},F=l.onStateChange(()=>R()),U=new ResizeObserver(()=>R());return U.observe(e),U.observe(t),R(),a&&(t.addEventListener("touchstart",O,{passive:!1}),t.addEventListener("touchmove",L,{passive:!1}),t.addEventListener("touchend",$),t.addEventListener("touchcancel",$)),s&&t.addEventListener("wheel",j,{passive:!1}),()=>{a&&(t.removeEventListener("touchstart",O),t.removeEventListener("touchmove",L),t.removeEventListener("touchend",$),t.removeEventListener("touchcancel",$)),s&&t.removeEventListener("wheel",j),g&&clearTimeout(g),F(),U.disconnect(),E(),e.style.marginLeft=""}}({element:a,container:s,documentId:e,zoomProvides:o,viewportGap:(null==n?void 0:n.getViewportGap())||0,options:t})},[n,o,e,i,t.enablePinch,t.enableWheel]),{elementRef:r}}function ns({children:e,documentId:t,style:n,enablePinch:o=!0,enableWheel:i=!0,...r}){const a=Re(()=>({enablePinch:o,enableWheel:i}),[o,i]),{elementRef:s}=ts(t,a);return He("div",{ref:s,...r,style:{...n,display:"inline-block",overflow:"visible",boxSizing:"border-box"},children:e})}const os=({documentId:e,pageIndex:t,scale:n,className:o,stroke:i="rgba(33,150,243,0.8)",fill:r="rgba(33,150,243,0.15)"})=>{const{provides:a}=Ja(),s=Oo(e),[l,c]=Se(null),d=Re(()=>void 0!==n?n:(null==s?void 0:s.scale)??1,[n,null==s?void 0:s.scale]);return Ae(()=>{if(a)return a.registerMarqueeOnPage({documentId:e,pageIndex:t,scale:d,callback:{onPreview:c}})},[a,e,t,d]),l?He("div",{style:{position:"absolute",pointerEvents:"none",left:l.origin.x*d,top:l.origin.y*d,width:l.size.width*d,height:l.size.height*d,border:`1px solid ${i}`,background:r,boxSizing:"border-box"},className:o}):null},is=class extends fo{constructor(e,t,n){super(e,t),this.config=n}buildCapability(){return{renderPage:e=>this.renderPage(e),renderPageRect:e=>this.renderPageRect(e),renderPageRaw:e=>this.renderPageRaw(e),renderPageRectRaw:e=>this.renderPageRectRaw(e),forDocument:e=>this.createRenderScope(e)}}createRenderScope(e){return{renderPage:t=>this.renderPage(t,e),renderPageRect:t=>this.renderPageRect(t,e),renderPageRaw:t=>this.renderPageRaw(t,e),renderPageRectRaw:t=>this.renderPageRectRaw(t,e)}}renderPage({pageIndex:e,options:t},n){const o=n??this.getActiveDocumentId(),i=this.coreState.core.documents[o];if(!(null==i?void 0:i.document))throw new Error(`Document ${o} not loaded`);const r=i.document.pages.find(t=>t.index===e);if(!r)throw new Error(`Page ${e} not found in document ${o}`);const a={...t??{},withForms:(null==t?void 0:t.withForms)??this.config.withForms??!1,withAnnotations:(null==t?void 0:t.withAnnotations)??this.config.withAnnotations??!1,imageType:(null==t?void 0:t.imageType)??this.config.defaultImageType??"image/png",imageQuality:(null==t?void 0:t.imageQuality)??this.config.defaultImageQuality??.92};return this.engine.renderPage(i.document,r,a)}renderPageRect({pageIndex:e,rect:t,options:n},o){const i=o??this.getActiveDocumentId(),r=this.coreState.core.documents[i];if(!(null==r?void 0:r.document))throw new Error(`Document ${i} not loaded`);const a=r.document.pages.find(t=>t.index===e);if(!a)throw new Error(`Page ${e} not found in document ${i}`);const s={...n??{},withForms:(null==n?void 0:n.withForms)??this.config.withForms??!1,withAnnotations:(null==n?void 0:n.withAnnotations)??this.config.withAnnotations??!1,imageType:(null==n?void 0:n.imageType)??this.config.defaultImageType??"image/png",imageQuality:(null==n?void 0:n.imageQuality)??this.config.defaultImageQuality??.92};return this.engine.renderPageRect(r.document,a,t,s)}renderPageRaw({pageIndex:e,options:t},n){const o=n??this.getActiveDocumentId(),i=this.coreState.core.documents[o];if(!(null==i?void 0:i.document))throw new Error(`Document ${o} not loaded`);const r=i.document.pages.find(t=>t.index===e);if(!r)throw new Error(`Page ${e} not found in document ${o}`);const a={...t??{},withForms:(null==t?void 0:t.withForms)??this.config.withForms??!1,withAnnotations:(null==t?void 0:t.withAnnotations)??this.config.withAnnotations??!1};return this.engine.renderPageRaw(i.document,r,a)}renderPageRectRaw({pageIndex:e,rect:t,options:n},o){const i=o??this.getActiveDocumentId(),r=this.coreState.core.documents[i];if(!(null==r?void 0:r.document))throw new Error(`Document ${i} not loaded`);const a=r.document.pages.find(t=>t.index===e);if(!a)throw new Error(`Page ${e} not found in document ${i}`);const s={...n??{},withForms:(null==n?void 0:n.withForms)??this.config.withForms??!1,withAnnotations:(null==n?void 0:n.withAnnotations)??this.config.withAnnotations??!1};return this.engine.renderPageRectRaw(r.document,a,t,s)}async initialize(e){this.logger.info("RenderPlugin","Initialize","Render plugin initialized")}async destroy(){super.destroy()}};is.id="render";let rs=is;const as="render",ss={manifest:{id:as,name:"Render Plugin",version:"1.0.0",provides:["render"],requires:[],optional:[],defaultConfig:{}},create:(e,t)=>new rs(as,e,t),reducer:()=>{},initialState:{}};function ls({documentId:e,pageIndex:t,scale:n,dpr:o,style:i,...r}){const{provides:a}=_o(rs.id),s=Oo(e),[l,c]=Se(null),d=De(null),u=Re(()=>s&&s.pageRefreshVersions[t]||0,[s,t]),h=Re(()=>void 0!==n?n:(null==s?void 0:s.scale)??1,[n,null==s?void 0:s.scale]),m=Re(()=>void 0!==o?o:window.devicePixelRatio,[o]);Ae(()=>{if(!a)return;const n=a.forDocument(e).renderPage({pageIndex:t,options:{scaleFactor:h,dpr:m}});return n.wait(e=>{const t=URL.createObjectURL(e);c(t),d.current=t},En),()=>{d.current?(URL.revokeObjectURL(d.current),d.current=null):n.abort({code:Qt.Cancelled,message:"canceled render task"})}},[e,t,h,m,a,u]);return He(H,{children:l&&He("img",{src:l,onLoad:()=>{d.current&&(URL.revokeObjectURL(d.current),d.current=null)},...r,style:{width:"100%",height:"100%",...i||{}}})})}const cs="rotate",ds={id:cs,name:"Rotate Plugin",version:"1.0.0",provides:["rotate"],requires:[],optional:[],defaultConfig:{}};const us="ROTATE/INIT_STATE",hs="ROTATE/CLEANUP_STATE",ms="ROTATE/SET_ROTATION";const gs=class extends fo{constructor(e,t,n){super(e,t),this.rotate$=Mo(),this.defaultRotation=n.defaultRotation??0}onDocumentLoadingStarted(e){const t={rotation:this.defaultRotation};this.dispatch(function(e,t){return{type:us,payload:{documentId:e,state:t}}}(e,t)),this.dispatchCoreAction(oo(this.defaultRotation,e)),this.logger.debug("RotatePlugin","DocumentOpened",`Initialized rotation state for document: ${e}`)}onDocumentClosed(e){this.dispatch(function(e){return{type:hs,payload:e}}(e)),this.logger.debug("RotatePlugin","DocumentClosed",`Cleaned up rotation state for document: ${e}`)}buildCapability(){return{setRotation:e=>this.setRotationForDocument(e),getRotation:()=>this.getRotationForDocument(),rotateForward:()=>this.rotateForward(),rotateBackward:()=>this.rotateBackward(),forDocument:e=>this.createRotateScope(e),onRotateChange:this.rotate$.on}}createRotateScope(e){return{setRotation:t=>this.setRotationForDocument(t,e),getRotation:()=>this.getRotationForDocument(e),rotateForward:()=>this.rotateForward(e),rotateBackward:()=>this.rotateBackward(e),onRotateChange:t=>this.rotate$.on(n=>{n.documentId===e&&t(n.rotation)})}}getDocumentState(e){const t=e??this.getActiveDocumentId();return this.state.documents[t]??null}getDocumentStateOrThrow(e){const t=this.getDocumentState(e);if(!t)throw new Error(`Rotation state not found for document: ${e??"active"}`);return t}setRotationForDocument(e,t){const n=t??this.getActiveDocumentId(),o=this.coreState.core.documents[n];if(!(null==o?void 0:o.document))throw new Error(`Document ${n} not loaded`);this.dispatch(function(e,t){return{type:ms,payload:{documentId:e,rotation:t}}}(n,e)),this.dispatchCoreAction(oo(e,n)),this.rotate$.emit({documentId:n,rotation:e})}getRotationForDocument(e){return this.getDocumentStateOrThrow(e).rotation}rotateForward(e){const t=e??this.getActiveDocumentId(),n=this.getRotationForDocument(t),o=(n+1)%4;this.setRotationForDocument(o,t)}rotateBackward(e){const t=e??this.getActiveDocumentId(),n=this.getRotationForDocument(t),o=(n+3)%4;this.setRotationForDocument(o,t)}getMatrixAsString(e){return function(e,t,n){const[o,i,r,a,s,l]=function(e,t,n){let o=1,i=0,r=0,a=1,s=0,l=0;switch(e){case 1:o=0,i=1,r=-1,a=0,s=n;break;case 2:o=-1,i=0,r=0,a=-1,s=t,l=n;break;case 3:o=0,i=-1,r=1,a=0,l=t}return[o,i,r,a,s,l]}(e,t,n);return`matrix(${o},${i},${r},${a},${s},${l})`}(e.rotation,e.width,e.height)}onStoreUpdated(e,t){for(const n in t.documents){const o=e.documents[n],i=t.documents[n];(null==o?void 0:o.rotation)!==i.rotation&&this.logger.debug("RotatePlugin","RotationChanged",`Rotation changed for document ${n}: ${(null==o?void 0:o.rotation)??0} -> ${i.rotation}`)}}async initialize(e){this.logger.info("RotatePlugin","Initialize","Rotate plugin initialized")}async destroy(){this.rotate$.clear(),super.destroy()}};gs.id="rotate";let ps=gs;const fs={documents:{},activeDocumentId:null},vs={manifest:ds,create:(e,t)=>new ps(cs,e,t),reducer:(e=fs,t)=>{switch(t.type){case us:{const{documentId:n,state:o}=t.payload;return{...e,documents:{...e.documents,[n]:o},activeDocumentId:e.activeDocumentId??n}}case hs:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i,activeDocumentId:e.activeDocumentId===n?null:e.activeDocumentId}}case"ROTATE/SET_ACTIVE_DOCUMENT":return{...e,activeDocumentId:t.payload};case ms:{const{documentId:n,rotation:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,rotation:o}}}:e}default:return e}},initialState:fs};function ys({children:e,documentId:t,pageIndex:n,rotation:o,scale:i,style:r,...a}){var s,l,c,d;const{plugin:u}=Eo(ps.id),h=Oo(t),m=null==(l=null==(s=null==h?void 0:h.document)?void 0:s.pages)?void 0:l[n],g=(null==(c=null==m?void 0:m.size)?void 0:c.width)??0,p=(null==(d=null==m?void 0:m.size)?void 0:d.height)??0,f=(null==m?void 0:m.rotation)??0,v=(null==h?void 0:h.rotation)??0,y=void 0!==o?o:(f+v)%4,b=i??(null==h?void 0:h.scale)??1,w=(null==u?void 0:u.getMatrixAsString({width:g*b,height:p*b,rotation:y}))??"matrix(1, 0, 0, 1, 0, 0)";return m?He("div",{...a,style:{position:"absolute",transformOrigin:"0 0",transform:w,...r},children:e}):null}const bs="SEARCH/INIT_STATE",ws="SEARCH/CLEANUP_STATE",xs="SEARCH/START_SEARCH_SESSION",Cs="SEARCH/STOP_SEARCH_SESSION",Is="SEARCH/SET_SEARCH_FLAGS",ks="SEARCH/SET_SHOW_ALL_RESULTS",Ss="SEARCH/START_SEARCH",Ms="SEARCH/SET_SEARCH_RESULTS",As="SEARCH/APPEND_SEARCH_RESULTS",Ps="SEARCH/SET_ACTIVE_RESULT_INDEX";function Ds(e,t){return{type:ks,payload:{documentId:e,showAll:t}}}function Rs(e,t,n,o){return{type:Ms,payload:{documentId:e,results:t,total:n,activeResultIndex:o}}}function zs(e,t){return{type:Ps,payload:{documentId:e,index:t}}}const Ts={flags:[],results:[],total:0,activeResultIndex:-1,showAllResults:!0,query:"",loading:!1,active:!1},Es={documents:{}},_s=(e,t,n)=>{const o=e.documents[t]||Ts;return{...e,documents:{...e.documents,[t]:{...o,...n}}}},Ns=class extends fo{constructor(e,t,n){super(e,t),this.searchStop$=Mo(),this.searchStart$=Mo(),this.searchResult$=Mo(),this.searchActiveResultChange$=Mo(),this.searchResultState$=Mo(),this.searchState$=Mo(),this.currentTask=new Map,this.pluginConfig=n}onDocumentLoadingStarted(e){const t={...Ts,flags:this.pluginConfig.flags||[],showAllResults:this.pluginConfig.showAllResults??!0};this.dispatch(function(e,t){return{type:bs,payload:{documentId:e,state:t}}}(e,t))}onDocumentClosed(e){this.stopSearchSession(e),this.dispatch(function(e){return{type:ws,payload:e}}(e)),this.currentTask.delete(e)}async initialize(){}onStoreUpdated(e,t){for(const n in t.documents){const o=e.documents[n],i=t.documents[n];o!==i&&(this.searchState$.emit({documentId:n,state:i}),o&&o.results===i.results&&o.activeResultIndex===i.activeResultIndex&&o.showAllResults===i.showAllResults&&o.active===i.active||this.searchResultState$.emit({documentId:n,state:{results:i.results,activeResultIndex:i.activeResultIndex,showAllResults:i.showAllResults,active:i.active}}))}}buildCapability(){const e=e=>e??this.getActiveDocumentId(),t=t=>{const n=e(t),o=this.state.documents[n];if(!o)throw new Error(`Search state not found for document ${n}`);return o};return{startSearch:t=>this.startSearchSession(e(t)),stopSearch:t=>this.stopSearchSession(e(t)),searchAllPages:(t,n)=>this.searchAllPages(t,e(n)),nextResult:t=>this.nextResult(e(t)),previousResult:t=>this.previousResult(e(t)),goToResult:(t,n)=>this.goToResult(t,e(n)),setShowAllResults:(t,n)=>this.dispatch(Ds(e(n),t)),getShowAllResults:e=>t(e).showAllResults,getFlags:e=>t(e).flags,setFlags:(t,n)=>this.setFlags(t,e(n)),getState:e=>t(e),forDocument:this.createSearchScope.bind(this),onSearchResult:this.searchResult$.on,onSearchStart:this.searchStart$.on,onSearchStop:this.searchStop$.on,onActiveResultChange:this.searchActiveResultChange$.on,onSearchResultStateChange:this.searchResultState$.on,onStateChange:this.searchState$.on}}createSearchScope(e){const t=()=>{const t=this.state.documents[e];if(!t)throw new Error(`Search state not found for document ${e}`);return t};return{startSearch:()=>this.startSearchSession(e),stopSearch:()=>this.stopSearchSession(e),searchAllPages:t=>this.searchAllPages(t,e),nextResult:()=>this.nextResult(e),previousResult:()=>this.previousResult(e),goToResult:t=>this.goToResult(t,e),setShowAllResults:t=>this.dispatch(Ds(e,t)),getShowAllResults:()=>t().showAllResults,getFlags:()=>t().flags,setFlags:t=>this.setFlags(t,e),getState:t,onSearchResult:t=>this.searchResult$.on(n=>{n.documentId===e&&t(n.results)}),onSearchStart:t=>this.searchStart$.on(n=>{n.documentId===e&&t()}),onSearchStop:t=>this.searchStop$.on(n=>{n.documentId===e&&t()}),onActiveResultChange:t=>this.searchActiveResultChange$.on(n=>{n.documentId===e&&t(n.index)}),onSearchResultStateChange:t=>this.searchResultState$.on(n=>{n.documentId===e&&t(n.state)}),onStateChange:t=>this.searchState$.on(n=>{n.documentId===e&&t(n.state)})}}setFlags(e,t){this.dispatch(function(e,t){return{type:Is,payload:{documentId:e,flags:t}}}(t,e));const n=this.state.documents[t];(null==n?void 0:n.active)&&this.searchAllPages(n.query,t,!0)}notifySearchStart(e){this.searchStart$.emit({documentId:e})}notifySearchStop(e){this.searchStop$.emit({documentId:e})}notifyActiveResultChange(e,t){this.searchActiveResultChange$.emit({documentId:e,index:t})}startSearchSession(e){this.getCoreDocument(e)&&(this.dispatch(function(e){return{type:xs,payload:{documentId:e}}}(e)),this.notifySearchStart(e))}stopSearchSession(e){var t;const n=this.state.documents[e];if(!(null==n?void 0:n.active))return;const o=this.currentTask.get(e);if(o){try{null==(t=o.abort)||t.call(o,{code:Qt.Cancelled,message:"search stopped"})}catch{}this.currentTask.delete(e)}this.dispatch(function(e){return{type:Cs,payload:{documentId:e}}}(e)),this.notifySearchStop(e)}searchAllPages(e,t,n=!1){var o;const i=this.state.documents[t];if(!i)return Jt.reject({code:Qt.NotFound,message:"Search state not initialized"});const r=this.getCoreDocument(t);if(!(null==r?void 0:r.document))return Jt.reject({code:Qt.NotFound,message:"Document not loaded"});const a=e.trim();if(i.query===a&&!n)return Jt.resolve({results:i.results,total:i.total});const s=this.currentTask.get(t);if(s){try{null==(o=s.abort)||o.call(s,{code:Qt.Cancelled,message:"new search"})}catch{}this.currentTask.delete(t)}if(this.dispatch(function(e,t){return{type:Ss,payload:{documentId:e,query:t}}}(t,a)),!a)return this.dispatch(Rs(t,[],0,-1)),Jt.resolve({results:[],total:0});i.active||this.startSearchSession(t);const l=this.engine.searchAllPages(r.document,a,{flags:i.flags});return this.currentTask.set(t,l),l.onProgress(e=>{var n;(null==(n=null==e?void 0:e.results)?void 0:n.length)&&this.currentTask.get(t)===l&&(this.dispatch(function(e,t){return{type:As,payload:{documentId:e,results:t}}}(t,e.results)),-1===this.state.documents[t].activeResultIndex&&(this.dispatch(zs(t,0)),this.notifyActiveResultChange(t,0)))}),l.wait(e=>{this.currentTask.delete(t);const n=e.total>0?0:-1;this.dispatch(Rs(t,e.results,e.total,n)),this.searchResult$.emit({documentId:t,results:e}),e.total>0&&this.notifyActiveResultChange(t,0)},e=>{var n;(null==(n=null==e?void 0:e.reason)?void 0:n.code)!==Qt.Cancelled&&(console.error("Error during search:",e),this.dispatch(Rs(t,[],0,-1))),this.currentTask.delete(t)}),l}nextResult(e){const t=this.state.documents[e];if(!t||0===t.results.length)return-1;const n=t.activeResultIndex>=t.results.length-1?0:t.activeResultIndex+1;return this.goToResult(n,e)}previousResult(e){const t=this.state.documents[e];if(!t||0===t.results.length)return-1;const n=t.activeResultIndex<=0?t.results.length-1:t.activeResultIndex-1;return this.goToResult(n,e)}goToResult(e,t){const n=this.state.documents[t];return!n||0===n.results.length||e<0||e>=n.results.length?-1:(this.dispatch(zs(t,e)),this.notifyActiveResultChange(t,e),e)}async destroy(){for(const e of Object.keys(this.state.documents))this.stopSearchSession(e);this.searchResult$.clear(),this.searchStart$.clear(),this.searchStop$.clear(),this.searchActiveResultChange$.clear(),this.searchResultState$.clear(),this.searchState$.clear(),super.destroy()}};Ns.id="search";let Os=Ns;const Ls="search",$s={manifest:{id:Ls,name:"Search Plugin",version:"1.0.0",provides:["search"],requires:[],optional:[],defaultConfig:{flags:[]}},create:(e,t)=>new Os(Ls,e,t),reducer:(e=Es,t)=>{switch(t.type){case bs:return{...e,documents:{...e.documents,[t.payload.documentId]:t.payload.state}};case ws:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i}}case xs:return _s(e,t.payload.documentId,{active:!0});case Cs:return _s(e,t.payload.documentId,{results:[],total:0,activeResultIndex:-1,query:"",loading:!1,active:!1});case Is:return _s(e,t.payload.documentId,{flags:t.payload.flags});case ks:return _s(e,t.payload.documentId,{showAllResults:t.payload.showAll});case Ss:return _s(e,t.payload.documentId,{loading:!0,query:t.payload.query,results:[],total:0,activeResultIndex:-1});case As:{const{documentId:n,results:o}=t.payload,i=e.documents[n];if(!i)return e;const r=[...i.results,...o],a=-1===i.activeResultIndex&&r.length>0?0:i.activeResultIndex;return _s(e,n,{results:r,total:r.length,activeResultIndex:a,loading:!0})}case Ms:{const{documentId:n,results:o,total:i,activeResultIndex:r}=t.payload;return _s(e,n,{results:o,total:i,activeResultIndex:r,loading:!1})}case Ps:return _s(e,t.payload.documentId,{activeResultIndex:t.payload.index});default:return e}},initialState:Es},js=()=>_o(Os.id);function Fs({documentId:e,pageIndex:t,scale:n,style:o,highlightColor:i="#FFFF00",activeHighlightColor:r="#FFBF00",...a}){const{provides:s}=js(),[l,c]=Se(null),d=Oo(e),u=Re(()=>null==s?void 0:s.forDocument(e),[s,e]),h=Re(()=>void 0!==n?n:(null==d?void 0:d.scale)??1,[n,null==d?void 0:d.scale]);if(Ae(()=>{if(!u)return void c(null);const e=u.getState();return c({results:e.results,activeResultIndex:e.activeResultIndex,showAllResults:e.showAllResults,active:e.active}),u.onSearchResultStateChange(e=>{c(e)})},[u]),!l||!l.active)return null;return He("div",{style:{...o,pointerEvents:"none"},...a,children:l.results.map((e,t)=>({result:e,originalIndex:t})).filter(({result:e})=>e.pageIndex===t).filter(({originalIndex:e})=>l.showAllResults||e===l.activeResultIndex).map(({result:e,originalIndex:t})=>e.rects.map((e,n)=>He("div",{style:{position:"absolute",top:e.origin.y*h,left:e.origin.x*h,width:e.size.width*h,height:e.size.height*h,backgroundColor:t===l.activeResultIndex?r:i,mixBlendMode:"multiply",transform:"scale(1.02)",transformOrigin:"center",transition:"opacity .3s ease-in-out",opacity:1}},`${t}-${n}`)))})}const Us="selection",Hs={id:Us,name:"Selection Plugin",version:"1.0.0",provides:["selection"],requires:["interaction-manager"],optional:["viewport","scroll"],defaultConfig:{menuHeight:40}},Bs="SELECTION/INIT_STATE",Ws="SELECTION/CLEANUP_STATE",qs="SELECTION/CACHE_PAGE_GEOMETRY",Gs="SELECTION/SET_SELECTION",Vs="SELECTION/START_SELECTION",Ks="SELECTION/END_SELECTION",Zs="SELECTION/CLEAR_SELECTION",Ys="SELECTION/SET_RECTS",Xs="SELECTION/SET_SLICES",Qs="SELECTION/EVICT_PAGE_GEOMETRY",Js=(e,t)=>({type:Gs,payload:{documentId:e,selection:t}}),el=e=>({type:Vs,payload:{documentId:e}}),tl=e=>({type:Ks,payload:{documentId:e}}),nl=(e,t)=>({type:Ys,payload:{documentId:e,rects:t}}),ol=(e,t)=>({type:Xs,payload:{documentId:e,slices:t}}),il={geometry:{},rects:{},slices:{},selection:null,active:!1,selecting:!1},rl={documents:{}},al=(e,t,n)=>({...e,documents:{...e.documents,[t]:n}});function sl(e,t){return e.rects[t]??[]}function ll(e,t){return rt(sl(e,t))}function cl(e){const t=[],n=e.rects;for(const e in n){const o=Number(e),i=rt(n[o]);i&&t.push({page:o,rect:i})}return t}function dl(e,t){const n=e.rects[t]||[];if(0===n.length)return null;const o=ll(e,t);return o?{pageIndex:t,rect:o,segmentRects:n}:null}function ul(e){const t=[],n=Object.keys(e.rects).map(Number);for(const o of n){const n=e.rects[o]||[];if(0===n.length)continue;const i=ll(e,o);i&&t.push({pageIndex:o,rect:i,segmentRects:n})}return t}function hl(e,t,n=1.5){for(const n of e.runs){if(!(t.y>=n.rect.y&&t.y<=n.rect.y+n.rect.height&&t.x>=n.rect.x&&t.x<=n.rect.x+n.rect.width))continue;const e=n.glyphs.findIndex(e=>{const n=e.tightX??e.x,o=e.tightY??e.y,i=e.tightWidth??e.width,r=e.tightHeight??e.height;return t.x>=n&&t.x<=n+i&&t.y>=o&&t.y<=o+r});if(-1!==e)return n.charStart+e}if(n<=0)return-1;const o=function(e,t){let n=0,o=0;for(const t of e.runs)for(const e of t.glyphs)2!==e.flags&&(n+=e.height,o++);return 0===o?0:n/o*t}(e,n),i=o/2;let r=-1,a=1/0;for(const n of e.runs)if(!(t.yn.rect.y+n.rect.height+i||t.xn.rect.x+n.rect.width+i))for(let e=0;eh||t.yg)continue;const p=Math.min(Math.abs(t.x-s),Math.abs(t.x-(s+c)))+Math.min(Math.abs(t.y-l),Math.abs(t.y-(l+d)));pe.end.page)return null;const o=n===e.start.page?e.start.index:0,i=t.runs[t.runs.length-1],r=i.charStart+i.glyphs.length-1;return{from:o,to:n===e.end.page?e.end.index:r}}function gl(e,t,n,o=!0){const i=[];for(const o of e.runs){const e=o.charStart,r=e+o.glyphs.length-1;if(rn)continue;const a=Math.max(t,e)-e,s=Math.min(n,r)-e;let l=1/0,c=-1/0,d=1/0,u=-1/0,h=0,m=0,g=-1/0;const p=()=>{l!==1/0&&h>0&&i.push({rect:{origin:{x:l,y:d},size:{width:c-l,height:u-d}},charCount:h,fontSize:o.fontSize}),l=1/0,c=-1/0,d=1/0,u=-1/0,h=0,m=0,g=-1/0};for(let e=a;e<=s;e++){const t=o.glyphs[e];if(2!==t.flags){if(h>0&&g>-1/0){const e=Math.abs(t.x-g),n=m/h;n>0&&e>2.5*n&&p()}l=Math.min(l,t.x),c=Math.max(c,t.x+t.width),d=Math.min(d,t.y),u=Math.max(u,t.y+t.height),h++,m+=t.width,g=t.x+t.width}}p()}return o?function(e){const t=[];let n=null,o=null;for(const i of e)n&&o?yl(n,i)?o=pl(o,i.rect):(t.push(o),o=i.rect):o=i.rect,n=i;o&&!fl(o)&&t.push(o);return t}(i):i.map(e=>e.rect)}function pl(e,t){const n=Math.min(e.origin.x,t.origin.x),o=Math.min(e.origin.y,t.origin.y);return{origin:{x:n,y:o},size:{width:Math.max(e.origin.x+e.size.width,t.origin.x+t.size.width)-n,height:Math.max(e.origin.y+e.size.height,t.origin.y+t.size.height)-o}}}function fl(e){return e.size.width<=0||e.size.height<=0}function vl(e,t){if(fl(e)||fl(t))return 0;const n=pl(e,t);if(n.size.height===e.size.height||n.size.height===t.size.height)return 1;const o=function(e,t){const n=Math.max(e.origin.x,t.origin.x),o=Math.max(e.origin.y,t.origin.y),i=Math.min(e.origin.x+e.size.width,t.origin.x+t.size.width),r=Math.min(e.origin.y+e.size.height,t.origin.y+t.size.height);return{origin:{x:n,y:o},size:{width:Math.max(0,i-n),height:Math.max(0,r-o)}}}(e,t);return o.size.height/n.size.height}function yl(e,t){if(null!=e.fontSize&&null!=t.fontSize&&e.fontSize>0&&t.fontSize>0){if(Math.max(e.fontSize,t.fontSize)/Math.min(e.fontSize,t.fontSize)>1.5)return!1}const n=e.rect,o=t.rect;if(vl(n,o)<.8)return!1;const i=1*n.size.width/e.charCount,r=1*o.size.width/t.charCount,a=n.origin.x-i,s=n.origin.x+n.size.width+i,l=o.origin.x-r;return al}function bl(e,t){for(let n=0;n=0&&i=.5}const Il=class extends fo{constructor(e,t,n){var o,i,r;super(e,t),this.enabledModesPerDoc=new Map,this.selecting=new Map,this.anchor=new Map,this.hasTextAnchor=new Map,this.marqueePage=new Map,this.pageCallbacks=new Map,this.geoAccessOrder=new Map,this.menuPlacement$=Ao((e,t)=>({documentId:e,placement:t})),this.selChange$=Ao((e,t)=>({documentId:e,selection:t,modeId:this.interactionManagerCapability.forDocument(e).getActiveMode()})),this.textRetrieved$=Ao((e,t)=>({documentId:e,text:t})),this.copyToClipboard$=Ao((e,t)=>({documentId:e,text:t}),{cache:!1}),this.beginSelection$=Ao((e,t)=>({documentId:e,page:t.page,index:t.index,modeId:t.modeId}),{cache:!1}),this.endSelection$=Ao((e,t)=>({documentId:e,modeId:t.modeId}),{cache:!1}),this.marqueeChange$=Ao((e,t)=>({documentId:e,pageIndex:t.pageIndex,rect:t.rect,modeId:t.modeId}),{cache:!1}),this.marqueeEnd$=Ao((e,t)=>({documentId:e,pageIndex:t.pageIndex,rect:t.rect,modeId:t.modeId}),{cache:!1}),this.emptySpaceClick$=Ao((e,t)=>({documentId:e,pageIndex:t.pageIndex,modeId:t.modeId}),{cache:!1}),this.viewportCapability=null,this.scrollCapability=null,this.config=n,this.menuHeight=n.menuHeight??40;const a=t.getPlugin("interaction-manager");if(!a)throw new Error("SelectionPlugin: InteractionManagerPlugin is required.");this.interactionManagerCapability=a.provides(),this.viewportCapability=(null==(o=t.getPlugin("viewport"))?void 0:o.provides())??null,this.scrollCapability=(null==(i=t.getPlugin("scroll"))?void 0:i.provides())??null,this.coreStore.onAction(Yn,e=>{const{documentId:t,pageIndexes:n}=e.payload,o=n.map(e=>this.getNewPageGeometryAndCache(t,e));Ct.all(o).wait(()=>{n.forEach(e=>{this.notifyPage(t,e)})},En)}),null==(r=this.viewportCapability)||r.onViewportChange(e=>{this.recalculateMenuPlacement(e.documentId)},{mode:"throttle",wait:100})}onDocumentLoadingStarted(e){var t;this.dispatch(((e,t)=>({type:Bs,payload:{documentId:e,state:t}}))(e,il));const n=!1!==(null==(t=this.config.marquee)?void 0:t.enabled);this.enabledModesPerDoc.set(e,new Map([["pointerMode",{enableSelection:!0,showSelectionRects:!0,enableMarquee:n,showMarqueeRects:!0}]])),this.pageCallbacks.set(e,new Map),this.geoAccessOrder.set(e,[]),this.selecting.set(e,!1),this.anchor.set(e,void 0),this.hasTextAnchor.set(e,!1)}onDocumentClosed(e){this.dispatch((e=>({type:Ws,payload:e}))(e)),this.enabledModesPerDoc.delete(e),this.pageCallbacks.delete(e),this.geoAccessOrder.delete(e),this.selecting.delete(e),this.hasTextAnchor.delete(e),this.anchor.delete(e),this.marqueePage.delete(e),this.selChange$.clearScope(e),this.textRetrieved$.clearScope(e),this.copyToClipboard$.clearScope(e),this.beginSelection$.clearScope(e),this.endSelection$.clearScope(e),this.menuPlacement$.clearScope(e),this.marqueeChange$.clearScope(e),this.marqueeEnd$.clearScope(e),this.emptySpaceClick$.clearScope(e)}async initialize(){}async destroy(){this.selChange$.clear(),this.textRetrieved$.clear(),this.copyToClipboard$.clear(),this.beginSelection$.clear(),this.endSelection$.clear(),this.menuPlacement$.clear(),this.marqueeChange$.clear(),this.marqueeEnd$.clear(),this.emptySpaceClick$.clear(),super.destroy()}buildCapability(){const e=e=>e??this.getActiveDocumentId();return{getFormattedSelection:t=>ul(this.getDocumentState(e(t))),getFormattedSelectionForPage:(t,n)=>dl(this.getDocumentState(e(n)),t),getHighlightRectsForPage:(t,n)=>sl(this.getDocumentState(e(n)),t),getHighlightRects:t=>this.getDocumentState(e(t)).rects,getBoundingRectForPage:(t,n)=>ll(this.getDocumentState(e(n)),t),getBoundingRects:t=>cl(this.getDocumentState(e(t))),getSelectedText:t=>this.getSelectedText(e(t)),clear:t=>this.clearSelection(e(t)),copyToClipboard:t=>this.copyToClipboard(e(t)),getState:t=>this.getDocumentState(e(t)),enableForMode:(t,n,o)=>{var i;return null==(i=this.enabledModesPerDoc.get(e(o)))?void 0:i.set(t,{...n})},isEnabledForMode:(t,n)=>{var o;return(null==(o=this.enabledModesPerDoc.get(e(n)))?void 0:o.has(t))??!1},setMarqueeEnabled:(t,n)=>this.setMarqueeEnabled(e(n),t),isMarqueeEnabled:t=>this.isMarqueeEnabled(e(t)),forDocument:this.createSelectionScope.bind(this),onCopyToClipboard:this.copyToClipboard$.onGlobal,onSelectionChange:this.selChange$.onGlobal,onTextRetrieved:this.textRetrieved$.onGlobal,onBeginSelection:this.beginSelection$.onGlobal,onEndSelection:this.endSelection$.onGlobal,onMarqueeChange:this.marqueeChange$.onGlobal,onMarqueeEnd:this.marqueeEnd$.onGlobal,onEmptySpaceClick:this.emptySpaceClick$.onGlobal}}createSelectionScope(e){return{getFormattedSelection:()=>ul(this.getDocumentState(e)),getFormattedSelectionForPage:t=>dl(this.getDocumentState(e),t),getHighlightRectsForPage:t=>sl(this.getDocumentState(e),t),getHighlightRects:()=>this.getDocumentState(e).rects,getBoundingRectForPage:t=>ll(this.getDocumentState(e),t),getBoundingRects:()=>cl(this.getDocumentState(e)),getSelectedText:()=>this.getSelectedText(e),clear:()=>this.clearSelection(e),copyToClipboard:()=>this.copyToClipboard(e),getState:()=>this.getDocumentState(e),setMarqueeEnabled:t=>this.setMarqueeEnabled(e,t),isMarqueeEnabled:()=>this.isMarqueeEnabled(e),onSelectionChange:this.selChange$.forScope(e),onTextRetrieved:this.textRetrieved$.forScope(e),onCopyToClipboard:this.copyToClipboard$.forScope(e),onBeginSelection:this.beginSelection$.forScope(e),onEndSelection:this.endSelection$.forScope(e),onMarqueeChange:this.marqueeChange$.forScope(e),onMarqueeEnd:this.marqueeEnd$.forScope(e),onEmptySpaceClick:this.emptySpaceClick$.forScope(e)}}getDocumentState(e){const t=this.state.documents[e];if(!t)throw new Error(`Selection state not found for document: ${e}`);return t}onMenuPlacement(e,t){return this.menuPlacement$.forScope(e)(t)}registerSelectionOnPage(e){var t;const{documentId:n,pageIndex:o,onRectsChange:i}=e,r=this.state.documents[n];if(!r)return this.logger.warn("SelectionPlugin","RegisterFailed",`Cannot register selection on page ${o} for document ${n}: document state not initialized.`),()=>{};null==(t=this.pageCallbacks.get(n))||t.set(o,i);const a=this.getOrLoadGeometry(n,o),s=this.interactionManagerCapability.forDocument(n),l=this.enabledModesPerDoc.get(n);i({rects:sl(r,o),boundingRect:ll(r,o)}),a.wait(e=>{const t=this.getDocumentState(n),i=t.selection;if(!i||oi.end.page)return;const r=ml(i,e,o);if(!r)return;const a=gl(e,r.from,r.to);this.dispatch(nl(n,{...t.rects,[o]:a})),this.dispatch(ol(n,{...t.slices,[o]:{start:r.from,count:r.to-r.from+1}})),this.notifyPage(n,o)},En);const c=function(e){const t=e.minDragDistance??3,n=e.toleranceFactor??1.5;let o=null,i=null,r=!1,a=0;function s(){var t;o=null,i=null,r=!1,null==(t=e.setHasTextAnchor)||t.call(e,!1)}return{onPointerDown:(t,s,l)=>{var c,d;if(s.target===s.currentTarget&&(null==(c=e.onEmptySpaceClick)||c.call(e,l)),!e.isEnabled(l))return;const u=Date.now();(0===a||u-a>=500)&&e.onClear(l);const h=e.getGeometry();if(!h)return;const m=hl(h,t,n);-1!==m&&(o=m,i=t,r=!1,null==(d=e.setHasTextAnchor)||d.call(e,!0))},onPointerMove:(a,s,l)=>{if(!e.isEnabled(l))return;const c=e.getGeometry();if(!c)return;const d=hl(c,a,n);if(e.setCursor(-1!==d?"text":null),null!==o&&i&&!r){const n=a.x-i.x,s=a.y-i.y;return void(Math.sqrt(n*n+s*s)>=t&&(r=!0,e.onBegin(o,l),-1!==d&&e.onUpdate(d,l)))}e.isSelecting()&&-1!==d&&e.onUpdate(d,l)},onPointerUp:(t,n,o)=>{e.isEnabled(o)?(r&&e.onEnd(o),s()):s()},onDoubleClick:(t,o,i)=>{var r;if(!e.isEnabled(i))return;const s=e.getGeometry();if(!s)return;const l=hl(s,t,n);-1!==l&&(a=Date.now(),null==(r=e.onWordSelect)||r.call(e,l,i))},onClick:(t,o,i)=>{var r;if(!e.isEnabled(i))return;if(0===a)return;if(Date.now()-a>500)return void(a=0);a=0;const s=e.getGeometry();if(!s)return;const l=hl(s,t,n);-1!==l&&(null==(r=e.onLineSelect)||r.call(e,l,i))},onHandlerActiveEnd:t=>{s(),e.isEnabled(t)&&e.onClear(t)}}}({getGeometry:()=>this.getDocumentState(n).geometry[o],isEnabled:e=>{const t=null==l?void 0:l.get(e);return!!t&&!1!==t.enableSelection},onBegin:(e,t)=>this.beginSelection(n,o,e,t),onUpdate:(e,t)=>this.updateSelection(n,o,e,t),onEnd:e=>this.endSelection(n,e),onClear:e=>this.clearSelection(n,e),isSelecting:()=>this.selecting.get(n)??!1,setCursor:e=>e?s.setCursor("selection-text",e,10):s.removeCursor("selection-text"),onEmptySpaceClick:e=>this.emptySpaceClick$.emit(n,{pageIndex:o,modeId:e}),onWordSelect:(e,t)=>this.selectWord(n,o,e,t),onLineSelect:(e,t)=>this.selectLine(n,o,e,t),setHasTextAnchor:e=>this.hasTextAnchor.set(n,e),minDragDistance:this.config.minSelectionDragDistance,toleranceFactor:this.config.toleranceFactor}),d=this.interactionManagerCapability.registerAlways({scope:{type:"page",documentId:n,pageIndex:o},handlers:c});return()=>{var e;d(),null==(e=this.pageCallbacks.get(n))||e.delete(o),a.abort({code:Qt.Cancelled,message:"Cleanup"})}}registerMarqueeOnPage(e){var t;const{documentId:n,pageIndex:o,scale:i,onRectChange:r}=e;if(!this.state.documents[n])return this.logger.warn("SelectionPlugin","RegisterMarqueeFailed",`Cannot register marquee on page ${o} for document ${n}: document state not initialized.`),()=>{};const a=this.coreState.core.documents[n];if(!a||!a.document)return this.logger.warn("SelectionPlugin","DocumentNotFound",`Cannot register marquee on page ${o}: document not found`),()=>{};const s=a.document.pages[o];if(!s)return this.logger.warn("SelectionPlugin","PageNotFound",`Cannot register marquee on page ${o}: page not found`),()=>{};const l=s.size,c=(null==(t=this.config.marquee)?void 0:t.minDragPx)??5,d=()=>{var e;const t=this.interactionManagerCapability.forDocument(n).getActiveMode(),o=null==(e=this.enabledModesPerDoc.get(n))?void 0:e.get(t);return!1!==(null==o?void 0:o.showMarqueeRects)},u=function(e){const{pageSize:t,scale:n,minDragPx:o=5}=e;let i=null,r=null;return{onPointerDown:(t,n,o)=>{var a,s;e.isEnabled(o)&&((null==(a=e.isTextSelecting)?void 0:a.call(e))||(i=t,r={origin:{x:t.x,y:t.y},size:{width:0,height:0}},e.onBegin(t,o),null==(s=n.setPointerCapture)||s.call(n)))},onPointerMove:(n,o,a)=>{if(!i||!e.isEnabled(a))return;const s=wo(n.x,0,t.width),l=wo(n.y,0,t.height);r={origin:{x:Math.min(i.x,s),y:Math.min(i.y,l)},size:{width:Math.abs(s-i.x),height:Math.abs(l-i.y)}},e.onChange(r,a)},onPointerUp:(t,a,s)=>{var l;e.isEnabled(s)&&(r&&i&&(Math.max(r.size.width,r.size.height)*n>o?e.onEnd(r,s):e.onCancel(s)),i=null,r=null,null==(l=a.releasePointerCapture)||l.call(a))},onPointerCancel:(t,n,o)=>{var a;e.isEnabled(o)&&(i=null,r=null,e.onCancel(o),null==(a=n.releasePointerCapture)||a.call(n))}}}({pageSize:l,scale:i,minDragPx:c,isEnabled:e=>{var t;const o=null==(t=this.enabledModesPerDoc.get(n))?void 0:t.get(e);return!0===(null==o?void 0:o.enableMarquee)},isTextSelecting:()=>(this.selecting.get(n)??!1)||(this.hasTextAnchor.get(n)??!1),onBegin:(e,t)=>this.beginMarquee(n,o,e,t),onChange:(e,t)=>{this.updateMarquee(n,o,e,t),r(d()?e:null)},onEnd:(e,t)=>{this.endMarquee(n,o,e,t),r(null)},onCancel:e=>{this.cancelMarquee(n,e),r(null)}});return this.interactionManagerCapability.registerAlways({scope:{type:"page",documentId:n,pageIndex:o},handlers:u})}getPlacementMetrics(e,t,n,o){var i;const r=null==(i=this.scrollCapability)?void 0:i.forDocument(e),a=null==r?void 0:r.getRectPositionForPage(t,n);if(!a)return null;const s=a.origin.y-o.scrollTop,l=a.origin.y+a.size.height-o.scrollTop;return{pageIndex:t,rect:n,spaceAbove:s,spaceBelow:o.clientHeight-l,isBottomVisible:l>0&&l<=o.clientHeight,isTopVisible:s>=0&&sthis.menuHeight?this.emitMenuPlacement(e,{...a,suggestTop:!1,isVisible:!0}):s&&s.isTopVisible?this.emitMenuPlacement(e,{...s,suggestTop:!0,isVisible:!0}):a&&a.isBottomVisible?this.emitMenuPlacement(e,{...a,suggestTop:!1,isVisible:!0}):this.emitMenuPlacement(e,null)}notifyPage(e,t){var n,o;const i=null==(n=this.pageCallbacks.get(e))?void 0:n.get(t);if(i){const n=this.getDocumentState(e),r=this.interactionManagerCapability.forDocument(e).getActiveMode(),a=null==(o=this.enabledModesPerDoc.get(e))?void 0:o.get(r);i(a&&!1!==(a.showSelectionRects??a.showRects)?{rects:sl(n,t),boundingRect:ll(n,t)}:{rects:[],boundingRect:null})}}notifyAllPages(e){var t;null==(t=this.pageCallbacks.get(e))||t.forEach((t,n)=>{this.notifyPage(e,n)})}getNewPageGeometryAndCache(e,t){const n=this.getCoreDocument(e);if(!n||!n.document)return Jt.reject({code:Qt.NotFound,message:"Doc Not Found"});const o=n.document.pages.find(e=>e.index===t),i=this.engine.getPageGeometry(n.document,o);return i.wait(n=>{this.dispatch(((e,t,n)=>({type:qs,payload:{documentId:e,page:t,geo:n}}))(e,t,n)),this.touchGeometry(e,t)},En),i}getOrLoadGeometry(e,t){const n=this.getDocumentState(e).geometry[t];return n?(this.touchGeometry(e,t),Jt.resolve(n)):this.getNewPageGeometryAndCache(e,t)}touchGeometry(e,t){const n=this.geoAccessOrder.get(e);if(!n)return;const o=n.indexOf(t);o>-1&&n.splice(o,1),n.push(t),this.evictGeometryIfNeeded(e)}evictGeometryIfNeeded(e){const t=this.config.maxCachedGeometries??50,n=this.geoAccessOrder.get(e);if(!n||n.length<=t)return;const o=this.pageCallbacks.get(e),i=[];for(;n.length-i.length>t;){const e=n.find(e=>!i.includes(e)&&!(null==o?void 0:o.has(e)));if(void 0===e)break;i.push(e)}if(0!==i.length){for(const e of i){const t=n.indexOf(e);t>-1&&n.splice(t,1)}this.dispatch(((e,t)=>({type:Qs,payload:{documentId:e,pages:t}}))(e,i))}}beginSelection(e,t,n,o){this.selecting.set(e,!0),this.anchor.set(e,{page:t,index:n}),this.dispatch(el(e)),this.beginSelection$.emit(e,{page:t,index:n,modeId:o}),this.recalculateMenuPlacement(e)}endSelection(e,t){this.selecting.set(e,!1),this.anchor.set(e,void 0),this.dispatch(tl(e)),this.endSelection$.emit(e,{modeId:t}),this.recalculateMenuPlacement(e)}clearSelection(e,t){this.selecting.set(e,!1),this.anchor.set(e,void 0),this.dispatch((e=>({type:Zs,payload:{documentId:e}}))(e)),this.selChange$.emit(e,null),this.emitMenuPlacement(e,null),this.notifyAllPages(e)}selectWord(e,t,n,o){const i=this.getDocumentState(e).geometry[t];if(!i)return;const r=function(e,t){if(!bl(e,t))return null;const n=function(e){if(0===e.runs.length)return 0;const t=e.runs[e.runs.length-1];return t.charStart+t.glyphs.length}(e);if(0===n)return null;let o=t;for(;o>0;){const t=bl(e,o-1);if(!t)break;if(wl(e.runs[t.runIdx].glyphs[t.localIdx].flags))break;o--}let i=t;for(;i=0;t--){const n=e.runs[t];if(!xl(n)){if(!Cl(n.rect.y,n.rect.y+n.rect.height,i,r))break;a=n.charStart}}for(let t=n.runIdx+1;ti.page||t===i.page&&n>=i.index,a={start:r?i:{page:t,index:n},end:r?{page:t,index:n}:i};this.dispatch(Js(e,a)),this.updateRectsAndSlices(e,a),this.selChange$.emit(e,a);for(let t=a.start.page;t<=a.end.page;t++)this.notifyPage(e,t)}updateRectsAndSlices(e,t){const n=this.getDocumentState(e),o={},i={};for(let e=t.start.page;e<=t.end.page;e++){const r=n.geometry[e],a=ml(t,r,e);a&&(o[e]=gl(r,a.from,a.to),i[e]={start:a.from,count:a.to-a.from+1})}this.dispatch(nl(e,o)),this.dispatch(ol(e,i))}getSelectedText(e){if(!this.checkPermission(e,Zt.CopyContents))return this.logger.debug("SelectionPlugin","GetSelectedText",`Cannot get selected text: document ${e} lacks CopyContents permission`),Jt.reject({code:Qt.Security,message:"Document lacks CopyContents permission"});const t=this.getCoreDocument(e),n=this.getDocumentState(e);if(!(null==t?void 0:t.document)||!n.selection)return Jt.reject({code:Qt.NotFound,message:"Doc Not Found or No Selection"});const o=n.selection,i=[];for(let e=o.start.page;e<=o.end.page;e++){const t=n.slices[e];t&&i.push({pageIndex:e,charIndex:t.start,charCount:t.count})}if(0===i.length)return Jt.resolve([]);const r=this.engine.getTextSlices(t.document,i);return r.wait(t=>{this.textRetrieved$.emit(e,t)},En),r}copyToClipboard(e){if(!this.checkPermission(e,Zt.CopyContents))return void this.logger.debug("SelectionPlugin","CopyToClipboard",`Cannot copy to clipboard: document ${e} lacks CopyContents permission`);this.getSelectedText(e).wait(t=>{this.copyToClipboard$.emit(e,t.join("\n"))},En)}beginMarquee(e,t,n,o){this.marqueePage.set(e,t)}updateMarquee(e,t,n,o){this.marqueeChange$.emit(e,{pageIndex:t,rect:n,modeId:o})}endMarquee(e,t,n,o){this.marqueeEnd$.emit(e,{pageIndex:t,rect:n,modeId:o}),this.marqueeChange$.emit(e,{pageIndex:t,rect:null,modeId:o}),this.marqueePage.delete(e)}cancelMarquee(e,t){const n=this.marqueePage.get(e);void 0!==n&&(this.marqueeChange$.emit(e,{pageIndex:n,rect:null,modeId:t}),this.marqueePage.delete(e))}setMarqueeEnabled(e,t){const n=this.enabledModesPerDoc.get(e);if(!n)return;const o=n.get("pointerMode");o?o.enableMarquee=t:t&&n.set("pointerMode",{enableMarquee:!0})}isMarqueeEnabled(e){var t;const n=null==(t=this.enabledModesPerDoc.get(e))?void 0:t.get("pointerMode");return!1!==(null==n?void 0:n.enableMarquee)}};Il.id="selection";let kl=Il;const Sl={manifest:Hs,create:(e,t)=>new kl(Us,e,t),reducer:(e=rl,t)=>{switch(t.type){case Bs:{const{documentId:n,state:o}=t.payload;return al(e,n,o)}case Ws:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i}}case qs:{const{documentId:n,page:o,geo:i}=t.payload,r=e.documents[n];return r?al(e,n,{...r,geometry:{...r.geometry,[o]:i}}):e}case Gs:{const{documentId:n,selection:o}=t.payload,i=e.documents[n];return i?al(e,n,{...i,selection:o,active:!0}):e}case Vs:{const{documentId:n}=t.payload,o=e.documents[n];return o?al(e,n,{...o,selecting:!0,selection:null,rects:{}}):e}case Ks:{const{documentId:n}=t.payload,o=e.documents[n];return o?al(e,n,{...o,selecting:!1}):e}case Zs:{const{documentId:n}=t.payload,o=e.documents[n];return o?al(e,n,{...o,selecting:!1,selection:null,rects:{},active:!1}):e}case Ys:{const{documentId:n,rects:o}=t.payload,i=e.documents[n];return i?al(e,n,{...i,rects:o}):e}case Xs:{const{documentId:n,slices:o}=t.payload,i=e.documents[n];return i?al(e,n,{...i,slices:o}):e}case Qs:{const{documentId:n,pages:o}=t.payload,i=e.documents[n];if(!i)return e;const r={...i.geometry},a={...i.rects},s={...i.slices};for(const e of o)delete r[e],delete a[e],delete s[e];return al(e,n,{...i,geometry:r,rects:a,slices:s})}case"SELECTION/RESET":{const{documentId:n}=t.payload;return e.documents[n]?al(e,n,il):e}default:return e}},initialState:rl};const Ml="onDblClick";function Al({children:e,...t}){const{rect:n,rotation:o}=t,{matrix:i,width:r,height:a}=function(e,t){const{width:n,height:o}=e.size;switch(t%4){case 1:return{matrix:`matrix(0, -1, 1, 0, 0, ${o})`,width:o,height:n};case 2:return{matrix:`matrix(-1, 0, 0, -1, ${n}, ${o})`,width:n,height:o};case 3:return{matrix:`matrix(0, 1, -1, 0, ${n}, 0)`,width:o,height:n};default:return{matrix:"matrix(1, 0, 0, 1, 0, 0)",width:n,height:o}}}(n,o),s=De(null);Ae(()=>{const e=s.current;if(!e)return;const t=e=>{e.stopPropagation()},n=e=>{e.stopPropagation()};return e.addEventListener("pointerdown",t,{capture:!0}),e.addEventListener("touchstart",n,{capture:!0}),()=>{e.removeEventListener("pointerdown",t,{capture:!0}),e.removeEventListener("touchstart",n,{capture:!0})}},[]);return He(H,{children:e({menuWrapperProps:{style:{position:"absolute",left:n.origin.x,top:n.origin.y,transform:i,transformOrigin:"0 0",width:r,height:a,pointerEvents:"none",zIndex:3},ref:e=>{s.current=e}},matrix:i,rect:{origin:{x:n.origin.x,y:n.origin.y},size:{width:r,height:a}}})})}const Pl={n:0,ne:45,e:90,se:135,s:180,sw:225,w:270,nw:315},Dl=["ns-resize","nesw-resize","ew-resize","nwse-resize","ns-resize","nesw-resize","ew-resize","nwse-resize"];function Rl(e,t,n=0){const o=((Pl[e]+90*t+n)%360+360)%360,i=Math.round(o/45)%8;return Dl[i]}function zl(e,t,n){const o=-e/2;return"center"===n?o:"outside"===n?o-t:o+t}function Tl(e,t,n,o=!1){if(!t)return e;let{origin:{x:i,y:r},size:{width:a,height:s}}=e;const l=t.minWidth??1,c=t.minHeight??1,d=t.maxWidth,u=t.maxHeight;if(n&&a>0&&s>0){const e=a/s;ad&&(a=d,s=a/e),void 0!==u&&s>u&&(s=u,a=s*e)}else a=Math.max(l,a),s=Math.max(c,s),void 0!==d&&(a=Math.min(d,a)),void 0!==u&&(s=Math.min(u,s));return t.boundingBox&&!o&&(i=Math.max(0,Math.min(i,t.boundingBox.width-a)),r=Math.max(0,Math.min(r,t.boundingBox.height-s))),{origin:{x:i,y:r},size:{width:a,height:s}}}function El(e,t,n){const o=1e-6,i=ut(e,t);return i.origin.x>=-o&&i.origin.y>=-o&&i.origin.x+i.size.width<=n.width+o&&i.origin.y+i.size.height<=n.height+o}function _l(e,t,n,o,i){const{startRect:r,maintainAspectRatio:a=!1,annotationRotation:s=0,constraints:l}=n,c=function(e){return{x:e.includes("e")?"left":e.includes("w")?"right":"center",y:e.includes("s")?"top":e.includes("n")?"bottom":"center"}}(t),d=r.size.width/r.size.height||1;let u=function(e,t,n){let o=e.origin.x,i=e.origin.y,r=e.size.width,a=e.size.height;return"left"===n.x?r+=t.x:"right"===n.x&&(o+=t.x,r-=t.x),"top"===n.y?a+=t.y:"bottom"===n.y&&(i+=t.y,a-=t.y),{origin:{x:o,y:i},size:{width:r,height:a}}}(r,e,c);if(a&&(u=function(e,t,n,o){let{x:i,y:r}=e.origin,{width:a,height:s}=e.size;if("center"===n.x||"center"===n.y)"center"===n.y?(s=a/o,r=t.origin.y+(t.size.height-s)/2):(a=s*o,i=t.origin.x+(t.size.width-a)/2);else{const e=Math.abs(a-t.size.width),n=Math.abs(s-t.size.height),i=e+n;if(0===i)a=t.size.width,s=t.size.height;else{const t=e/i,r=n/i,l=a/o;a=t*a+r*(s*o),s=t*l+r*s}}return"right"===n.x&&(i=t.origin.x+t.size.width-a),"bottom"===n.y&&(r=t.origin.y+t.size.height-s),{origin:{x:i,y:r},size:{width:a,height:s}}}(u,r,c,d)),o&&(u=function(e,t,n,o,i){if(!o)return e;let{x:r,y:a}=e.origin,{width:s,height:l}=e.size;s=Math.max(1,s),l=Math.max(1,l);const c="left"===n.x?t.origin.x:t.origin.x+t.size.width,d="top"===n.y?t.origin.y:t.origin.y+t.size.height,u="left"===n.x?o.width-c:"right"===n.x?c:2*Math.min(t.origin.x,o.width-t.origin.x-t.size.width)+t.size.width,h="top"===n.y?o.height-d:"bottom"===n.y?d:2*Math.min(t.origin.y,o.height-t.origin.y-t.size.height)+t.size.height;if(i){const e=s>u?u/s:1,t=l>h?h/l:1,n=Math.min(e,t);n<1&&(s*=n,l*=n)}else s=Math.min(s,u),l=Math.min(l,h);return r="left"===n.x?c:"right"===n.x?c-s:t.origin.x+(t.size.width-s)/2,a="top"===n.y?d:"bottom"===n.y?d-l:t.origin.y+(t.size.height-l)/2,r=Math.max(0,Math.min(r,o.width-s)),a=Math.max(0,Math.min(a,o.height-l)),{origin:{x:r,y:a},size:{width:s,height:l}}}(u,r,c,null==l?void 0:l.boundingBox,a)),u=Tl(u,l,a,i),i&&(u=function(e,t,n){let o,i;return o="left"===n.x?t.origin.x:"right"===n.x?t.origin.x+t.size.width-e.size.width:t.origin.x+(t.size.width-e.size.width)/2,i="top"===n.y?t.origin.y:"bottom"===n.y?t.origin.y+t.size.height-e.size.height:t.origin.y+(t.size.height-e.size.height)/2,{origin:{x:o,y:i},size:e.size}}(u,r,c)),0!==s){const e=function(e,t){return{x:"left"===t.x?e.origin.x:"right"===t.x?e.origin.x+e.size.width:e.origin.x+e.size.width/2,y:"top"===t.y?e.origin.y:"bottom"===t.y?e.origin.y+e.size.height:e.origin.y+e.size.height/2}}(r,c),t={x:r.origin.x+r.size.width/2,y:r.origin.y+r.size.height/2},n={x:u.origin.x+u.size.width/2,y:u.origin.y+u.size.height/2},o=lt(e,t,s),i=lt(e,n,s);u={origin:{x:u.origin.x+(o.x-i.x),y:u.origin.y+(o.y-i.y)},size:u.size}}return u}class Nl{constructor(e,t){this.config=e,this.onUpdate=t,this.state="idle",this.startPoint=null,this.startElement=null,this.startRotationElement=null,this.gestureRotationCenter=null,this.activeHandle=null,this.currentPosition=null,this.activeVertexIndex=null,this.startVertices=[],this.currentVertices=[],this.rotationCenter=null,this.centerScreen=null,this.initialRotation=0,this.lastComputedRotation=0,this.rotationDelta=0,this.rotationSnappedAngle=null,this.currentVertices=e.vertices||[]}updateConfig(e){this.config={...this.config,...e},"vertex-editing"!==this.state&&(this.currentVertices=e.vertices||[])}startDrag(e,t){this.state="dragging",this.startPoint={x:e,y:t},this.startElement={...this.config.element},this.startRotationElement=this.config.rotationElement?{...this.config.rotationElement}:null,this.currentPosition={...this.config.element},this.onUpdate({state:"start",transformData:{type:"move",changes:{rect:this.startElement}}})}startResize(e,t,n){this.state="resizing",this.activeHandle=e,this.startPoint={x:t,y:n},this.startElement={...this.config.element},this.currentPosition={...this.config.element},this.onUpdate({state:"start",transformData:{type:"resize",changes:{rect:this.startElement},metadata:{handle:this.activeHandle,maintainAspectRatio:this.config.maintainAspectRatio}}})}startVertexEdit(e,t,n){this.currentVertices=[...this.config.vertices??this.currentVertices],e<0||e>=this.currentVertices.length||(this.state="vertex-editing",this.activeVertexIndex=e,this.startPoint={x:t,y:n},this.startVertices=[...this.currentVertices],this.gestureRotationCenter=this.config.rotationCenter??{x:this.config.element.origin.x+this.config.element.size.width/2,y:this.config.element.origin.y+this.config.element.size.height/2},this.onUpdate({state:"start",transformData:{type:"vertex-edit",changes:{vertices:this.startVertices},metadata:{vertexIndex:e}}}))}startRotation(e,t,n=0,o){this.state="rotating",this.startPoint={x:e,y:t},this.startElement={...this.config.element},this.rotationCenter=this.config.rotationCenter??{x:this.config.element.origin.x+this.config.element.size.width/2,y:this.config.element.origin.y+this.config.element.size.height/2};const{scale:i=1}=this.config,r=this.config.rotationElement??this.config.element,a=r.size.width*i,s=r.size.height*i,l=o??Math.max(a,s)/2+35,c=(n+90*(this.config.pageRotation??0))*Math.PI/180;this.centerScreen={x:e-l*Math.sin(c),y:t+l*Math.cos(c)},this.initialRotation=n,this.lastComputedRotation=n,this.rotationDelta=0,this.rotationSnappedAngle=null,this.onUpdate({state:"start",transformData:{type:"rotate",changes:{rotation:n},metadata:{rotationAngle:n,rotationDelta:0,rotationCenter:this.rotationCenter,isSnapped:!1}}})}move(e,t,n){if("idle"!==this.state&&this.startPoint)if(void 0===n||0!==n){if("dragging"===this.state&&this.startElement){const n=this.calculateDelta(e,t),o=this.calculateDragPosition(n);this.currentPosition=o,this.onUpdate({state:"move",transformData:{type:"move",changes:{rect:o}}})}else if("resizing"===this.state&&this.activeHandle&&this.startElement){const n=function(e,t,n){const{annotationRotation:o=0,constraints:i}=n,r=null==i?void 0:i.boundingBox;if(0!==o&&r){const i=_l(e,t,n,!1,!0);if(El(i,o,r))return i;let a=_l({x:0,y:0},t,n,!1,!0),s=0,l=1;for(let i=0;i<20;i+=1){const i=(s+l)/2,c=_l({x:e.x*i,y:e.y*i},t,n,!1,!0);El(c,o,r)?(a=c,s=i):l=i}return a}return _l(e,t,n,!0,!1)}(this.calculateLocalDelta(e,t),this.activeHandle,{startRect:this.startElement,maintainAspectRatio:this.config.maintainAspectRatio,annotationRotation:this.config.annotationRotation,constraints:this.config.constraints});this.currentPosition=n,this.onUpdate({state:"move",transformData:{type:"resize",changes:{rect:n},metadata:{handle:this.activeHandle,maintainAspectRatio:this.config.maintainAspectRatio}}})}else if("vertex-editing"===this.state&&null!==this.activeVertexIndex){const n=this.calculateVertexPosition(e,t);this.currentVertices=n,this.onUpdate({state:"move",transformData:{type:"vertex-edit",changes:{vertices:n},metadata:{vertexIndex:this.activeVertexIndex}}})}else if("rotating"===this.state&&this.rotationCenter){const n=this.calculateAngleFromMouse(e,t),o=this.applyRotationSnapping(n),i=at(o.angle),r=i-this.lastComputedRotation,a=r>180?r-360:r<-180?r+360:r;this.rotationDelta+=a,this.lastComputedRotation=i,this.rotationSnappedAngle=o.isSnapped?i:null,this.onUpdate({state:"move",transformData:{type:"rotate",changes:{rotation:i},metadata:{rotationAngle:i,rotationDelta:this.rotationDelta,rotationCenter:this.rotationCenter,isSnapped:o.isSnapped,snappedAngle:this.rotationSnappedAngle??void 0,cursorPosition:{clientX:e,clientY:t}}}})}}else this.end()}end(){if("idle"===this.state)return;const e=this.state,t=this.activeHandle,n=this.activeVertexIndex;if("vertex-editing"===e)this.onUpdate({state:"end",transformData:{type:"vertex-edit",changes:{vertices:this.currentVertices},metadata:{vertexIndex:n||void 0}}});else if("rotating"===e)this.onUpdate({state:"end",transformData:{type:"rotate",changes:{rotation:this.lastComputedRotation},metadata:{rotationAngle:this.lastComputedRotation,rotationDelta:this.rotationDelta,rotationCenter:this.rotationCenter||void 0,isSnapped:null!==this.rotationSnappedAngle,snappedAngle:this.rotationSnappedAngle??void 0}}});else{const n=this.currentPosition||this.config.element;this.onUpdate({state:"end",transformData:{type:"dragging"===e?"move":"resize",changes:{rect:n},metadata:"dragging"===e?void 0:{handle:t||void 0,maintainAspectRatio:this.config.maintainAspectRatio}}})}this.reset()}cancel(){"idle"!==this.state&&("vertex-editing"===this.state?this.onUpdate({state:"end",transformData:{type:"vertex-edit",changes:{vertices:this.startVertices},metadata:{vertexIndex:this.activeVertexIndex||void 0}}}):"rotating"===this.state?this.onUpdate({state:"end",transformData:{type:"rotate",changes:{rotation:this.initialRotation},metadata:{rotationAngle:this.initialRotation,rotationDelta:0,rotationCenter:this.rotationCenter||void 0,isSnapped:!1}}}):this.startElement&&this.onUpdate({state:"end",transformData:{type:"dragging"===this.state?"move":"resize",changes:{rect:this.startElement},metadata:"dragging"===this.state?void 0:{handle:this.activeHandle||void 0,maintainAspectRatio:this.config.maintainAspectRatio}}}),this.reset())}reset(){this.state="idle",this.startPoint=null,this.startElement=null,this.startRotationElement=null,this.gestureRotationCenter=null,this.activeHandle=null,this.currentPosition=null,this.activeVertexIndex=null,this.startVertices=[],this.rotationCenter=null,this.centerScreen=null,this.initialRotation=0,this.lastComputedRotation=0,this.rotationDelta=0,this.rotationSnappedAngle=null}calculateDelta(e,t){if(!this.startPoint)return{x:0,y:0};const n={x:e-this.startPoint.x,y:t-this.startPoint.y};return this.transformDelta(n)}transformDelta(e){const{pageRotation:t=0,scale:n=1}=this.config,o=t*Math.PI/2,i=Math.cos(o),r=Math.sin(o),a=e.x/n,s=e.y/n;return{x:i*a+r*s,y:-r*a+i*s}}calculateLocalDelta(e,t){const n=this.calculateDelta(e,t),{annotationRotation:o=0}=this.config;if(0===o)return n;const i=o*Math.PI/180,r=Math.cos(i),a=Math.sin(i);return{x:r*n.x+a*n.y,y:-a*n.x+r*n.y}}clampPoint(e){var t;const n=null==(t=this.config.constraints)?void 0:t.boundingBox;if(!n)return e;const{annotationRotation:o=0}=this.config;if(0===o)return{x:Math.max(0,Math.min(e.x,n.width)),y:Math.max(0,Math.min(e.y,n.height))};const i=this.gestureRotationCenter??this.config.rotationCenter??{x:this.config.element.origin.x+this.config.element.size.width/2,y:this.config.element.origin.y+this.config.element.size.height/2},r=lt(e,i,o),a=Math.max(0,Math.min(r.x,n.width)),s=Math.max(0,Math.min(r.y,n.height));return a===r.x&&s===r.y?e:lt({x:a,y:s},i,-o)}calculateVertexPosition(e,t){if(null===this.activeVertexIndex)return this.startVertices;const n=this.calculateLocalDelta(e,t),o=[...this.startVertices],i=o[this.activeVertexIndex],r={x:i.x+n.x,y:i.y+n.y};return o[this.activeVertexIndex]=this.clampPoint(r),o}calculateDragPosition(e){if(!this.startElement)return this.config.element;const t={origin:{x:this.startElement.origin.x+e.x,y:this.startElement.origin.y+e.y},size:{width:this.startElement.size.width,height:this.startElement.size.height}},{annotationRotation:n=0,constraints:o}=this.config,i=null==o?void 0:o.boundingBox;if(0!==n&&i){let e,o,r,a;if(this.startRotationElement)e=this.startRotationElement.size.width,o=this.startRotationElement.size.height,r=this.startRotationElement.origin.x-this.startElement.origin.x,a=this.startRotationElement.origin.y-this.startElement.origin.y;else{const i=Math.abs(n*Math.PI/180),s=Math.abs(Math.cos(i)),l=Math.abs(Math.sin(i)),c=t.size.width,d=t.size.height;e=c*s+d*l,o=c*l+d*s,r=(c-e)/2,a=(d-o)/2}let{x:s,y:l}=t.origin;return s=Math.max(-r,Math.min(s,i.width-e-r)),l=Math.max(-a,Math.min(l,i.height-o-a)),{origin:{x:s,y:l},size:t.size}}return Tl(t,o,this.config.maintainAspectRatio??!1)}calculateAngleFromMouse(e,t){if(!this.centerScreen)return this.initialRotation;const n=e-this.centerScreen.x,o=t-this.centerScreen.y;if(Math.sqrt(n*n+o*o)<10)return this.lastComputedRotation;const i=90*(this.config.pageRotation??0),r=Math.atan2(o,n)*(180/Math.PI)+90-i;return at(Math.round(r))}applyRotationSnapping(e){const t=this.config.rotationSnapAngles??[0,90,180,270],n=this.config.rotationSnapThreshold??4,o=at(e);for(const e of t){const t=at(e),i=Math.abs(o-t);if(Math.min(i,360-i)<=n)return{angle:t,isSnapped:!0,snapTarget:t}}return{angle:o,isSnapped:!1}}}function Ol(e){var t,n,o,i,r,a;const{controller:s,resizeUI:l,vertexUI:c,rotationUI:d,includeVertices:u=!1,includeRotation:h=!1,currentRotation:m=0,handleAttrs:g,vertexAttrs:p,rotationAttrs:f}=e,{dragProps:v,createResizeProps:y,createVertexProps:b,createRotationProps:w}=function(e){const{onUpdate:t,enabled:n=!0,...o}=e,i=De(null),r=De(t),a=De(null),s=De(null);Ae(()=>{r.current=t},[t]),Ae(()=>{i.current?i.current.updateConfig(o):i.current=new Nl(o,e=>{var t;return null==(t=r.current)?void 0:t.call(r,e)})},[o.element,o.rotationCenter,o.rotationElement,o.constraints,o.maintainAspectRatio,o.pageRotation,o.annotationRotation,o.scale,o.vertices]);const l=ze(e=>{var t,n;const o=a.current,i=s.current,r=e??o;if(i&&null!==r)try{(null==(t=i.hasPointerCapture)?void 0:t.call(i,r))&&(null==(n=i.releasePointerCapture)||n.call(i,r))}catch{}a.current=null,s.current=null},[]),c=ze(e=>{var t;null!==a.current&&a.current!==e.pointerId&&(null==(t=i.current)||t.end(),l(a.current));const n=e.currentTarget;a.current=e.pointerId,s.current=n;try{n.setPointerCapture(e.pointerId)}catch{}},[l]);Ae(()=>{const e=globalThis,t=e=>{var t;const n=a.current;null!==n&&e.pointerId===n&&(null==(t=i.current)||t.end(),l(e.pointerId))},n=()=>{var e;null!==a.current&&(null==(e=i.current)||e.end(),l())};return e.addEventListener("pointerup",t,!0),e.addEventListener("pointercancel",t,!0),e.addEventListener("blur",n,!0),()=>{e.removeEventListener("pointerup",t,!0),e.removeEventListener("pointercancel",t,!0),e.removeEventListener("blur",n,!0)}},[l]),Ae(()=>()=>{var e;null!==a.current&&(null==(e=i.current)||e.end(),l())},[l]);const d=ze(e=>{var t;n&&(e.preventDefault(),e.stopPropagation(),null==(t=i.current)||t.startDrag(e.clientX,e.clientY),c(e))},[n,c]),u=ze(e=>{var t;e.preventDefault(),e.stopPropagation();const n=a.current;null!==n&&e.pointerId!==n||(null==(t=i.current)||t.move(e.clientX,e.clientY,e.buttons),a.current===e.pointerId&&0===e.buttons&&l(e.pointerId))},[l]),h=ze(e=>{var t;e.preventDefault(),e.stopPropagation();const n=a.current;null!==n&&e.pointerId!==n||(null==(t=i.current)||t.end(),l(e.pointerId))},[l]),m=ze(e=>{var t;const n=a.current;null!==n&&e.pointerId===n&&(null==(t=i.current)||t.end(),l(e.pointerId))},[l]),g=ze(e=>({onPointerDown:t=>{var o;n&&(t.preventDefault(),t.stopPropagation(),null==(o=i.current)||o.startResize(e,t.clientX,t.clientY),c(t))},onPointerMove:u,onPointerUp:h,onPointerCancel:h,onLostPointerCapture:m}),[n,u,h,m,c]),p=ze(e=>({onPointerDown:t=>{var o;n&&(t.preventDefault(),t.stopPropagation(),null==(o=i.current)||o.startVertexEdit(e,t.clientX,t.clientY),c(t))},onPointerMove:u,onPointerUp:h,onPointerCancel:h,onLostPointerCapture:m}),[n,u,h,m,c]),f=ze((e=0,t)=>({onPointerDown:o=>{var r;if(!n)return;o.preventDefault(),o.stopPropagation();const a=o.currentTarget.getBoundingClientRect(),s=a.left+a.width/2,l=a.top+a.height/2;null==(r=i.current)||r.startRotation(s,l,e,t),c(o)},onPointerMove:u,onPointerUp:h,onPointerCancel:h,onLostPointerCapture:m}),[n,u,h,m,c]);return{dragProps:n?{onPointerDown:d,onPointerMove:u,onPointerUp:h,onPointerCancel:h,onLostPointerCapture:m}:{},createResizeProps:g,createVertexProps:p,createRotationProps:f}}(s),x=Re(()=>function(e,t={}){const{handleSize:n=8,spacing:o=1,offsetMode:i="outside",includeSides:r=!1,zIndex:a=3,rotationAwareCursor:s=!0}=t,l=(e.pageRotation??0)%4,c=e.annotationRotation??0,d=e=>({[e]:zl(n,o,i)+"px"});return[["nw",{...d("top"),...d("left")}],["ne",{...d("top"),...d("right")}],["sw",{...d("bottom"),...d("left")}],["se",{...d("bottom"),...d("right")}],...r?[["n",{...d("top"),left:`calc(50% - ${n/2}px)`}],["s",{...d("bottom"),left:`calc(50% - ${n/2}px)`}],["w",{...d("left"),top:`calc(50% - ${n/2}px)`}],["e",{...d("right"),top:`calc(50% - ${n/2}px)`}]]:[]].map(([e,t])=>({handle:e,style:{position:"absolute",width:n+"px",height:n+"px",borderRadius:"50%",zIndex:a,cursor:s?Rl(e,l,c):"default",pointerEvents:"auto",touchAction:"none",...t},attrs:{"data-epdf-handle":e}}))}(s,l).map(e=>{var t;return{key:null==(t=e.attrs)?void 0:t["data-epdf-handle"],style:e.style,...y(e.handle),...e.attrs??{},...(null==g?void 0:g(e.handle))??{}}}),[s.element.origin.x,s.element.origin.y,s.element.size.width,s.element.size.height,s.scale,s.pageRotation,s.annotationRotation,s.maintainAspectRatio,null==l?void 0:l.handleSize,null==l?void 0:l.spacing,null==l?void 0:l.offsetMode,null==l?void 0:l.includeSides,null==l?void 0:l.zIndex,null==l?void 0:l.rotationAwareCursor,y,g]),C=Re(()=>{if(!u)return[];const e=function(e,t={},n){const{vertexSize:o=12,zIndex:i=4}=t,r=e.element,a=e.scale??1;return(n??e.vertices??[]).map((e,t)=>({handle:"nw",style:{position:"absolute",left:(e.x-r.origin.x)*a-o/2+"px",top:(e.y-r.origin.y)*a-o/2+"px",width:o+"px",height:o+"px",borderRadius:"50%",cursor:"pointer",zIndex:i,pointerEvents:"auto",touchAction:"none"},attrs:{"data-epdf-vertex":t}}))}(s,c,s.vertices);return e.map((e,t)=>({key:t,style:e.style,...b(t),...e.attrs??{},...(null==p?void 0:p(t))??{}}))},[u,s.element.origin.x,s.element.origin.y,s.element.size.width,s.element.size.height,s.scale,s.vertices,null==c?void 0:c.vertexSize,null==c?void 0:c.zIndex,b,p]);return{dragProps:v,resize:x,vertices:C,rotation:Re(()=>{if(!h)return null;const e=function(e,t={},n=0){const{handleSize:o=16,zIndex:i=5,showConnector:r=!0,connectorWidth:a=1}=t,s=e.scale??1,l=e.element,c=e.rotationElement??l,d=e.rotationCenter??{x:l.origin.x+l.size.width/2,y:l.origin.y+l.size.height/2};c.size.width,c.size.height;const u=(d.x-c.origin.x)*s,h=(d.y-c.origin.y)*s,m=n*Math.PI/180,g=t.margin??35,p=l.size.height*s/2+g;return{handleStyle:{position:"absolute",left:u+p*Math.sin(m)-o/2+"px",top:h-p*Math.cos(m)-o/2+"px",width:o+"px",height:o+"px",borderRadius:"50%",cursor:"grab",zIndex:i,pointerEvents:"auto",touchAction:"none"},connectorStyle:r?{position:"absolute",left:u-a/2+"px",top:h-p+"px",width:a+"px",height:p+"px",transformOrigin:"center bottom",transform:`rotate(${n}deg)`,zIndex:i-1,pointerEvents:"none"}:{},radius:p,attrs:{"data-epdf-rotation-handle":!0}}}(s,d,m);return{handle:{style:e.handleStyle,...w(m,e.radius),...e.attrs??{},...(null==f?void 0:f())??{}},connector:{style:e.connectorStyle,"data-epdf-rotation-connector":!0}}},[h,s.element.origin.x,s.element.origin.y,s.element.size.width,s.element.size.height,null==(t=s.rotationCenter)?void 0:t.x,null==(n=s.rotationCenter)?void 0:n.y,null==(o=s.rotationElement)?void 0:o.origin.x,null==(i=s.rotationElement)?void 0:i.origin.y,null==(r=s.rotationElement)?void 0:r.size.width,null==(a=s.rotationElement)?void 0:a.size.height,s.scale,m,null==d?void 0:d.handleSize,null==d?void 0:d.margin,null==d?void 0:d.zIndex,null==d?void 0:d.showConnector,null==d?void 0:d.connectorWidth,w,f])}}const Ll=()=>_o(kl.id),$l=()=>Eo(kl.id);function jl({documentId:e,pageIndex:t,scale:n,rotation:o,background:i="rgba(33,150,243)",selectionMenu:r}){var a,s;const{plugin:l}=$l(),c=Oo(e),d=null==(s=null==(a=null==c?void 0:c.document)?void 0:a.pages)?void 0:s[t],[u,h]=Se([]),[m,g]=Se(null),[p,f]=Se(null);Ae(()=>{if(l&&e)return l.registerSelectionOnPage({documentId:e,pageIndex:t,onRectsChange:({rects:e,boundingRect:t})=>{h(e),g(t)}})},[l,e,t]),Ae(()=>{if(l&&e)return l.onMenuPlacement(e,e=>{f(e)})},[l,e]);const v=Re(()=>void 0!==n?n:(null==c?void 0:c.scale)??1,[n,null==c?void 0:c.scale]),y=Re(()=>{if(void 0!==o)return o;return(((null==d?void 0:d.rotation)??0)+((null==c?void 0:c.rotation)??0))%4},[o,null==d?void 0:d.rotation,null==c?void 0:c.rotation]),b=r&&p&&p.pageIndex===t&&p.isVisible;return m?He(H,{children:[He("div",{style:{position:"absolute",left:m.origin.x*v,top:m.origin.y*v,width:m.size.width*v,height:m.size.height*v,mixBlendMode:"multiply",isolation:"isolate",pointerEvents:"none"},children:u.map((e,t)=>He("div",{style:{position:"absolute",left:(e.origin.x-m.origin.x)*v,top:(e.origin.y-m.origin.y)*v,width:e.size.width*v,height:e.size.height*v,background:i}},t))}),b&&He(Al,{rect:{origin:{x:p.rect.origin.x*v,y:p.rect.origin.y*v},size:{width:p.rect.size.width*v,height:p.rect.size.height*v}},rotation:y,children:e=>r({...e,context:{type:"selection",pageIndex:t},selected:!0,placement:p})})]}):null}const Fl=({documentId:e,pageIndex:t,scale:n,className:o,background:i,borderColor:r,borderStyle:a="dashed",stroke:s,fill:l})=>{const{plugin:c}=$l(),d=Oo(e),[u,h]=Se(null),m=r??s??"rgba(0,122,204,0.8)",g=i??l??"rgba(0,122,204,0.15)",p=Re(()=>void 0!==n?n:(null==d?void 0:d.scale)??1,[n,null==d?void 0:d.scale]);return Ae(()=>{if(c&&e)return c.registerMarqueeOnPage({documentId:e,pageIndex:t,scale:p,onRectChange:h})},[c,e,t,p]),u?He("div",{style:{position:"absolute",pointerEvents:"none",left:u.origin.x*p,top:u.origin.y*p,width:u.size.width*p,height:u.size.height*p,border:`1px ${a} ${m}`,background:g,boxSizing:"border-box",zIndex:1e3},className:o}):null};function Ul({documentId:e,pageIndex:t,scale:n,rotation:o,background:i,textStyle:r,marqueeStyle:a,marqueeClassName:s,selectionMenu:l}){return He(H,{children:[He(jl,{documentId:e,pageIndex:t,scale:n,rotation:o,background:(null==r?void 0:r.background)??i,selectionMenu:l}),He(Fl,{documentId:e,pageIndex:t,scale:n,background:null==a?void 0:a.background,borderColor:null==a?void 0:a.borderColor,borderStyle:null==a?void 0:a.borderStyle,className:s})]})}const Hl=Do(Sl).addUtility(function(){const{provides:e}=Ll();return Ae(()=>{if(e)return e.onCopyToClipboard(({text:e})=>{navigator.clipboard.writeText(e)})},[e]),null}).build(),Bl="tiling",Wl={id:Bl,name:"Tiling Plugin",version:"1.0.0",provides:["tiling"],requires:["render","scroll","viewport"],optional:[],defaultConfig:{tileSize:768,overlapPx:2.5,extraRings:0}},ql="TILING/INIT_STATE",Gl="TILING/CLEANUP_STATE",Vl="TILING/UPDATE_VISIBLE_TILES",Kl="TILING/MARK_TILE_STATUS",Zl=(e,t)=>({type:Vl,payload:{documentId:e,tiles:t}}),Yl=(e,t,n,o)=>({type:Kl,payload:{documentId:e,pageIndex:t,tileId:n,status:o}}),Xl={visibleTiles:{}};function Ql({tileSize:e=768,overlapPx:t=2.5,extraRings:n=0,scale:o,rotation:i,page:r,metric:a}){const s=r.size.width*o,l=r.size.height*o,c=e-t,d=function(e,t,n,o){return nt(tt(e,t,(4-n)%4),1/o)}(Ke(r.size,i,o),{origin:{x:a.scaled.pageX,y:a.scaled.pageY},size:{width:a.scaled.visibleWidth,height:a.scaled.visibleHeight}},i,1),u=d.origin.x,h=d.origin.y,m=u+d.size.width,g=h+d.size.height,p=Math.floor((s-1)/c),f=Math.floor((l-1)/c),v=Math.max(0,Math.floor(u/c)-n),y=Math.min(p,Math.floor((m-1)/c)+n),b=Math.max(0,Math.floor(h/c)-n),w=Math.min(f,Math.floor((g-1)/c)+n),x=[];for(let t=v;t<=y;t++){const n=t*c,i=Math.min(e,s-n),a=n/o,d=i/o;for(let s=b;s<=w;s++){const u=s*c,h=Math.min(e,l-u),m=u/o,g=h/o;x.push({id:`p${r.index}-${o}-x${n}-y${u}-w${i}-h${h}`,col:t,row:s,pageRect:{origin:{x:a,y:m},size:{width:d,height:g}},screenRect:{origin:{x:n,y:u},size:{width:i,height:h}},status:"queued",srcScale:o,isFallback:!1})}}return x}const Jl=class extends fo{constructor(e,t,n){super(e,t),this.tileRendering$=Mo(),this.config=n,this.renderCapability=this.registry.getPlugin("render").provides(),this.scrollCapability=this.registry.getPlugin("scroll").provides(),this.viewportCapability=this.registry.getPlugin("viewport").provides(),this.scrollCapability.onScroll(e=>this.calculateVisibleTiles(e.documentId,e.metrics),{mode:"throttle",wait:50,throttleMode:"trailing"}),this.coreStore.onAction(Yn,e=>this.recalculateTiles(e.payload))}onDocumentLoadingStarted(e){this.dispatch(((e,t)=>({type:ql,payload:{documentId:e,state:t}}))(e,Xl))}onDocumentClosed(e){this.dispatch((e=>({type:Gl,payload:e}))(e))}onScaleChanged(e){this.recalculateTilesForDocument(e)}onRotationChanged(e){this.recalculateTilesForDocument(e)}recalculateTilesForDocument(e){const t=this.scrollCapability.forDocument(e),n=this.viewportCapability.forDocument(e),o=t.getMetrics(n.getMetrics());this.calculateVisibleTiles(e,o)}async recalculateTiles(e){const{documentId:t,pageIndexes:n}=e,o=this.getCoreDocument(t);if(!o||!o.document)return;const i=this.scrollCapability.forDocument(t),r=this.viewportCapability.forDocument(t),a=i.getMetrics(r.getMetrics()),s={},l=Date.now(),c=o.scale;for(const e of n){const t=a.pageVisibilityMetrics.find(t=>t.pageNumber===e+1);if(!t)continue;const n=o.document.pages[e];if(!n)continue;const i=((n.rotation??0)+o.rotation)%4;s[e]=Ql({page:n,metric:t,scale:c,rotation:i,tileSize:this.config.tileSize,overlapPx:this.config.overlapPx,extraRings:this.config.extraRings}).map(e=>({...e,id:`${e.id}-r${l}`}))}Object.keys(s).length>0&&this.dispatch(Zl(t,s))}async initialize(){}calculateVisibleTiles(e,t){const n=this.getCoreDocument(e);if(!n||!n.document)return;const o=n.scale,i={};for(const e of t.pageVisibilityMetrics){const t=e.pageNumber-1,r=n.document.pages[t];if(!r)continue;const a=Ql({page:r,metric:e,scale:o,rotation:((r.rotation??0)+n.rotation)%4,tileSize:this.config.tileSize,overlapPx:this.config.overlapPx,extraRings:this.config.extraRings});i[t]=a}this.dispatch(Zl(e,i))}onStoreUpdated(e,t){for(const n in t.documents){const o=e.documents[n],i=t.documents[n];o!==i&&this.tileRendering$.emit({documentId:n,tiles:i.visibleTiles})}}buildCapability(){return{renderTile:this.renderTile.bind(this),forDocument:this.createTilingScope.bind(this),onTileRendering:this.tileRendering$.on}}createTilingScope(e){return{renderTile:t=>this.renderTile(t,e),onTileRendering:t=>this.tileRendering$.on(n=>{n.documentId===e&&t(n.tiles)})}}renderTile(e,t){const n=t??this.getActiveDocumentId();if(!this.renderCapability)throw new Error("Render capability not available.");this.dispatch(Yl(n,e.pageIndex,e.tile.id,"rendering"));const o=this.renderCapability.forDocument(n).renderPageRect({pageIndex:e.pageIndex,rect:e.tile.pageRect,options:{scaleFactor:e.tile.srcScale,dpr:e.dpr}});return o.wait(()=>{this.dispatch(Yl(n,e.pageIndex,e.tile.id,"ready"))},En),o}};Jl.id="tiling";let ec=Jl;const tc={manifest:Wl,create:(e,t)=>new ec(Bl,e,t),reducer:(e,t)=>((e,t)=>{var n,o;switch(t.type){case ql:{const{documentId:n,state:o}=t.payload;return{...e,documents:{...e.documents,[n]:o}}}case Gl:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i}}case Vl:{const{documentId:o,tiles:i}=t.payload,r=e.documents[o];if(!r)return e;const a={...r.visibleTiles};for(const e in i){const t=Number(e),o=i[t],r=a[t]??[],s=null==(n=r.find(e=>!e.isFallback))?void 0:n.srcScale,l=o.length>0?o[0].srcScale:s;if(void 0!==s&&s!==l){const e=r.filter(e=>!e.isFallback&&"ready"===e.status).map(e=>({...e,isFallback:!0})),n=e.length>0?[]:r.filter(e=>e.isFallback);a[t]=[...n,...e,...o]}else{const e=new Set(o.map(e=>e.id)),n=[],i=new Set;for(const t of r)(t.isFallback||e.has(t.id))&&(n.push(t),i.add(t.id));for(const e of o)i.has(e.id)||n.push(e);a[t]=n}}return{...e,documents:{...e.documents,[o]:{...r,visibleTiles:a}}}}case Kl:{const{documentId:n,pageIndex:i,tileId:r,status:a}=t.payload,s=e.documents[n];if(!s)return e;const l=(null==(o=s.visibleTiles[i])?void 0:o.map(e=>e.id===r?{...e,status:a}:e))??[],c=l.filter(e=>!e.isFallback),d=c.length>0&&c.every(e=>"ready"===e.status),u=d?c:l;return{...e,documents:{...e.documents,[n]:{...s,visibleTiles:{...s.visibleTiles,[i]:u}}}}}default:return e}})(e,t),initialState:{documents:{}}},nc=()=>_o(ec.id);function oc({documentId:e,pageIndex:t,tile:n,dpr:o,scale:i}){const{provides:r}=nc(),a=Re(()=>null==r?void 0:r.forDocument(e),[r,e]),[s,l]=Se(),c=De(null),d=i/n.srcScale;Ae(()=>{if("ready"===n.status&&c.current)return;if(!a)return;const e=a.renderTile({pageIndex:t,tile:n,dpr:o});return e.wait(e=>{const t=URL.createObjectURL(e);c.current=t,l(t)},En),()=>{c.current?(URL.revokeObjectURL(c.current),c.current=null):e.abort({code:Qt.Cancelled,message:"canceled render task"})}},[a,t,n.id]);return s?He("img",{src:s,onLoad:()=>{c.current&&(URL.revokeObjectURL(c.current),c.current=null)},style:{position:"absolute",left:n.screenRect.origin.x*d,top:n.screenRect.origin.y*d,width:n.screenRect.size.width*d,height:n.screenRect.size.height*d,display:"block"}}):null}function ic({documentId:e,pageIndex:t,scale:n,style:o,...i}){const{provides:r}=nc(),a=Oo(e),[s,l]=Se([]);Ae(()=>{if(r)return r.onTileRendering(n=>{n.documentId===e&&l(n.tiles[t]??[])})},[r,e,t]);const c=Re(()=>void 0!==n?n:(null==a?void 0:a.scale)??1,[n,null==a?void 0:a.scale]);return He("div",{style:{...o},...i,children:null==s?void 0:s.map(n=>He(oc,{documentId:e,pageIndex:t,tile:n,dpr:window.devicePixelRatio,scale:c},n.id))})}const rc="thumbnail",ac={id:rc,name:"Thumbnail Plugin",version:"1.0.0",provides:["thumbnail"],requires:["render"],optional:["scroll"],defaultConfig:{width:150,gap:10,buffer:3,labelHeight:16,autoScroll:!0,scrollBehavior:"smooth",imagePadding:0,paddingY:0}},sc="THUMBNAIL/INIT_STATE",lc="THUMBNAIL/CLEANUP_STATE",cc="THUMBNAIL/SET_WINDOW_STATE",dc="THUMBNAIL/UPDATE_VIEWPORT_METRICS";function uc(e,t){return{type:sc,payload:{documentId:e,state:t}}}const hc={thumbs:[],window:null,viewportH:0,scrollY:0},mc={documents:{},activeDocumentId:null},gc=class extends fo{constructor(e,t,n){var o;super(e,t),this.cfg=n,this.scrollCapability=null,this.taskCaches=new Map,this.canAutoScroll=new Map,this.window$=Ao((e,t)=>({documentId:e,window:t})),this.scrollTo$=Ao((e,t)=>({documentId:e,options:t})),this.refreshPages$=Ao((e,t)=>({documentId:e,pages:t}),{cache:!1}),this.renderCapability=this.registry.getPlugin("render").provides(),this.scrollCapability=(null==(o=this.registry.getPlugin("scroll"))?void 0:o.provides())??null,this.coreStore.onAction(Yn,e=>{const t=e.payload.documentId??this.getActiveDocumentId(),n=e.payload.pageIndexes;this.refreshPages$.emit(t,n);const o=this.taskCaches.get(t);if(o)for(const e of n)o.delete(e)}),this.scrollCapability&&!1!==this.cfg.autoScroll&&(this.scrollCapability.onPageChangeState(({documentId:e,state:t})=>{this.canAutoScroll.set(e,!t.isChanging),t.isChanging||this.scrollToThumb(t.targetPage-1,e)}),this.scrollCapability.onPageChange(({documentId:e,pageNumber:t})=>{!1!==this.canAutoScroll.get(e)&&this.scrollToThumb(t-1,e)}))}onDocumentLoadingStarted(e){this.dispatch(uc(e,{...hc})),this.taskCaches.set(e,new Map),this.canAutoScroll.set(e,!0),this.logger.debug("ThumbnailPlugin","DocumentOpened",`Initialized thumbnail state for document: ${e}`)}onDocumentLoaded(e){this.calculateWindowState(e)}onDocumentClosed(e){this.dispatch(function(e){return{type:lc,payload:e}}(e));const t=this.taskCaches.get(e);t&&(t.forEach(e=>{e.abort({code:"cancelled",message:"Document closed"})}),t.clear(),this.taskCaches.delete(e)),this.canAutoScroll.delete(e),this.window$.clearScope(e),this.scrollTo$.clearScope(e),this.refreshPages$.clearScope(e),this.logger.debug("ThumbnailPlugin","DocumentClosed",`Cleaned up thumbnail state for document: ${e}`)}onRotationChanged(e){this.calculateWindowState(e)}buildCapability(){return{scrollToThumb:e=>this.scrollToThumb(e),renderThumb:(e,t)=>this.renderThumb(e,t),updateWindow:(e,t)=>this.updateWindow(e,t),getWindow:()=>this.getWindow(),forDocument:e=>this.createThumbnailScope(e),onWindow:this.window$.onGlobal,onScrollTo:this.scrollTo$.onGlobal,onRefreshPages:this.refreshPages$.onGlobal}}createThumbnailScope(e){return{scrollToThumb:t=>this.scrollToThumb(t,e),renderThumb:(t,n)=>this.renderThumb(t,n,e),updateWindow:(t,n)=>this.updateWindow(t,n,e),getWindow:()=>this.getWindow(e),onWindow:this.window$.forScope(e),onScrollTo:this.scrollTo$.forScope(e),onRefreshPages:this.refreshPages$.forScope(e)}}getDocumentState(e){const t=e??this.getActiveDocumentId();return this.state.documents[t]??null}calculateWindowState(e){const t=this.coreState.core.documents[e];if(!(null==t?void 0:t.document))return;const n=this.cfg.width??120,o=this.cfg.labelHeight??16,i=this.cfg.gap??8,r=this.cfg.imagePadding??0,a=this.cfg.paddingY??0,s=Math.max(1,n-2*r);let l=a;const c=t.document.pages.map(e=>{const t=e.rotation%2==1,n=t?e.size.height:e.size.width,a=(t?e.size.width:e.size.height)/n,c=Math.round(s*a),d=r+c+r+o,u={pageIndex:e.index,width:s,height:c,wrapperHeight:d,top:l,labelHeight:o,padding:r};return l+=d+i,u}),d={start:-1,end:-1,items:[],totalHeight:l-i+a},u=this.getDocumentState(e);u&&(this.dispatch(uc(e,{...u,thumbs:c,window:d})),u.viewportH>0?this.updateWindow(u.scrollY,u.viewportH,e):this.window$.emit(e,d))}updateWindow(e,t,n){const o=n??this.getActiveDocumentId(),i=this.getDocumentState(o);if(!i||!i.window||0===i.thumbs.length)return;const r=this.cfg.buffer??3;this.dispatch(function(e,t,n){return{type:dc,payload:{documentId:e,scrollY:t,viewportH:n}}}(o,e,t));let a=0,s=i.thumbs.length-1,l=0;for(;a<=s;){const t=a+s>>1,n=i.thumbs[t];n.top+n.wrapperHeighto.scrollY+o.viewportH-8;c?this.scrollTo$.emit(n,{top:Math.max(0,s-a),behavior:r}):d&&this.scrollTo$.emit(n,{top:Math.max(0,l-o.viewportH+a),behavior:r})}renderThumb(e,t,n){const o=n??this.getActiveDocumentId(),i=this.taskCaches.get(o);if(!i)throw new Error(`Task cache not found for document: ${o}`);if(i.has(e))return i.get(e);const r=this.coreState.core.documents[o];if(!(null==r?void 0:r.document))throw new Error(`Document not found: ${o}`);const a=r.document.pages[e];if(!a)throw new Error(`Page ${e} not found in document: ${o}`);const s=this.cfg.width??120,l=this.cfg.imagePadding??0,c=Math.max(1,s-2*l)/a.size.width,d=this.renderCapability.forDocument(o).renderPageRect({pageIndex:e,rect:{origin:{x:0,y:0},size:a.size},options:{scaleFactor:c,dpr:t,rotation:a.rotation}});return i.set(e,d),d.wait(En,()=>i.delete(e)),d}async initialize(){this.logger.info("ThumbnailPlugin","Initialize","Thumbnail plugin initialized")}async destroy(){this.window$.clear(),this.refreshPages$.clear(),this.scrollTo$.clear(),this.taskCaches.forEach(e=>{e.forEach(e=>{e.abort({code:"cancelled",message:"Plugin destroyed"})}),e.clear()}),this.taskCaches.clear(),this.canAutoScroll.clear(),super.destroy()}};gc.id="thumbnail";let pc=gc;const fc={manifest:ac,create:(e,t)=>new pc(rc,e,t),reducer:(e=mc,t)=>{switch(t.type){case sc:{const{documentId:n,state:o}=t.payload;return{...e,documents:{...e.documents,[n]:o},activeDocumentId:e.activeDocumentId??n}}case lc:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i,activeDocumentId:e.activeDocumentId===n?null:e.activeDocumentId}}case"THUMBNAIL/SET_ACTIVE_DOCUMENT":return{...e,activeDocumentId:t.payload};case cc:{const{documentId:n,window:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,window:o}}}:e}case dc:{const{documentId:n,scrollY:o,viewportH:i}=t.payload,r=e.documents[n];return r?{...e,documents:{...e.documents,[n]:{...r,scrollY:o,viewportH:i}}}:e}default:return e}},initialState:mc},vc=()=>Eo(pc.id);function yc({documentId:e,style:t,children:n,...o}){const{plugin:i}=vc(),r=De(null),[a,s]=Se({window:null,docId:null}),l=a.docId===e?a.window:null;Ae(()=>{if(!i)return;const t=i.provides().forDocument(e),n=t.getWindow();n&&s({window:n,docId:e});const o=t.onWindow(t=>{s({window:t,docId:e})});return()=>{o(),s({window:null,docId:null})}},[i,e]),Ae(()=>{const t=r.current;if(!t||!i)return;const n=i.provides().forDocument(e),o=()=>n.updateWindow(t.scrollTop,t.clientHeight);return t.addEventListener("scroll",o),()=>t.removeEventListener("scroll",o)},[i,e]),Ae(()=>{const t=r.current;if(!t||!i)return;const n=i.provides().forDocument(e),o=new ResizeObserver(()=>{n.updateWindow(t.scrollTop,t.clientHeight)});return o.observe(t),()=>o.disconnect()},[i,e]),Ae(()=>{const t=r.current;if(!t||!i)return;i.provides().forDocument(e).updateWindow(t.scrollTop,t.clientHeight)},[l,i,e]),Ae(()=>{const t=r.current;if(!t||!i||!l)return;return i.provides().forDocument(e).onScrollTo(({top:e,behavior:n})=>{t.scrollTo({top:e,behavior:n})})},[i,e,!!l]);const c=(null==i?void 0:i.cfg.paddingY)??0;return He("div",{ref:r,style:{overflowY:"auto",position:"relative",paddingTop:c,paddingBottom:c,height:"100%",...t},...o,children:He("div",{style:{height:(null==l?void 0:l.totalHeight)??0,position:"relative"},children:null==l?void 0:l.items.map(e=>n(e))})})}function bc({documentId:e,meta:t,style:n,...o}){const{provides:i}=_o(pc.id),{plugin:r}=vc(),[a,s]=Se(),l=De(null),[c,d]=Se(0);Ae(()=>{if(!r)return;return r.provides().forDocument(e).onRefreshPages(e=>{e.includes(t.pageIndex)&&d(e=>e+1)})},[r,e,t.pageIndex]),Ae(()=>{const n=null==i?void 0:i.forDocument(e),o=null==n?void 0:n.renderThumb(t.pageIndex,window.devicePixelRatio);return null==o||o.wait(e=>{const t=URL.createObjectURL(e);l.current=t,s(t)},En),()=>{l.current?(URL.revokeObjectURL(l.current),l.current=null):null==o||o.abort({code:Qt.Cancelled,message:"canceled render task"})}},[i,e,t.pageIndex,c]);return a?He("img",{src:a,onLoad:()=>{l.current&&(URL.revokeObjectURL(l.current),l.current=null)},style:n,...o}):null}const wc="annotation",xc={id:wc,name:"Annotation Plugin",version:"1.0.0",provides:["annotation"],requires:["interaction-manager","selection"],optional:["history"],defaultConfig:{autoCommit:!0,annotationAuthor:"Guest",deactivateToolAfterCreate:!1,selectAfterCreate:!0}},Cc="ANNOTATION/INIT_STATE",Ic="ANNOTATION/CLEANUP_STATE",kc="ANNOTATION/SET_ANNOTATIONS",Sc="ANNOTATION/SELECT_ANNOTATION",Mc="ANNOTATION/DESELECT_ANNOTATION",Ac="ANNOTATION/ADD_TO_SELECTION",Pc="ANNOTATION/REMOVE_FROM_SELECTION",Dc="ANNOTATION/SET_SELECTION",Rc="ANNOTATION/SET_ACTIVE_TOOL_ID",zc="ANNOTATION/CREATE_ANNOTATION",Tc="ANNOTATION/PATCH_ANNOTATION",Ec="ANNOTATION/DELETE_ANNOTATION",_c="ANNOTATION/COMMIT",Nc="ANNOTATION/PURGE_ANNOTATION",Oc="ANNOTATION/ADD_COLOR_PRESET",Lc="ANNOTATION/SET_TOOL_DEFAULTS",$c="ANNOTATION/ADD_TOOL";const jc=e=>({type:Mc,payload:{documentId:e}}),Fc=(e,t,n)=>({type:Ac,payload:{documentId:e,pageIndex:t,id:n}}),Uc=(e,t)=>({type:Pc,payload:{documentId:e,id:t}}),Hc=(e,t)=>({type:Dc,payload:{documentId:e,ids:t}}),Bc=(e,t)=>({type:Rc,payload:{documentId:e,toolId:t}}),Wc=(e,t,n)=>({type:zc,payload:{documentId:e,pageIndex:t,annotation:n}}),qc=(e,t,n,o)=>({type:Tc,payload:{documentId:e,pageIndex:t,id:n,patch:o}}),Gc=(e,t,n)=>({type:Ec,payload:{documentId:e,pageIndex:t,id:n}}),Vc=(e,t,n)=>({type:Nc,payload:{documentId:e,pageIndex:t,uid:n}});function Kc(e){return e.object.type===_t.INK}function Zc(e){return e.object.type===_t.CIRCLE}function Yc(e){return e.object.type===_t.POLYGON}function Xc(e){return e.object.type===_t.SQUARE}function Qc(e){return e.object.type===_t.LINE}function Jc(e){return e.object.type===_t.POLYLINE}function ed(e){return e.object.type===_t.HIGHLIGHT}function td(e){return e.object.type===_t.UNDERLINE}function nd(e){return e.object.type===_t.STRIKEOUT}function od(e){return e.object.type===_t.SQUIGGLY}function id(e){return e.object.type===_t.FREETEXT}function rd(e){return e.object.type===_t.STAMP}function ad(e){return e.object.type===_t.TEXT}function sd(e){return e.object.type===_t.LINK}function ld(e){return function(e){return ed(e)||td(e)||nd(e)||od(e)}(e)||Kc(e)||Xc(e)||Zc(e)||Yc(e)||Qc(e)||Jc(e)||id(e)||rd(e)||function(e){return e.object.type===_t.REDACT}(e)}const cd=(e,t)=>(e.pages[t]??[]).map(t=>e.byUid[t]),dd=e=>e.selectedUids.map(t=>e.byUid[t]).filter(e=>void 0!==e),ud=e=>e.selectedUids,hd=(e,t)=>e.byUid[t]??null;function md(e,t){const n=e.tools.find(e=>e.id===t);return null==n?void 0:n.defaults}const gd=(e,t)=>((e,t,n)=>{const o=[];for(const i of Object.values(e.pages))for(const r of i){const i=e.byUid[r];i&&"inReplyToId"in i.object&&i.object.inReplyToId===t&&n.includes(i.object.type)&&o.push(i)}return o})(e,t,[_t.LINK]),pd=(e,t)=>{const n=((e,t)=>{const n=e.byUid[t];if(n)return n.object.inReplyToId&&n.object.replyType===$t.Group?n.object.inReplyToId:t})(e,t);if(!n)return[];const o=[],i=e.byUid[n];i&&i.object.type!==_t.LINK&&o.push(i);for(const t of Object.values(e.pages))for(const i of t){const t=e.byUid[i];t&&t.object.inReplyToId===n&&t.object.replyType===$t.Group&&t.object.type!==_t.LINK&&o.push(t)}return o},fd=(e,t)=>{const n=e.byUid[t];if(!n)return!1;if(n.object.type===_t.LINK)return!1;if(n.object.inReplyToId&&n.object.replyType===$t.Group)return!0;for(const n of Object.values(e.pages))for(const o of n){const n=e.byUid[o];if(n&&n.object.inReplyToId===t&&n.object.replyType===$t.Group&&n.object.type!==_t.LINK)return!0}return!1},vd=[{id:"highlight",name:"Highlight",matchScore:e=>e.type===_t.HIGHLIGHT?1:0,interaction:{exclusive:!1,textSelection:!0,isDraggable:!1,isResizable:!1,isGroupDraggable:!1,isGroupResizable:!1},defaults:{type:_t.HIGHLIGHT,strokeColor:"#FFCD45",color:"#FFCD45",opacity:1,blendMode:zt.Multiply}},{id:"underline",name:"Underline",matchScore:e=>e.type===_t.UNDERLINE?1:0,interaction:{exclusive:!1,textSelection:!0,isDraggable:!1,isResizable:!1,isGroupDraggable:!1,isGroupResizable:!1},defaults:{type:_t.UNDERLINE,strokeColor:"#E44234",color:"#E44234",opacity:1}},{id:"strikeout",name:"Strikeout",matchScore:e=>e.type===_t.STRIKEOUT?1:0,interaction:{exclusive:!1,textSelection:!0,isDraggable:!1,isResizable:!1,isGroupDraggable:!1,isGroupResizable:!1},defaults:{type:_t.STRIKEOUT,strokeColor:"#E44234",color:"#E44234",opacity:1}},{id:"squiggly",name:"Squiggly",matchScore:e=>e.type===_t.SQUIGGLY?1:0,interaction:{exclusive:!1,textSelection:!0,isDraggable:!1,isResizable:!1,isGroupDraggable:!1,isGroupResizable:!1},defaults:{type:_t.SQUIGGLY,strokeColor:"#E44234",color:"#E44234",opacity:1}},{id:"ink",name:"Pen",matchScore:e=>e.type===_t.INK&&"InkHighlight"!==e.intent?5:0,interaction:{exclusive:!1,cursor:"crosshair",isDraggable:!0,isResizable:!0,lockAspectRatio:!1},defaults:{type:_t.INK,strokeColor:"#E44234",color:"#E44234",opacity:1,strokeWidth:6}},{id:"inkHighlighter",name:"Ink Highlighter",matchScore:e=>e.type===_t.INK&&"InkHighlight"===e.intent?10:0,interaction:{exclusive:!1,cursor:"crosshair",isDraggable:!0,isResizable:!0,lockAspectRatio:!1,lockGroupAspectRatio:e=>{const t=((e.rotation??0)%90+90)%90;return t>=6&&t<=84}},defaults:{type:_t.INK,intent:"InkHighlight",strokeColor:"#FFCD45",color:"#FFCD45",opacity:1,strokeWidth:14,blendMode:zt.Multiply}},{id:"circle",name:"Circle",matchScore:e=>e.type===_t.CIRCLE?1:0,interaction:{exclusive:!1,cursor:"crosshair",isDraggable:!0,isResizable:!0,lockAspectRatio:!1,lockGroupAspectRatio:e=>{const t=((e.rotation??0)%90+90)%90;return t>=6&&t<=84}},defaults:{type:_t.CIRCLE,color:"transparent",opacity:1,strokeWidth:6,strokeColor:"#E44234",strokeStyle:Ut.SOLID},clickBehavior:{enabled:!0,defaultSize:{width:100,height:100}}},{id:"square",name:"Square",matchScore:e=>e.type===_t.SQUARE?1:0,interaction:{exclusive:!1,cursor:"crosshair",isDraggable:!0,isResizable:!0,lockAspectRatio:!1,lockGroupAspectRatio:e=>{const t=((e.rotation??0)%90+90)%90;return t>=6&&t<=84}},defaults:{type:_t.SQUARE,color:"transparent",opacity:1,strokeWidth:6,strokeColor:"#E44234",strokeStyle:Ut.SOLID},clickBehavior:{enabled:!0,defaultSize:{width:100,height:100}}},{id:"line",name:"Line",matchScore:e=>e.type===_t.LINE&&"LineArrow"!==e.intent?5:0,interaction:{exclusive:!1,cursor:"crosshair",isDraggable:!0,isResizable:!1,lockAspectRatio:!1,isGroupResizable:!0,lockGroupAspectRatio:e=>{const t=((e.rotation??0)%90+90)%90;return t>=6&&t<=84}},defaults:{type:_t.LINE,color:"transparent",opacity:1,strokeWidth:6,strokeColor:"#E44234"},clickBehavior:{enabled:!0,defaultLength:100,defaultAngle:0}},{id:"lineArrow",name:"Arrow",matchScore:e=>e.type===_t.LINE&&"LineArrow"===e.intent?10:0,interaction:{exclusive:!1,cursor:"crosshair",isDraggable:!0,isResizable:!1,lockAspectRatio:!1,isGroupResizable:!0,lockGroupAspectRatio:e=>{const t=((e.rotation??0)%90+90)%90;return t>=6&&t<=84}},defaults:{type:_t.LINE,intent:"LineArrow",color:"transparent",opacity:1,strokeWidth:6,strokeColor:"#E44234",lineEndings:{start:Lt.None,end:Lt.OpenArrow}},clickBehavior:{enabled:!0,defaultLength:100,defaultAngle:0}},{id:"polyline",name:"Polyline",matchScore:e=>e.type===_t.POLYLINE?1:0,interaction:{exclusive:!1,cursor:"crosshair",isDraggable:!0,isResizable:!1,lockAspectRatio:!1,isGroupResizable:!0,lockGroupAspectRatio:e=>{const t=((e.rotation??0)%90+90)%90;return t>=6&&t<=84}},defaults:{type:_t.POLYLINE,color:"transparent",opacity:1,strokeWidth:6,strokeColor:"#E44234"}},{id:"polygon",name:"Polygon",matchScore:e=>e.type===_t.POLYGON?1:0,interaction:{exclusive:!1,cursor:"crosshair",isDraggable:!0,isResizable:!1,lockAspectRatio:!1,isGroupResizable:!0,lockGroupAspectRatio:e=>{const t=((e.rotation??0)%90+90)%90;return t>=6&&t<=84}},defaults:{type:_t.POLYGON,color:"transparent",opacity:1,strokeWidth:6,strokeColor:"#E44234"}},{id:"freeText",name:"Free Text",matchScore:e=>e.type===_t.FREETEXT?1:0,interaction:{exclusive:!1,cursor:"crosshair",isDraggable:!0,isResizable:!0,lockAspectRatio:!1,lockGroupAspectRatio:e=>{const t=((e.rotation??0)%90+90)%90;return t>=6&&t<=84}},defaults:{type:_t.FREETEXT,contents:"Insert text",fontSize:14,fontColor:"#E44234",fontFamily:Pt.Helvetica,textAlign:Dt.Left,verticalAlign:Rt.Top,color:"transparent",backgroundColor:"transparent",opacity:1},clickBehavior:{enabled:!0,defaultSize:{width:100,height:20},defaultContent:"Insert text"},behavior:{insertUpright:!0}},{id:"stamp",name:"Image",matchScore:e=>e.type===_t.STAMP?1:0,interaction:{exclusive:!1,cursor:"copy",isDraggable:!0,isResizable:!0,lockAspectRatio:!0,lockGroupAspectRatio:!0},defaults:{type:_t.STAMP},behavior:{insertUpright:!0}}],yd=["#E44234","#FF8D00","#FFCD45","#5CC96E","#25D2D1","#597CE2","#C544CE","#7D2E25","#000000","#FFFFFF"],bd=e=>1===e.length?e[0]:null,wd=(e,t,n)=>{const o=e.byUid[t];return o?{...e,byUid:{...e.byUid,[t]:{...o,commitState:"synced"===o.commitState?"dirty":o.commitState,object:{...o.object,...n}}},hasPendingChanges:!0}:e};function xd(e){let t=e;return[()=>t,e=>{t=e}]}const Cd={annotationType:_t.INK,create(e){const{onCommit:t,onPreview:n,getTool:o,pageSize:i}=e,[r,a]=xd([]),[s,l]=xd(!1),c={current:null},d=e=>({x:wo(e.x,0,i.width),y:wo(e.y,0,i.height)}),u=()=>{const e=o();return e?{...e.defaults,strokeWidth:e.defaults.strokeWidth??1,strokeColor:e.defaults.strokeColor??e.defaults.color??"#000000",opacity:e.defaults.opacity??1,flags:e.defaults.flags??["print"]}:null},h=()=>{const e=r();if(0===e.length||0===e[0].points.length)return null;const t=u();if(!t)return null;const n=e.flatMap(e=>e.points),o=et(Je(n),t.strokeWidth/2);return{type:_t.INK,bounds:o,data:{...t,rect:o,inkList:e}}};return{onPointerDown:(e,t)=>{var o;const i=d(e);l(!0),c.current&&clearTimeout(c.current);const s=[...r(),{points:[i]}];a(s),n(h()),null==(o=t.setPointerCapture)||o.call(t)},onPointerMove:e=>{if(!s())return;const t=r();if(0===t.length)return;const o=d(e);t[t.length-1].points.push(o),a(t),n(h())},onPointerUp:(o,i)=>{var s;l(!1),null==(s=i.releasePointerCapture)||s.call(i),c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{const o=r();if(o.length>0&&o[0].points.length>1){const n=u();if(!n)return;const i=o.flatMap(e=>e.points),r=et(Je(i),n.strokeWidth/2);t({...n,inkList:o,rect:r,type:_t.INK,pageIndex:e.pageIndex,id:zn(),created:new Date})}a([]),n(null)},800)},onPointerCancel:(e,t)=>{var o;a([]),l(!1),n(null),c.current&&clearTimeout(c.current),null==(o=t.releasePointerCapture)||o.call(t)}}}};function Id({threshold:e=5,getTool:t,onClickDetected:n}){const[o,i]=xd(null),[r,a]=xd(!1);return{onStart:e=>{i(e),a(!1)},onMove:t=>{const n=o();if(!n||r())return;Math.sqrt(Math.pow(t.x-n.x,2)+Math.pow(t.y-n.y,2))>e&&a(!0)},onEnd:e=>{var s;if(o()&&!r()){const o=t();o&&"clickBehavior"in o&&(null==(s=o.clickBehavior)?void 0:s.enabled)&&n(e,o)}i(null),a(!1)},hasMoved:r,reset:()=>{i(null),a(!1)}}}function kd(e){const t=e=>{const t=9*e,n=Math.PI/6;return{x:-t*Math.cos(n),y:t*Math.sin(n)}};return{getSvgPath:n=>{const{x:o,y:i}=t(n);return e?`M 0 0 L ${o} ${i} L ${o} ${-i} Z`:`M ${o} ${i} L 0 0 L ${o} ${-i}`},getLocalPoints:e=>{const{x:n,y:o}=t(e);return[{x:0,y:0},{x:n,y:o},{x:n,y:-o}]},getRotation:e=>e,filled:e}}function Sd(e,t){const n=t=>t*e/2;return{getSvgPath:e=>{const t=n(e);return`M ${-t} 0 L ${t} 0`},getLocalPoints:e=>{const t=n(e);return[{x:-t,y:0},{x:t,y:0}]},getRotation:t,filled:!1}}const Md=kd(!1),Ad=kd(!0),Pd={[Lt.OpenArrow]:Md,[Lt.ClosedArrow]:Ad,[Lt.ROpenArrow]:{...Md,getRotation:e=>e+Math.PI},[Lt.RClosedArrow]:{...Ad,getRotation:e=>e+Math.PI},[Lt.Circle]:{getSvgPath:e=>{const t=5*e/2;return`M ${t} 0 A ${t} ${t} 0 1 1 ${-t} 0 A ${t} ${t} 0 1 1 ${t} 0`},getLocalPoints:e=>{const t=5*e/2;return[{x:-t,y:-t},{x:t,y:t}]},getRotation:()=>0,filled:!0},[Lt.Square]:{getSvgPath:e=>{const t=6*e/2;return`M ${-t} ${-t} L ${t} ${-t} L ${t} ${t} L ${-t} ${t} Z`},getLocalPoints:e=>{const t=6*e/2;return[{x:-t,y:-t},{x:t,y:-t},{x:t,y:t},{x:-t,y:t}]},getRotation:e=>e,filled:!0},[Lt.Diamond]:{getSvgPath:e=>{const t=6*e/2;return`M 0 ${-t} L ${t} 0 L 0 ${t} L ${-t} 0 Z`},getLocalPoints:e=>{const t=6*e/2;return[{x:0,y:-t},{x:t,y:0},{x:0,y:t},{x:-t,y:0}]},getRotation:e=>e,filled:!0},[Lt.Butt]:Sd(6,e=>e+Math.PI/2),[Lt.Slash]:Sd(18,e=>e+Math.PI/1.5)};function Dd(e,t,n){if(!e||0===e.length)return{origin:{x:0,y:0},size:{width:0,height:0}};const o=[...e],i=(e,t)=>Math.atan2(t.y-e.y,t.x-e.x),r=(e,n,i)=>{if(!e)return;const r=Pd[e];if(!r)return;const a=r.getLocalPoints(t),s=r.getRotation(i),l=a.map(e=>function(e,t,n){const o=Math.cos(t),i=Math.sin(t),r=e.x*o-e.y*i,a=e.x*i+e.y*o;return{x:r+n.x,y:a+n.y}}(e,s,n));o.push(...l)};if(e.length>=2){const t=i(e[1],e[0]);r(null==n?void 0:n.start,e[0],t);const o=e.length-1,a=i(e[o-1],e[o]);r(null==n?void 0:n.end,e[o],a)}if(o.length<=1){const n=e[0]||{x:0,y:0},o=t;return{origin:{x:n.x-o,y:n.y-o},size:{width:2*o,height:2*o}}}return et(Je(o),t/2+1.2*t)}function Rd(e,t){if(!e.unrotatedRect)return{rect:t};const n=st(t);return{rect:dt(t,e.rotation??0,n),unrotatedRect:t}}function zd(e){return e.unrotatedRect?ht(e.unrotatedRect,e.rect,e.rotation??0):st(e.rect)}function Td(e,t,n){const o=zd(e),i=e.unrotatedRect??e.rect,r=t.origin.x-i.origin.x,a=t.origin.y-i.origin.y;return{rect:dt(t,n,{x:o.x+r,y:o.y+a}),unrotatedRect:t}}function Ed(e,t,n){if(!e.unrotatedRect)return t;const o=e.rotation??0;if(Math.abs(o%360)<1e-8)return t;const i=zd(e),r=st(n),a=o*Math.PI/180,s=Math.cos(a),l=Math.sin(a),c=i.x-r.x,d=i.y-r.y,u=(1-s)*c+l*d,h=-l*c+(1-s)*d;return Math.abs(u)<1e-8&&Math.abs(h)<1e-8?t:t.map(e=>({x:e.x+u,y:e.y+h}))}class _d{constructor(){this.patches=new Map}register(e,t){this.patches.set(e,t)}transform(e,t){const n=this.patches.get(e.type);return n?n(e,t):t.changes}}const Nd=new _d;function Od(e,t){var n;if(void 0===(null==(n=t.metadata)?void 0:n.rotationAngle))return null;const o=t.metadata.rotationAngle,i=t.changes.unrotatedRect??e.unrotatedRect??e.rect;return{...Td(e,{origin:{...i.origin},size:{...i.size}},o),rotation:o}}function Ld(e,t){return{rotation:t,...Td(e,e.unrotatedRect??e.rect,t)}}function $d(e,t){const n=t.origin.x-e.rect.origin.x,o=t.origin.y-e.rect.origin.y,i={rect:t};return e.unrotatedRect&&(i.unrotatedRect={origin:{x:e.unrotatedRect.origin.x+n,y:e.unrotatedRect.origin.y+o},size:{...e.unrotatedRect.size}}),{dx:n,dy:o,rects:i}}function jd(e,t,n){const o=e.unrotatedRect??e.rect;let i=t.size.width/o.size.width,r=t.size.height/o.size.height;if((t.size.width<10||t.size.height<10)&&(i=Math.max(i,10/o.size.width),r=Math.max(r,10/o.size.height),t={origin:t.origin,size:{width:o.size.width*i,height:o.size.height*r}}),null==n?void 0:n.maintainAspectRatio){const e=Math.min(i,r);i=e,r=e,t={origin:t.origin,size:{width:o.size.width*e,height:o.size.height*e}}}return{scaleX:i,scaleY:r,oldRect:o,resolvedRect:t,rects:e.unrotatedRect?{unrotatedRect:t,rect:ut(t,e.rotation??0)}:{rect:t}}}function Fd(e,t){const n=e.unrotatedRect??e.rect,o=t.unrotatedRect??n;return{dx:o.origin.x-n.origin.x,dy:o.origin.y-n.origin.y}}function Ud(e,t,n){if(0===t||void 0!==e.rotation)return e;const o=(4-t)%4*90;let i=e;if(n&&(1===t||3===t)){const t=e.rect,n=t.origin.x+t.size.width/2,o=t.origin.y+t.size.height/2;i={...e,rect:{origin:{x:n-t.size.height/2,y:o-t.size.width/2},size:{width:t.size.height,height:t.size.width}}}}const{rotation:r,rect:a,unrotatedRect:s}=Ld(i,o);return{...i,rotation:r,rect:a,unrotatedRect:s}}function Hd(e,t){const n=wo(e.rect.origin.x,0,t.width-e.rect.size.width),o=wo(e.rect.origin.y,0,t.height-e.rect.size.height),i=n-e.rect.origin.x,r=o-e.rect.origin.y;return 0===i&&0===r?e:{...e,rect:{origin:{x:n,y:o},size:e.rect.size},...e.unrotatedRect?{unrotatedRect:{origin:{x:e.unrotatedRect.origin.x+i,y:e.unrotatedRect.origin.y+r},size:e.unrotatedRect.size}}:{}}}const Bd=Object.freeze(Object.defineProperty({__proto__:null,LINE_ENDING_HANDLERS:Pd,PatchRegistry:_d,applyInsertUpright:Ud,calculateAABBFromVertices:function(e,t=0){if(0===e.length)return{origin:{x:0,y:0},size:{width:0,height:0}};const n=Je(e);return t>0?et(n,t):n},calculateRotatedRectAABB:ut,calculateRotatedRectAABBAroundPoint:dt,clampAnnotationToPage:Hd,compensateRotatedVertexEdit:Ed,createEnding:function(e,t,n,o,i){if(!e)return null;const r=Pd[e];if(!r)return null;const a=r.getRotation(n);return{d:r.getSvgPath(t),transform:`translate(${o} ${i}) rotate(${(e=>180*e/Math.PI)(a)})`,filled:r.filled}},getRectCenter:st,lineRectWithEndings:Dd,patchRegistry:Nd,resolveAnnotationRotationCenter:zd,resolveRotateRects:Td,resolveVertexEditRects:Rd,rotatePointAroundCenter:lt,rotateVertices:ct},Symbol.toStringTag,{value:"Module"})),Wd={annotationType:_t.FREETEXT,create(e){const{onCommit:t,onPreview:n,getTool:o,pageSize:i,pageIndex:r,pageRotation:a}=e,[s,l]=xd(null),c=e=>({x:wo(e.x,0,i.width),y:wo(e.y,0,i.height)}),d=()=>{const e=o();return e?{...e.defaults,fontColor:e.defaults.fontColor??"#000000",opacity:e.defaults.opacity??1,fontSize:e.defaults.fontSize??12,fontFamily:e.defaults.fontFamily??Pt.Helvetica,color:e.defaults.color??e.defaults.backgroundColor??"transparent",textAlign:e.defaults.textAlign??Dt.Left,verticalAlign:e.defaults.verticalAlign??Rt.Top,contents:e.defaults.contents??"Insert text here",flags:e.defaults.flags??["print"]}:null},u=Id({threshold:5,getTool:o,onClickDetected:(e,n)=>{var o;const s=d();if(!s)return;const l=n.clickBehavior;if(!(null==l?void 0:l.enabled))return;const{width:c,height:u}=l.defaultSize,h={origin:{x:e.x-c/2,y:e.y-u/2},size:{width:c,height:u}},m=l.defaultContent??s.contents;let g={...s,contents:m,type:_t.FREETEXT,rect:h,pageIndex:r,id:zn(),created:new Date};(null==(o=n.behavior)?void 0:o.insertUpright)&&(g=Ud(g,a,!1)),g=Hd(g,i),t(g)}}),h=e=>{const t=s();if(!t)return null;const n=d();if(!n)return null;const o={origin:{x:Math.min(t.x,e.x),y:Math.min(t.y,e.y)},size:{width:Math.abs(t.x-e.x),height:Math.abs(t.y-e.y)}};return{type:_t.FREETEXT,bounds:o,data:{...n,rect:o}}};return{onPointerDown:(e,t)=>{var o;const i=c(e);l(i),u.onStart(i),n(h(i)),null==(o=t.setPointerCapture)||o.call(t)},onPointerMove:e=>{const t=c(e);u.onMove(t),s()&&u.hasMoved()&&n(h(t))},onPointerUp:(i,r)=>{var h,m;const g=s();if(!g)return;const p=d();if(!p)return;const f=c(i);if(u.hasMoved()){const n={origin:{x:Math.min(g.x,f.x),y:Math.min(g.y,f.y)},size:{width:Math.abs(g.x-f.x),height:Math.abs(g.y-f.y)}},i=o();let r={...p,type:_t.FREETEXT,rect:n,pageIndex:e.pageIndex,id:zn(),created:new Date};(null==(h=null==i?void 0:i.behavior)?void 0:h.insertUpright)&&(r=Ud(r,a,!0)),t(r)}else u.onEnd(f);l(null),n(null),u.reset(),null==(m=r.releasePointerCapture)||m.call(r)},onPointerLeave:(e,t)=>{var o;l(null),n(null),u.reset(),null==(o=t.releasePointerCapture)||o.call(t)},onPointerCancel:(e,t)=>{var o;l(null),n(null),u.reset(),null==(o=t.releasePointerCapture)||o.call(t)}}}},qd={annotationType:_t.LINE,create(e){const{pageIndex:t,onCommit:n,onPreview:o,getTool:i,pageSize:r}=e,[a,s]=xd(null),l=e=>({x:wo(e.x,0,r.width),y:wo(e.y,0,r.height)}),c=()=>{const e=i();return e?{...e.defaults,strokeWidth:e.defaults.strokeWidth??1,lineEndings:e.defaults.lineEndings??{start:Lt.None,end:Lt.None},color:e.defaults.color??"#000000",opacity:e.defaults.opacity??1,strokeStyle:e.defaults.strokeStyle??Ut.SOLID,strokeDashArray:e.defaults.strokeDashArray??[],strokeColor:e.defaults.strokeColor??"#000000",flags:e.defaults.flags??["print"]}:null},d=Id({threshold:5,getTool:i,onClickDetected:(e,o)=>{const i=c();if(!i)return;const r=o.clickBehavior;if(!(null==r?void 0:r.enabled))return;const a=r.defaultAngle??0,s=r.defaultLength/2,d=e.x-s*Math.cos(a),u=e.y-s*Math.sin(a),h=e.x+s*Math.cos(a),m=e.y+s*Math.sin(a),g=l({x:d,y:u}),p=l({x:h,y:m}),f=Dd([g,p],i.strokeWidth,i.lineEndings);n({...i,rect:f,linePoints:{start:g,end:p},pageIndex:t,id:zn(),created:new Date,type:_t.LINE})}}),u=e=>{const t=a();if(!t)return null;const n=c();if(!n)return null;const o=Dd([t,e],n.strokeWidth,n.lineEndings);return{type:_t.LINE,bounds:o,data:{...n,rect:o,linePoints:{start:t,end:e}}}};return{onPointerDown:(e,t)=>{var n;const i=l(e);s(i),d.onStart(i),o(u(i)),null==(n=t.setPointerCapture)||n.call(t)},onPointerMove:e=>{const t=l(e);d.onMove(t),a()&&d.hasMoved()&&o(u(t))},onPointerUp:(e,i)=>{var r;const u=a();if(!u)return;const h=l(e);if(d.hasMoved()){const e=c();if(!e)return;if(Math.abs(h.x-u.x)>2||Math.abs(h.y-u.y)>2){const o=Dd([u,h],e.strokeWidth,e.lineEndings);n({...e,rect:o,linePoints:{start:u,end:h},pageIndex:t,id:zn(),flags:["print"],created:new Date,type:_t.LINE})}}else d.onEnd(h);s(null),o(null),d.reset(),null==(r=i.releasePointerCapture)||r.call(i)},onPointerLeave:(e,t)=>{var n;s(null),o(null),d.reset(),null==(n=t.releasePointerCapture)||n.call(t)},onPointerCancel:(e,t)=>{var n;s(null),o(null),d.reset(),null==(n=t.releasePointerCapture)||n.call(t)}}}},Gd={annotationType:_t.POLYLINE,create(e){const{onCommit:t,onPreview:n,getTool:o,pageSize:i}=e,[r,a]=xd([]),[s,l]=xd(null),c=e=>({x:wo(e.x,0,i.width),y:wo(e.y,0,i.height)}),d=()=>{const e=o();return e?{...e.defaults,strokeWidth:e.defaults.strokeWidth??1,lineEndings:e.defaults.lineEndings??{start:Lt.None,end:Lt.None},color:e.defaults.color??"#000000",opacity:e.defaults.opacity??1,strokeColor:e.defaults.strokeColor??"#000000",strokeStyle:e.defaults.strokeStyle??Ut.SOLID,strokeDashArray:e.defaults.strokeDashArray??[],flags:e.defaults.flags??["print"]}:null},u=()=>{const e=r(),t=s();if(0===e.length||!t)return null;const n=d();if(!n)return null;const o=[...e,t],i=Dd(o,n.strokeWidth,n.lineEndings);return{type:_t.POLYLINE,bounds:i,data:{...n,rect:i,vertices:o,currentVertex:t}}};return{onClick:(e,t)=>{if(t.metaKey||t.ctrlKey)return;const o=c(e),i=r(),s=i[i.length-1];s&&Math.abs(s.x-o.x)<1&&Math.abs(s.y-o.y)<1||(a([...i,o]),l(o),n(u()))},onDoubleClick:()=>{(()=>{const o=r();if(o.length<2)return;const i=d();if(!i)return;const s=Dd(o,i.strokeWidth,i.lineEndings),c={...i,vertices:o,rect:s,type:_t.POLYLINE,pageIndex:e.pageIndex,id:zn(),created:new Date};t(c),a([]),l(null),n(null)})()},onPointerMove:e=>{if(r().length>0){const t=c(e);l(t),n(u())}},onPointerCancel:()=>{a([]),l(null),n(null)}}}},Vd={annotationType:_t.POLYGON,create(e){const{onCommit:t,onPreview:n,getTool:o,scale:i,pageSize:r}=e,[a,s]=xd([]),[l,c]=xd(null),d=e=>({x:wo(e.x,0,r.width),y:wo(e.y,0,r.height)}),u=()=>{const e=o();return e?{...e.defaults,color:e.defaults.color??"#000000",opacity:e.defaults.opacity??1,strokeWidth:e.defaults.strokeWidth??1,strokeColor:e.defaults.strokeColor??"#000000",strokeStyle:e.defaults.strokeStyle??Ut.SOLID,strokeDashArray:e.defaults.strokeDashArray??[],flags:e.defaults.flags??["print"]}:null},h=()=>{const o=a();if(o.length<3)return;const i=u();if(!i)return;const r=et(Je(o),i.strokeWidth/2),l={...i,vertices:o,rect:r,type:_t.POLYGON,pageIndex:e.pageIndex,id:zn(),created:new Date};t(l),s([]),c(null),n(null)},m=()=>{const e=a(),t=l();if(0===e.length||!t)return null;const n=u();if(!n)return null;const o=et(Je([...e,t]),n.strokeWidth/2);return{type:_t.POLYGON,bounds:o,data:{...n,rect:o,vertices:e,currentVertex:t}}};return{onClick:(e,t)=>{if(t.metaKey||t.ctrlKey)return;const o=d(e);if((e=>{const t=a();if(t.length<2)return!1;const n=14/i/2,o=t[0];return e.x>=o.x-n&&e.x<=o.x+n&&e.y>=o.y-n&&e.y<=o.y+n})(o)&&a().length>=3)return void h();const r=a(),l=r[r.length-1];l&&Math.abs(l.x-o.x)<1&&Math.abs(l.y-o.y)<1||(s([...r,o]),c(o),n(m()))},onDoubleClick:e=>{h()},onPointerMove:e=>{if(a().length>0){const t=d(e);c(t),n(m())}},onPointerCancel:e=>{s([]),c(null),n(null)}}}},Kd={annotationType:_t.SQUARE,create(e){const{pageIndex:t,onCommit:n,onPreview:o,getTool:i,pageSize:r}=e,[a,s]=xd(null),l=e=>({x:wo(e.x,0,r.width),y:wo(e.y,0,r.height)}),c=()=>{const e=i();return e?{...e.defaults,flags:e.defaults.flags??["print"],strokeWidth:e.defaults.strokeWidth??2,strokeColor:e.defaults.strokeColor??"#000000",strokeStyle:e.defaults.strokeStyle??Ut.SOLID,strokeDashArray:e.defaults.strokeDashArray??[],color:e.defaults.color??"#000000",opacity:e.defaults.opacity??1}:null},d=Id({threshold:5,getTool:i,onClickDetected:(e,o)=>{const i=c();if(!i)return;const a=o.clickBehavior;if(!(null==a?void 0:a.enabled))return;const{width:s,height:l}=a.defaultSize,d=s/2,u=l/2,h=wo(e.x-d,0,r.width-s),m=wo(e.y-u,0,r.height-l),g=i.strokeWidth,p=g/2,f={origin:{x:h-p,y:m-p},size:{width:s+g,height:l+g}},v={...i,type:_t.SQUARE,created:new Date,id:zn(),pageIndex:t,rect:f};n(v)}}),u=e=>{const t=a();if(!t)return null;const n=Math.min(t.x,e.x),o=Math.min(t.y,e.y),i=Math.abs(t.x-e.x),r=Math.abs(t.y-e.y),s=c();if(!s)return null;const l=s.strokeWidth,d=l/2,u={origin:{x:n-d,y:o-d},size:{width:i+l,height:r+l}};return{type:_t.SQUARE,bounds:u,data:{rect:u,...s}}};return{onPointerDown:(e,t)=>{var n;const i=l(e);s(i),d.onStart(i),o(u(i)),null==(n=t.setPointerCapture)||n.call(t)},onPointerMove:e=>{const t=l(e);d.onMove(t),a()&&d.hasMoved()&&o(u(t))},onPointerUp:(e,i)=>{var r;if(!a())return;if(!c())return;const h=l(e);if(d.hasMoved()){const e=c();if(!e)return;const o=u(h);if(o){const i={...e,type:_t.SQUARE,created:new Date,id:zn(),pageIndex:t,rect:o.data.rect};n(i)}}else d.onEnd(h);s(null),o(null),d.reset(),null==(r=i.releasePointerCapture)||r.call(i)},onPointerLeave:(e,t)=>{var n;s(null),o(null),d.reset(),null==(n=t.releasePointerCapture)||n.call(t)},onPointerCancel:(e,t)=>{var n;s(null),o(null),d.reset(),null==(n=t.releasePointerCapture)||n.call(t)}}}},Zd={annotationType:_t.STAMP,create(e){const{services:t,onCommit:n,getTool:o,pageSize:i,pageRotation:r}=e;return{onPointerDown:a=>{const s=o();if(!s)return;const{imageSrc:l,imageSize:c}=s.defaults,d=(t,o,l)=>{var c;const d={origin:{x:a.x-o/2,y:a.y-l/2},size:{width:o,height:l}};let u={...s.defaults,rect:d,type:_t.STAMP,icon:s.defaults.icon??Ot.Draft,subject:s.defaults.subject??"Stamp",flags:s.defaults.flags??["print"],pageIndex:e.pageIndex,id:zn(),created:new Date};(null==(c=s.behavior)?void 0:c.insertUpright)&&(u=Ud(u,r,!1)),u=Hd(u,i),n(u,{imageData:t})};l?t.processImage({source:l,maxWidth:i.width,maxHeight:i.height,onComplete:e=>d(e.imageData,(null==c?void 0:c.width)??e.width,(null==c?void 0:c.height)??e.height)}):t.requestFile({accept:"image/png,image/jpeg",onFile:e=>{t.processImage({source:e,maxWidth:i.width,maxHeight:i.height,onComplete:e=>d(e.imageData,e.width,e.height)})}})}}}},Yd={annotationType:_t.CIRCLE,create(e){const{pageIndex:t,onCommit:n,onPreview:o,getTool:i,pageSize:r}=e,[a,s]=xd(null),l=e=>({x:wo(e.x,0,r.width),y:wo(e.y,0,r.height)}),c=()=>{const e=i();return e?{...e.defaults,strokeWidth:e.defaults.strokeWidth??2,strokeColor:e.defaults.strokeColor??"#000000",strokeStyle:e.defaults.strokeStyle??Ut.SOLID,strokeDashArray:e.defaults.strokeDashArray??[],color:e.defaults.color??"#000000",opacity:e.defaults.opacity??1,flags:e.defaults.flags??["print"]}:null},d=Id({threshold:5,getTool:i,onClickDetected:(e,o)=>{const i=c();if(!i)return;const a=o.clickBehavior;if(!(null==a?void 0:a.enabled))return;const{width:s,height:l}=a.defaultSize,d=s/2,u=l/2,h=wo(e.x-d,0,r.width-s),m=wo(e.y-u,0,r.height-l),g=i.strokeWidth,p=g/2,f={origin:{x:h-p,y:m-p},size:{width:s+g,height:l+g}},v={...i,type:_t.CIRCLE,created:new Date,id:zn(),pageIndex:t,rect:f};n(v)}}),u=e=>{const t=a();if(!t)return null;const n=Math.min(t.x,e.x),o=Math.min(t.y,e.y),i=Math.abs(t.x-e.x),r=Math.abs(t.y-e.y),s=c();if(!s)return null;const l=s.strokeWidth,d=l/2,u={origin:{x:n-d,y:o-d},size:{width:i+l,height:r+l}};return{type:_t.CIRCLE,bounds:u,data:{rect:u,...s}}};return{onPointerDown:(e,t)=>{var n;const i=l(e);s(i),d.onStart(i),o(u(i)),null==(n=t.setPointerCapture)||n.call(t)},onPointerMove:e=>{const t=l(e);d.onMove(t),a()&&d.hasMoved()&&o(u(t))},onPointerUp:(e,i)=>{var r;if(!a())return;if(!c())return;const h=l(e);if(d.hasMoved()){const e=c();if(!e)return;const o=u(h);if(o){const i={...e,type:_t.CIRCLE,flags:["print"],created:new Date,id:zn(),pageIndex:t,rect:o.data.rect};n(i)}}else d.onEnd(h);s(null),o(null),d.reset(),null==(r=i.releasePointerCapture)||r.call(i)},onPointerLeave:(e,t)=>{var n;s(null),o(null),d.reset(),null==(n=t.releasePointerCapture)||n.call(t)},onPointerCancel:(e,t)=>{var n;s(null),o(null),d.reset(),null==(n=t.releasePointerCapture)||n.call(t)}}}},Xd=(e,t)=>{switch(t.type){case"vertex-edit":default:return t.changes;case"move":{if(!t.changes.rect)return t.changes;const{dx:n,dy:o,rects:i}=$d(e,t.changes.rect);return{...i,inkList:e.inkList.map(e=>({points:e.points.map(e=>({x:e.x+n,y:e.y+o}))}))}}case"resize":{if(!t.changes.rect)return t.changes;const{oldRect:n,resolvedRect:o,rects:i}=jd(e,t.changes.rect,t.metadata),r=(e,t)=>({origin:{x:e.origin.x+t,y:e.origin.y+t},size:{width:Math.max(1,e.size.width-2*t),height:Math.max(1,e.size.height-2*t)}}),a=Math.min(o.size.width/n.size.width,o.size.height/n.size.height),s=Math.max(1,Math.round(e.strokeWidth*a)),l=r(n,e.strokeWidth/2),c=r(o,s/2),d=c.size.width/Math.max(l.size.width,1e-6),u=c.size.height/Math.max(l.size.height,1e-6);return{...i,inkList:e.inkList.map(e=>({points:e.points.map(e=>({x:c.origin.x+(e.x-l.origin.x)*d,y:c.origin.y+(e.y-l.origin.y)*u}))})),strokeWidth:s}}case"rotate":{const n=Od(e,t);if(!n)return t.changes;const{dx:o,dy:i}=Fd(e,n);return{...n,inkList:e.inkList.map(e=>({points:e.points.map(e=>({x:e.x+o,y:e.y+i}))}))}}case"property-update":{if(!(void 0!==t.changes.strokeWidth||void 0!==t.changes.rotation))return t.changes;const n={...e,...t.changes},o=n.inkList.flatMap(e=>e.points),i=et(Je(o),n.strokeWidth/2),r=t.changes.rotation??e.rotation??0;return e.unrotatedRect||void 0!==t.changes.rotation?{...t.changes,unrotatedRect:i,rect:dt(i,r,zd(e))}:{...t.changes,rect:i}}}},Qd=(e,t)=>{switch(t.type){case"vertex-edit":if(t.changes.linePoints){const{start:n,end:o}=t.changes.linePoints,i=[n,o],r=Ed(e,i,Dd(i,e.strokeWidth,e.lineEndings));return{...Rd(e,Dd(r,e.strokeWidth,e.lineEndings)),linePoints:{start:r[0],end:r[1]}}}return t.changes;case"move":{if(!t.changes.rect)return t.changes;const{dx:n,dy:o,rects:i}=$d(e,t.changes.rect);return{...i,linePoints:{start:{x:e.linePoints.start.x+n,y:e.linePoints.start.y+o},end:{x:e.linePoints.end.x+n,y:e.linePoints.end.y+o}}}}case"resize":{if(!t.changes.rect)return t.changes;const{scaleX:n,scaleY:o,oldRect:i,resolvedRect:r,rects:a}=jd(e,t.changes.rect,t.metadata);return{...a,linePoints:{start:{x:r.origin.x+(e.linePoints.start.x-i.origin.x)*n,y:r.origin.y+(e.linePoints.start.y-i.origin.y)*o},end:{x:r.origin.x+(e.linePoints.end.x-i.origin.x)*n,y:r.origin.y+(e.linePoints.end.y-i.origin.y)*o}}}}case"rotate":{const n=Od(e,t);if(!n)return t.changes;const{dx:o,dy:i}=Fd(e,n);return{...n,linePoints:{start:{x:e.linePoints.start.x+o,y:e.linePoints.start.y+i},end:{x:e.linePoints.end.x+o,y:e.linePoints.end.y+i}}}}case"property-update":{if(!(void 0!==t.changes.strokeWidth||void 0!==t.changes.lineEndings||void 0!==t.changes.rotation))return t.changes;const n={...e,...t.changes},o=Dd([n.linePoints.start,n.linePoints.end],n.strokeWidth,n.lineEndings),i=t.changes.rotation??e.rotation??0;return e.unrotatedRect||void 0!==t.changes.rotation?{...t.changes,unrotatedRect:o,rect:dt(o,i,zd(e))}:{...t.changes,rect:o}}default:return t.changes}},Jd=(e,t)=>{switch(t.type){case"vertex-edit":if(t.changes.vertices&&t.changes.vertices.length){const n=t.changes.vertices,o=Ed(e,n,Dd(n,e.strokeWidth,e.lineEndings));return{...Rd(e,Dd(o,e.strokeWidth,e.lineEndings)),vertices:o}}return t.changes;case"move":{if(!t.changes.rect)return t.changes;const{dx:n,dy:o,rects:i}=$d(e,t.changes.rect);return{...i,vertices:e.vertices.map(e=>({x:e.x+n,y:e.y+o}))}}case"resize":{if(!t.changes.rect)return t.changes;const{scaleX:n,scaleY:o,oldRect:i,resolvedRect:r,rects:a}=jd(e,t.changes.rect,t.metadata);return{...a,vertices:e.vertices.map(e=>({x:r.origin.x+(e.x-i.origin.x)*n,y:r.origin.y+(e.y-i.origin.y)*o}))}}case"rotate":{const n=Od(e,t);if(!n)return t.changes;const{dx:o,dy:i}=Fd(e,n);return{...n,vertices:e.vertices.map(e=>({x:e.x+o,y:e.y+i}))}}case"property-update":{if(!(void 0!==t.changes.strokeWidth||void 0!==t.changes.lineEndings||void 0!==t.changes.rotation))return t.changes;const n={...e,...t.changes},o=Dd(n.vertices,n.strokeWidth,n.lineEndings),i=t.changes.rotation??e.rotation??0;return e.unrotatedRect||void 0!==t.changes.rotation?{...t.changes,unrotatedRect:o,rect:dt(o,i,zd(e))}:{...t.changes,rect:o}}default:return t.changes}},eu=(e,t)=>{switch(t.type){case"vertex-edit":if(t.changes.vertices&&t.changes.vertices.length){const n=e.strokeWidth/2,o=t.changes.vertices,i=Ed(e,o,et(Je(o),n));return{...Rd(e,et(Je(i),n)),vertices:i}}return t.changes;case"move":{if(!t.changes.rect)return t.changes;const{dx:n,dy:o,rects:i}=$d(e,t.changes.rect);return{...i,vertices:e.vertices.map(e=>({x:e.x+n,y:e.y+o}))}}case"resize":{if(!t.changes.rect)return t.changes;const{scaleX:n,scaleY:o,oldRect:i,resolvedRect:r,rects:a}=jd(e,t.changes.rect,t.metadata);return{...a,vertices:e.vertices.map(e=>({x:r.origin.x+(e.x-i.origin.x)*n,y:r.origin.y+(e.y-i.origin.y)*o}))}}case"rotate":{const n=Od(e,t);if(!n)return t.changes;const{dx:o,dy:i}=Fd(e,n);return{...n,vertices:e.vertices.map(e=>({x:e.x+o,y:e.y+i}))}}case"property-update":{if(!(void 0!==t.changes.strokeWidth||void 0!==t.changes.rotation))return t.changes;const n={...e,...t.changes},o=n.strokeWidth/2,i=et(Je(n.vertices),o),r=t.changes.rotation??e.rotation??0;return e.unrotatedRect||void 0!==t.changes.rotation?{...t.changes,unrotatedRect:i,rect:dt(i,r,zd(e))}:{...t.changes,rect:i}}default:return t.changes}},tu=(e,t)=>{switch(t.type){case"move":return t.changes.rect?$d(e,t.changes.rect).rects:t.changes;case"resize":return t.changes.rect?jd(e,t.changes.rect,t.metadata).rects:t.changes;case"rotate":return Od(e,t)??t.changes;case"property-update":return void 0!==t.changes.rotation?{...t.changes,...Ld(e,t.changes.rotation)}:t.changes;default:return t.changes}},nu=(e,t)=>{switch(t.type){case"move":return t.changes.rect?$d(e,t.changes.rect).rects:t.changes;case"resize":return t.changes.rect?jd(e,t.changes.rect,t.metadata).rects:t.changes;case"rotate":return Od(e,t)??t.changes;case"property-update":return void 0!==t.changes.rotation?{...t.changes,...Ld(e,t.changes.rotation)}:t.changes;default:return t.changes}},ou=(e,t)=>{switch(t.type){case"move":return t.changes.rect?$d(e,t.changes.rect).rects:t.changes;case"resize":return t.changes.rect?jd(e,t.changes.rect,t.metadata).rects:t.changes;case"rotate":return Od(e,t)??t.changes;case"property-update":return void 0!==t.changes.rotation?{...t.changes,...Ld(e,t.changes.rotation)}:t.changes;default:return t.changes}},iu=(e,t)=>{switch(t.type){case"move":return t.changes.rect?$d(e,t.changes.rect).rects:t.changes;case"resize":return t.changes.rect?jd(e,t.changes.rect,t.metadata).rects:t.changes;case"rotate":return Od(e,t)??t.changes;case"property-update":return void 0!==t.changes.rotation?{...t.changes,...Ld(e,t.changes.rotation)}:t.changes;default:return t.changes}};function ru(e,t,n,o){const i=o*Math.PI/180,r=Math.abs(Math.cos(i)),a=Math.abs(Math.sin(i)),s=r*r-a*a,l=e.size.width,c=e.size.height;let d,u;if(Math.abs(s)>1e-6)d=(r*l-a*c)/s,u=(r*c-a*l)/s,d=Math.max(d,1),u=Math.max(u,1);else{const e=t.size.width*t.size.height,o=l*c,i=e>0?Math.sqrt(o/e):1;d=n.size.width*i,u=n.size.height*i}return{origin:{x:e.origin.x+l/2-d/2,y:e.origin.y+c/2-u/2},size:{width:d,height:u}}}const au=class extends fo{constructor(e,t,n){var o,i,r;super(e,t),this.ANNOTATION_HISTORY_TOPIC="annotations",this.state$=Mo(),this.pendingContexts=new Map,this.isInitialLoadComplete=new Map,this.importQueue=new Map,this.commitInProgress=new Map,this.handlerFactories=new Map,this.activeTool$=Mo(),this.events$=Mo(),this.toolsChange$=Mo(),this.patchRegistry=new _d,this.unifiedDragStates=new Map,this.unifiedDrag$=Mo(),this.unifiedResizeStates=new Map,this.unifiedResize$=Mo(),this.unifiedRotateStates=new Map,this.unifiedRotate$=Mo(),this.config=n,this.selection=(null==(o=t.getPlugin("selection"))?void 0:o.provides())??null,this.history=(null==(i=t.getPlugin("history"))?void 0:i.provides())??null,this.interactionManager=(null==(r=t.getPlugin("interaction-manager"))?void 0:r.provides())??null,this.registerHandlerFactories(),this.registerBuiltInPatches()}onDocumentLoadingStarted(e){this.dispatch(function(e,t){return{type:Cc,payload:{documentId:e,state:t}}}(e,{pages:{},byUid:{},selectedUids:[],selectedUid:null,activeToolId:null,hasPendingChanges:!1})),this.pendingContexts.set(e,new Map),this.isInitialLoadComplete.set(e,!1),this.importQueue.set(e,[]),this.logger.debug("AnnotationPlugin","DocumentOpened",`Initialized annotation state for document: ${e}`)}onDocumentLoaded(e){const t=this.getCoreDocument(e);if((null==t?void 0:t.document)&&this.getAllAnnotations(e,t.document),this.selection)for(const e of this.state.tools)e.interaction.textSelection&&this.selection.enableForMode(e.interaction.mode??e.id,{showSelectionRects:!1,enableSelection:!0,enableMarquee:!1})}onDocumentClosed(e){this.dispatch(function(e){return{type:Ic,payload:e}}(e)),this.pendingContexts.delete(e),this.isInitialLoadComplete.delete(e),this.importQueue.delete(e),this.logger.debug("AnnotationPlugin","DocumentClosed",`Cleaned up annotation state for document: ${e}`)}registerHandlerFactories(){this.handlerFactories.set(_t.CIRCLE,Yd),this.handlerFactories.set(_t.SQUARE,Kd),this.handlerFactories.set(_t.STAMP,Zd),this.handlerFactories.set(_t.POLYGON,Vd),this.handlerFactories.set(_t.POLYLINE,Gd),this.handlerFactories.set(_t.LINE,qd),this.handlerFactories.set(_t.INK,Cd),this.handlerFactories.set(_t.FREETEXT,Wd)}registerBuiltInPatches(){this.patchRegistry.register(_t.INK,Xd),this.patchRegistry.register(_t.LINE,Qd),this.patchRegistry.register(_t.POLYLINE,Jd),this.patchRegistry.register(_t.POLYGON,eu),this.patchRegistry.register(_t.CIRCLE,tu),this.patchRegistry.register(_t.SQUARE,nu),this.patchRegistry.register(_t.FREETEXT,ou),this.patchRegistry.register(_t.STAMP,iu)}async initialize(){var e,t,n;this.state.tools.forEach(e=>this.registerInteractionForTool(e)),this.history&&this.history.onHistoryChange(e=>{e.topic===this.ANNOTATION_HISTORY_TOPIC&&!1!==this.config.autoCommit&&this.commit(e.documentId)}),null==(e=this.interactionManager)||e.onModeChange(e=>{var t,n;const o=(null==(t=this.state.tools.find(t=>(t.interaction.mode??t.id)===e.activeMode))?void 0:t.id)??null;o!==((null==(n=this.state.documents[e.documentId])?void 0:n.activeToolId)??null)&&e.documentId&&this.dispatch(Bc(e.documentId,o))}),null==(t=this.selection)||t.onMarqueeEnd(({documentId:e,pageIndex:t,rect:n,modeId:o})=>{if("pointerMode"!==o)return;const i=this.state.documents[e];if(!i)return;const r=(i.pages[t]??[]).map(e=>i.byUid[e]).filter(e=>void 0!==e).filter(e=>!sd(e)).filter(e=>function(e,t){return!(e.origin.x+e.size.widthe.object.id);if(r.length>0){const t=new Set;for(const n of r)if(this.isInGroupMethod(n,e)){const o=this.getGroupMembersMethod(n,e);for(const e of o)t.add(e.object.id)}else t.add(n);this.setSelectionMethod([...t],e)}}),null==(n=this.selection)||n.onEndSelection(({documentId:e})=>{var t,n,o;if(!this.checkPermission(e,Zt.ModifyAnnotations))return;const i=this.getActiveTool(e);if(!i||!i.interaction.textSelection)return;const r=null==(t=this.selection)?void 0:t.getFormattedSelection(),a=null==(n=this.selection)?void 0:n.getSelectedText();if(r&&a){for(const t of r)a.wait(n=>{var o,r;const a=zn();this.createAnnotation(t.pageIndex,{...i.defaults,rect:t.rect,segmentRects:t.segmentRects,pageIndex:t.pageIndex,created:new Date,id:a,custom:{text:n.join("\n")}},void 0,e),(null==(o=i.behavior)?void 0:o.deactivateToolAfterCreate)&&this.setActiveTool(null,e),(null==(r=i.behavior)?void 0:r.selectAfterCreate)&&this.selectAnnotation(t.pageIndex,a,e)},En);null==(o=this.selection)||o.clear()}})}registerInteractionForTool(e){var t;null==(t=this.interactionManager)||t.registerMode({id:e.interaction.mode??e.id,scope:"page",exclusive:e.interaction.exclusive,cursor:e.interaction.cursor})}buildCapability(){return{getActiveTool:()=>this.getActiveTool(),setActiveTool:e=>this.setActiveTool(e),getState:()=>this.getDocumentState(),getPageAnnotations:e=>this.getPageAnnotations(e),getSelectedAnnotation:()=>this.getSelectedAnnotation(),getSelectedAnnotations:()=>this.getSelectedAnnotationsMethod(),getSelectedAnnotationIds:()=>this.getSelectedAnnotationIdsMethod(),getAnnotationById:e=>this.getAnnotationById(e),selectAnnotation:(e,t)=>this.selectAnnotation(e,t),toggleSelection:(e,t)=>this.toggleSelectionMethod(e,t),addToSelection:(e,t)=>this.addToSelectionMethod(e,t),removeFromSelection:e=>this.removeFromSelectionMethod(e),setSelection:e=>this.setSelectionMethod(e),deselectAnnotation:()=>this.deselectAnnotation(),importAnnotations:e=>this.importAnnotations(e),createAnnotation:(e,t,n)=>this.createAnnotation(e,t,n),updateAnnotation:(e,t,n)=>this.updateAnnotation(e,t,n),updateAnnotations:e=>this.updateAnnotationsMethod(e),deleteAnnotation:(e,t)=>this.deleteAnnotation(e,t),deleteAnnotations:(e,t)=>this.deleteAnnotationsMethod(e,t),purgeAnnotation:(e,t,n)=>this.purgeAnnotationMethod(e,t,n),renderAnnotation:e=>this.renderAnnotation(e),commit:()=>this.commit(),getAttachedLinks:(e,t)=>this.getAttachedLinksMethod(e,t),hasAttachedLinks:(e,t)=>this.hasAttachedLinksMethod(e,t),deleteAttachedLinks:(e,t)=>this.deleteAttachedLinksMethod(e,t),groupAnnotations:e=>this.groupAnnotationsMethod(e),ungroupAnnotations:(e,t)=>this.ungroupAnnotationsMethod(e,t),getGroupMembers:(e,t)=>this.getGroupMembersMethod(e,t),isInGroup:(e,t)=>this.isInGroupMethod(e,t),forDocument:e=>this.createAnnotationScope(e),getTools:()=>this.state.tools,getTool:e=>this.getTool(e),addTool:e=>{this.dispatch((e=>({type:$c,payload:e}))(e)),this.registerInteractionForTool(e)},findToolForAnnotation:e=>this.findToolForAnnotation(e),setToolDefaults:(e,t)=>this.dispatch(((e,t)=>({type:Lc,payload:{toolId:e,patch:t}}))(e,t)),getColorPresets:()=>[...this.state.colorPresets],addColorPreset:e=>this.dispatch((e=>({type:Oc,payload:e}))(e)),transformAnnotation:(e,t)=>this.transformAnnotation(e,t),registerPatchFunction:(e,t)=>this.registerPatchFunction(e,t),onStateChange:this.state$.on,onActiveToolChange:this.activeTool$.on,onAnnotationEvent:this.events$.on,onToolsChange:this.toolsChange$.on}}createAnnotationScope(e){return{getState:()=>this.getDocumentState(e),getPageAnnotations:t=>this.getPageAnnotations(t,e),getSelectedAnnotation:()=>this.getSelectedAnnotation(e),getSelectedAnnotations:()=>this.getSelectedAnnotationsMethod(e),getSelectedAnnotationIds:()=>this.getSelectedAnnotationIdsMethod(e),getAnnotationById:t=>this.getAnnotationById(t,e),selectAnnotation:(t,n)=>this.selectAnnotation(t,n,e),toggleSelection:(t,n)=>this.toggleSelectionMethod(t,n,e),addToSelection:(t,n)=>this.addToSelectionMethod(t,n,e),removeFromSelection:t=>this.removeFromSelectionMethod(t,e),setSelection:t=>this.setSelectionMethod(t,e),deselectAnnotation:()=>this.deselectAnnotation(e),getActiveTool:()=>this.getActiveTool(e),setActiveTool:t=>this.setActiveTool(t,e),findToolForAnnotation:e=>this.findToolForAnnotation(e),importAnnotations:t=>this.importAnnotations(t,e),createAnnotation:(t,n,o)=>this.createAnnotation(t,n,o,e),updateAnnotation:(t,n,o)=>this.updateAnnotation(t,n,o,e),updateAnnotations:t=>this.updateAnnotationsMethod(t,e),deleteAnnotation:(t,n)=>this.deleteAnnotation(t,n,e),deleteAnnotations:t=>this.deleteAnnotationsMethod(t,e),purgeAnnotation:(t,n)=>this.purgeAnnotationMethod(t,n,e),renderAnnotation:t=>this.renderAnnotation(t,e),commit:()=>this.commit(e),getAttachedLinks:t=>this.getAttachedLinksMethod(t,e),hasAttachedLinks:t=>this.hasAttachedLinksMethod(t,e),deleteAttachedLinks:t=>this.deleteAttachedLinksMethod(t,e),groupAnnotations:()=>this.groupAnnotationsMethod(e),ungroupAnnotations:t=>this.ungroupAnnotationsMethod(t,e),getGroupMembers:t=>this.getGroupMembersMethod(t,e),isInGroup:t=>this.isInGroupMethod(t,e),getGroupingAction:()=>this.getGroupingActionMethod(e),onStateChange:t=>this.state$.on(n=>{n.documentId===e&&t(n.state)}),onAnnotationEvent:t=>this.events$.on(n=>{n.documentId===e&&t(n)}),onActiveToolChange:t=>this.activeTool$.on(n=>{n.documentId===e&&t(n.tool)})}}onStoreUpdated(e,t){for(const n in t.documents){const o=e.documents[n],i=t.documents[n];o!==i&&(this.state$.emit({documentId:n,state:i}),o&&o.activeToolId!==i.activeToolId&&this.activeTool$.emit({documentId:n,tool:this.getActiveTool(n)}),(null==o?void 0:o.selectedUids)!==i.selectedUids&&this.updateAnnotationSelectionActivity(n,i))}if(e.tools!==t.tools){for(const e in t.documents)this.activeTool$.emit({documentId:e,tool:this.getActiveTool(e)});this.toolsChange$.emit({tools:t.tools})}}registerPatchFunction(e,t){this.patchRegistry.register(e,t)}transformAnnotation(e,t){const n={type:t.type,changes:t.changes,metadata:t.metadata};return this.patchRegistry.transform(e,n)}registerPageHandlers(e,t,n,o){var i;const r=this.getCoreDocument(e),a=null==(i=null==r?void 0:r.document)?void 0:i.pages[t];if(!a)return()=>{};if(!this.interactionManager)return()=>{};const s=[],l=((a.rotation??0)+((null==r?void 0:r.rotation)??0))%4;for(const i of this.state.tools){if(!i.defaults.type)continue;const r=this.handlerFactories.get(i.defaults.type);if(!r)continue;const c={pageIndex:t,pageSize:a.size,pageRotation:l,scale:n,services:o.services,onPreview:e=>o.onPreview(i.id,e),onCommit:(n,o)=>{var r,a;this.createAnnotation(t,n,o,e),(null==(r=i.behavior)?void 0:r.deactivateToolAfterCreate)&&this.setActiveTool(null,e),(null==(a=i.behavior)?void 0:a.selectAfterCreate)&&this.selectAnnotation(t,n.id,e)},getTool:()=>this.state.tools.find(e=>e.id===i.id)},d=this.interactionManager.registerHandlers({documentId:e,modeId:i.interaction.mode??i.id,handlers:r.create(c),pageIndex:t});s.push(d)}return()=>s.forEach(e=>e())}getDocumentState(e){const t=e??this.getActiveDocumentId(),n=this.state.documents[t];if(!n)throw new Error(`Annotation state not found for document: ${t}`);return n}getAllAnnotations(e,t){this.engine.getAllAnnotations(t).wait(t=>{this.dispatch(((e,t)=>({type:kc,payload:{documentId:e,annotations:t}}))(e,t)),this.isInitialLoadComplete.set(e,!0);const n=this.importQueue.get(e);n&&n.length>0&&this.processImportQueue(e),this.events$.emit({type:"loaded",documentId:e,total:Object.values(t).reduce((e,t)=>e+t.length,0)})},En)}getPageAnnotations(e,t){const{pageIndex:n}=e,o=t??this.getActiveDocumentId(),i=this.getCoreDocument(o),r=null==i?void 0:i.document;if(!r)return Jt.reject({code:Qt.NotFound,message:"Document not found"});const a=r.pages.find(e=>e.index===n);return a?this.engine.getPageAnnotations(r,a):Jt.reject({code:Qt.NotFound,message:"Page not found"})}getSelectedAnnotation(e){return(e=>e.selectedUids.length>0?e.byUid[e.selectedUids[0]]??null:null)(this.getDocumentState(e))}getAnnotationById(e,t){const n=this.getDocumentState(t);return hd(n,e)}renderAnnotation({pageIndex:e,annotation:t,options:n},o){const i=o??this.getActiveDocumentId(),r=this.getCoreDocument(i),a=null==r?void 0:r.document;if(!a)return Jt.reject({code:Qt.NotFound,message:"Document not found"});const s=a.pages.find(t=>t.index===e);return s?this.engine.renderPageAnnotation(a,s,t,n):Jt.reject({code:Qt.NotFound,message:"Page not found"})}importAnnotations(e,t){const n=t??this.getActiveDocumentId();if(!this.isInitialLoadComplete.get(n)){const t=this.importQueue.get(n)||[];return t.push(...e),void this.importQueue.set(n,t)}this.processImportItems(n,e)}processImportQueue(e){const t=this.importQueue.get(e);if(!t||0===t.length)return;const n=[...t];this.importQueue.set(e,[]),this.processImportItems(e,n)}processImportItems(e,t){const n=this.pendingContexts.get(e);if(n){for(const o of t){const{annotation:t,ctx:i}=o,r=t.pageIndex,a=t.id;this.dispatch(Wc(e,r,t)),i&&n.set(a,i)}!1!==this.config.autoCommit&&this.commit(e)}}createAnnotation(e,t,n,o){const i=o??this.getActiveDocumentId();if(!this.checkPermission(i,Zt.ModifyAnnotations))return void this.logger.debug("AnnotationPlugin","CreateAnnotation",`Cannot create annotation: document ${i} lacks ModifyAnnotations permission`);const r=t.id,a=this.pendingContexts.get(i);if(!a)return;const s={...t,author:t.author??this.config.annotationAuthor},l=()=>{this.dispatch(Wc(i,e,s)),n&&a.set(r,n),this.events$.emit({type:"create",documentId:i,annotation:s,pageIndex:e,ctx:n,committed:!1})};if(!this.history)return l(),void(this.config.autoCommit&&this.commit(i));const c={execute:l,undo:()=>{a.delete(r),this.dispatch(jc(i)),this.dispatch(Gc(i,e,r)),this.events$.emit({type:"delete",documentId:i,annotation:s,pageIndex:e,committed:!1})},metadata:{annotationIds:[r]}};this.history.forDocument(i).register(c,this.ANNOTATION_HISTORY_TOPIC)}buildPatch(e,t){return"rect"in t?t:this.transformAnnotation(e,{type:"property-update",changes:t})}updateAnnotation(e,t,n,o){const i=o??this.getActiveDocumentId();if(!this.checkPermission(i,Zt.ModifyAnnotations))return void this.logger.debug("AnnotationPlugin","UpdateAnnotation",`Cannot update annotation: document ${i} lacks ModifyAnnotations permission`);const r=this.getDocumentState(i).byUid[t].object,a=this.buildPatch(r,{...n,author:n.author??this.config.annotationAuthor}),s=()=>{this.dispatch(qc(i,e,t,a)),this.events$.emit({type:"update",documentId:i,annotation:r,pageIndex:e,patch:a,committed:!1})};if(!this.history)return s(),void(!1!==this.config.autoCommit&&this.commit(i));const l=Object.fromEntries(Object.keys(n).map(e=>[e,r[e]])),c={execute:s,undo:()=>{this.dispatch(qc(i,e,t,l)),this.events$.emit({type:"update",documentId:i,annotation:r,pageIndex:e,patch:l,committed:!1})},metadata:{annotationIds:[t]}};this.history.forDocument(i).register(c,this.ANNOTATION_HISTORY_TOPIC)}deleteAnnotation(e,t,n){var o;const i=n??this.getActiveDocumentId();if(!this.checkPermission(i,Zt.ModifyAnnotations))return void this.logger.debug("AnnotationPlugin","DeleteAnnotation",`Cannot delete annotation: document ${i} lacks ModifyAnnotations permission`);const r=this.getDocumentState(i),a=null==(o=r.byUid[t])?void 0:o.object;if(!a)return;const s=((e,t)=>{const n=[];for(const o of Object.values(e.pages))for(const i of o){const o=e.byUid[i];o&&"inReplyToId"in o.object&&o.object.inReplyToId===t&&n.push({id:o.object.id,pageIndex:o.object.pageIndex})}return n})(r,t),l=s.map(e=>{var t;return null==(t=r.byUid[e.id])?void 0:t.object}).filter(e=>void 0!==e),c=()=>{var n;for(const e of s){const t=null==(n=r.byUid[e.id])?void 0:n.object;t&&(this.dispatch(Gc(i,e.pageIndex,e.id)),this.events$.emit({type:"delete",documentId:i,annotation:t,pageIndex:e.pageIndex,committed:!1}))}this.dispatch(jc(i)),this.dispatch(Gc(i,e,t)),this.events$.emit({type:"delete",documentId:i,annotation:a,pageIndex:e,committed:!1})};if(!this.history)return c(),void(!1!==this.config.autoCommit&&this.commit(i));const d={execute:c,undo:()=>{this.dispatch(Wc(i,e,a)),this.events$.emit({type:"create",documentId:i,annotation:a,pageIndex:e,committed:!1});for(const e of l)this.dispatch(Wc(i,e.pageIndex,e)),this.events$.emit({type:"create",documentId:i,annotation:e,pageIndex:e.pageIndex,committed:!1})},metadata:{annotationIds:[t,...s.map(e=>e.id)]}};this.history.forDocument(i).register(d,this.ANNOTATION_HISTORY_TOPIC)}deleteAnnotationsMethod(e,t){for(const{pageIndex:n,id:o}of e)this.deleteAnnotation(n,o,t)}purgeAnnotationMethod(e,t,n){const o=n??this.getActiveDocumentId();this.dispatch(Vc(o,e,t))}selectAnnotation(e,t,n){const o=n??this.getActiveDocumentId();if(this.isInGroupMethod(t,o)){const e=this.getGroupMembersMethod(t,o).map(e=>e.object.id);this.dispatch(Hc(o,e))}else this.dispatch(((e,t,n)=>({type:Sc,payload:{documentId:e,pageIndex:t,id:n}}))(o,e,t))}deselectAnnotation(e){const t=e??this.getActiveDocumentId();this.dispatch(jc(t))}updateAnnotationSelectionActivity(e,t){var n,o;if(0===t.selectedUids.length)return void(null==(n=this.interactionManager)||n.releasePageActivity(e,"annotation-selection"));const i=t.selectedUids[0],r=t.byUid[i];r&&(null==(o=this.interactionManager)||o.claimPageActivity(e,"annotation-selection",r.object.pageIndex))}getSelectedAnnotationsMethod(e){return dd(this.getDocumentState(e))}getSelectedAnnotationIdsMethod(e){return ud(this.getDocumentState(e))}toggleSelectionMethod(e,t,n){const o=n??this.getActiveDocumentId(),i=this.getDocumentState(o);if(i.selectedUids.includes(t))this.dispatch(Uc(o,t));else if(this.isInGroupMethod(t,o)){const e=this.getGroupMembersMethod(t,o);for(const t of e)i.selectedUids.includes(t.object.id)||this.dispatch(Fc(o,t.object.pageIndex,t.object.id))}else this.dispatch(Fc(o,e,t))}addToSelectionMethod(e,t,n){const o=n??this.getActiveDocumentId();this.dispatch(Fc(o,e,t))}removeFromSelectionMethod(e,t){const n=t??this.getActiveDocumentId();this.dispatch(Uc(n,e))}setSelectionMethod(e,t){const n=t??this.getActiveDocumentId();this.dispatch(Hc(n,e))}getAttachedLinksMethod(e,t){return gd(this.getDocumentState(t),e)}hasAttachedLinksMethod(e,t){return this.getAttachedLinksMethod(e,t).length>0}deleteAttachedLinksMethod(e,t){const n=this.getAttachedLinksMethod(e,t);for(const e of n)this.deleteAnnotation(e.object.pageIndex,e.object.id,t)}groupAnnotationsMethod(e){const t=e??this.getActiveDocumentId();if(!this.checkPermission(t,Zt.ModifyAnnotations))return void this.logger.debug("AnnotationPlugin","GroupAnnotations",`Cannot group annotations: document ${t} lacks ModifyAnnotations permission`);const n=this.getSelectedAnnotationsMethod(t);if(n.length<2)return void this.logger.debug("AnnotationPlugin","GroupAnnotations","Need at least 2 annotations to group");const o=n[0],i=n.slice(1).map(e=>({pageIndex:e.object.pageIndex,id:e.object.id,patch:{inReplyToId:o.object.id,replyType:$t.Group}}));this.updateAnnotationsMethod(i,t)}ungroupAnnotationsMethod(e,t){const n=t??this.getActiveDocumentId();if(!this.checkPermission(n,Zt.ModifyAnnotations))return void this.logger.debug("AnnotationPlugin","UngroupAnnotations",`Cannot ungroup annotations: document ${n} lacks ModifyAnnotations permission`);const o=this.getGroupMembersMethod(e,n).filter(e=>e.object.inReplyToId&&e.object.replyType===$t.Group).map(e=>({pageIndex:e.object.pageIndex,id:e.object.id,patch:{inReplyToId:void 0,replyType:void 0}}));o.length>0&&this.updateAnnotationsMethod(o,n)}getGroupMembersMethod(e,t){return pd(this.getDocumentState(t),e)}isInGroupMethod(e,t){return fd(this.getDocumentState(t),e)}getGroupingActionMethod(e){return(e=>{const t=dd(e);if(0===t.length)return"disabled";const n=t[0].object.id;if(fd(e,n)){const o=pd(e,n),i=new Set(o.map(e=>e.object.id));if(t.every(e=>i.has(e.object.id)))return"ungroup"}return t.length>=2?"group":"disabled"})(this.getDocumentState(e))}computeCombinedConstraints(e){let t=1/0,n=1/0,o=1/0,i=1/0;for(const r of e){const e=r.rect.origin.y,a=r.pageSize.height-(r.rect.origin.y+r.rect.size.height),s=r.rect.origin.x,l=r.pageSize.width-(r.rect.origin.x+r.rect.size.width);t=Math.min(t,e),n=Math.min(n,a),o=Math.min(o,s),i=Math.min(i,l)}return isFinite(t)||(t=0),isFinite(n)||(n=0),isFinite(o)||(o=0),isFinite(i)||(i=0),{maxUp:t,maxDown:n,maxLeft:o,maxRight:i}}clampDelta(e,t){return{x:Math.max(-t.maxLeft,Math.min(t.maxRight,e.x)),y:Math.max(-t.maxUp,Math.min(t.maxDown,e.y))}}startDrag(e,t){const{annotationIds:n,pageSize:o}=t,i=[];for(const t of n){const n=this.getAttachedLinksMethod(t,e);for(const e of n)i.includes(e.object.id)||i.push(e.object.id)}const r=[...n,...i],a=new Map,s=[];for(const t of r){const n=this.getAnnotationById(t,e);n&&(a.set(t,{...n.object.rect}),s.push({id:t,rect:n.object.rect,pageIndex:n.object.pageIndex,pageSize:o}))}const l={documentId:e,isDragging:!0,primaryIds:n,attachedLinkIds:i,allParticipantIds:r,originalRects:a,delta:{x:0,y:0},combinedConstraints:this.computeCombinedConstraints(s)};this.unifiedDragStates.set(e,l),this.unifiedDrag$.emit({documentId:e,type:"start",state:l,previewPatches:{}})}computeDragPreviewPatches(e,t){const n={};for(const o of e.allParticipantIds){const i=this.getAnnotationById(o,t);if(!i)continue;const r=e.originalRects.get(o);if(!r)continue;const a={...r,origin:{x:r.origin.x+e.delta.x,y:r.origin.y+e.delta.y}};n[o]=this.transformAnnotation(i.object,{type:"move",changes:{rect:a}})}return n}updateDrag(e,t){const n=this.unifiedDragStates.get(e);if(!(null==n?void 0:n.isDragging))return{x:0,y:0};const o=this.clampDelta(t,n.combinedConstraints),i={...n,delta:o};this.unifiedDragStates.set(e,i);const r=this.computeDragPreviewPatches(i,e);return this.unifiedDrag$.emit({documentId:e,type:"update",state:i,previewPatches:r}),o}commitDrag(e){const t=this.unifiedDragStates.get(e);if(!t)return;const n=t.delta;if(0!==n.x||0!==n.y){const o=[];for(const i of t.allParticipantIds){const r=this.getAnnotationById(i,e);if(!r)continue;const a=t.originalRects.get(i)??r.object.rect,s={...a,origin:{x:a.origin.x+n.x,y:a.origin.y+n.y}},l=this.transformAnnotation(r.object,{type:"move",changes:{rect:s}});o.push({pageIndex:r.object.pageIndex,id:i,patch:l})}o.length>0&&this.updateAnnotationsMethod(o,e)}const o=this.computeDragPreviewPatches(t,e);this.unifiedDrag$.emit({documentId:e,type:"end",state:{...t,isDragging:!1},previewPatches:o}),this.unifiedDragStates.delete(e)}cancelDrag(e){const t=this.unifiedDragStates.get(e);t&&(this.unifiedDrag$.emit({documentId:e,type:"cancel",state:{...t,isDragging:!1,delta:{x:0,y:0}},previewPatches:{}}),this.unifiedDragStates.delete(e))}getDragState(e){return this.unifiedDragStates.get(e)??null}get onDragChange(){return this.unifiedDrag$.on}computeUnifiedGroupBoundingBox(e){if(0===e.length)return{origin:{x:0,y:0},size:{width:0,height:0}};let t=1/0,n=1/0,o=-1/0,i=-1/0;for(const r of e)t=Math.min(t,r.origin.x),n=Math.min(n,r.origin.y),o=Math.max(o,r.origin.x+r.size.width),i=Math.max(i,r.origin.y+r.size.height);return{origin:{x:t,y:n},size:{width:o-t,height:i-n}}}computeUnifiedRelativePositions(e,t){return e.map(e=>({id:e.id,originalRect:e.rect,originalUnrotatedRect:e.unrotatedRect,pageIndex:e.pageIndex,isAttachedLink:e.isAttachedLink,parentId:e.parentId,relativeX:t.size.width>0?(e.rect.origin.x-t.origin.x)/t.size.width:0,relativeY:t.size.height>0?(e.rect.origin.y-t.origin.y)/t.size.height:0,relativeWidth:t.size.width>0?e.rect.size.width/t.size.width:1,relativeHeight:t.size.height>0?e.rect.size.height/t.size.height:1}))}computeUnifiedResizedRects(e,t,n=10){const o=new Map;for(const i of e){const e=Math.max(n,i.relativeWidth*t.size.width),r=Math.max(n,i.relativeHeight*t.size.height);o.set(i.id,{origin:{x:t.origin.x+i.relativeX*t.size.width,y:t.origin.y+i.relativeY*t.size.height},size:{width:e,height:r}})}return o}computeResizePreviewPatches(e,t){const n={},o=this.unifiedResizeStates.get(t),i=o?new Map(o.participatingAnnotations.map(e=>[e.id,e])):void 0;for(const[r,a]of e){const e=this.getAnnotationById(r,t);if(!e)continue;let s=a;const l=null==i?void 0:i.get(r);(null==o?void 0:o.isGroupResize)&&(null==l?void 0:l.originalUnrotatedRect)&&(s=ru(a,l.originalRect,l.originalUnrotatedRect,e.object.rotation??0)),n[r]=this.transformAnnotation(e.object,{type:"resize",changes:{rect:s}})}return n}startResize(e,t){const{annotationIds:n,pageSize:o,resizeHandle:i}=t,r=[],a=[];for(const t of n){const n=this.getAnnotationById(t,e);if(n){a.push({id:t,rect:n.object.rect,unrotatedRect:n.object.unrotatedRect?this.cloneRect(n.object.unrotatedRect):void 0,pageIndex:n.object.pageIndex,isAttachedLink:!1});const o=this.getAttachedLinksMethod(t,e);for(const e of o)r.includes(e.object.id)||(r.push(e.object.id),a.push({id:e.object.id,rect:e.object.rect,unrotatedRect:e.object.unrotatedRect?this.cloneRect(e.object.unrotatedRect):void 0,pageIndex:e.object.pageIndex,isAttachedLink:!0,parentId:t}))}}const s=[...n,...r],l=a.map(e=>e.rect),c=this.computeUnifiedGroupBoundingBox(l),d=this.computeUnifiedRelativePositions(a,c),u=this.computeUnifiedResizedRects(d,c),h={documentId:e,isResizing:!0,isGroupResize:n.length>1,primaryIds:n,attachedLinkIds:r,allParticipantIds:s,originalGroupBox:c,currentGroupBox:c,participatingAnnotations:d,resizeHandle:i,computedRects:u};this.unifiedResizeStates.set(e,h);const m=this.computeResizePreviewPatches(u,e);this.unifiedResize$.emit({documentId:e,type:"start",state:h,computedRects:Object.fromEntries(u),previewPatches:m})}updateResize(e,t){const n=this.unifiedResizeStates.get(e);if(!(null==n?void 0:n.isResizing))return{};const o=this.computeUnifiedResizedRects(n.participatingAnnotations,t),i={...n,currentGroupBox:t,computedRects:o};this.unifiedResizeStates.set(e,i);const r=Object.fromEntries(o),a=this.computeResizePreviewPatches(o,e);return this.unifiedResize$.emit({documentId:e,type:"update",state:i,computedRects:r,previewPatches:a}),r}commitResize(e){const t=this.unifiedResizeStates.get(e);if(!t)return;const n=this.computeUnifiedResizedRects(t.participatingAnnotations,t.currentGroupBox),o=[],i=new Map(t.participatingAnnotations.map(e=>[e.id,e]));for(const[r,a]of n){const n=this.getAnnotationById(r,e);if(!n)continue;let s=a;const l=i.get(r);t.isGroupResize&&(null==l?void 0:l.originalUnrotatedRect)&&(s=ru(a,l.originalRect,l.originalUnrotatedRect,n.object.rotation??0));const c=this.transformAnnotation(n.object,{type:"resize",changes:{rect:s}});o.push({pageIndex:n.object.pageIndex,id:r,patch:c})}o.length>0&&this.updateAnnotationsMethod(o,e);const r=this.computeResizePreviewPatches(n,e);this.unifiedResize$.emit({documentId:e,type:"end",state:{...t,isResizing:!1},computedRects:Object.fromEntries(n),previewPatches:r}),this.unifiedResizeStates.delete(e)}cancelResize(e){const t=this.unifiedResizeStates.get(e);if(!t)return;const n=this.computeUnifiedResizedRects(t.participatingAnnotations,t.originalGroupBox);this.unifiedResize$.emit({documentId:e,type:"cancel",state:{...t,isResizing:!1,currentGroupBox:t.originalGroupBox},computedRects:Object.fromEntries(n),previewPatches:{}}),this.unifiedResizeStates.delete(e)}getResizeState(e){return this.unifiedResizeStates.get(e)??null}get onResizeChange(){return this.unifiedResize$.on}cloneRect(e){return{origin:{x:e.origin.x,y:e.origin.y},size:{width:e.size.width,height:e.size.height}}}translateRect(e,t){return{origin:{x:e.origin.x+t.x,y:e.origin.y+t.y},size:{...e.size}}}normalizeAngle(e){const t=e%360;return t<0?t+360:t}normalizeDelta(e){return(e+540)%360-180}buildRotationParticipants(e,t){const n=[],o=[];for(const i of e){const e=this.getAnnotationById(i,t);if(!e)continue;n.push({id:i,rect:this.cloneRect(e.object.rect),pageIndex:e.object.pageIndex,rotation:e.object.rotation??0,unrotatedRect:e.object.unrotatedRect?this.cloneRect(e.object.unrotatedRect):void 0,isAttachedLink:!1});const r=this.getAttachedLinksMethod(i,t);for(const e of r)o.includes(e.object.id)||(o.push(e.object.id),n.push({id:e.object.id,rect:this.cloneRect(e.object.rect),pageIndex:e.object.pageIndex,rotation:e.object.rotation??0,unrotatedRect:e.object.unrotatedRect?this.cloneRect(e.object.unrotatedRect):void 0,isAttachedLink:!0,parentId:i}))}return{participants:n,attachedLinkIds:o}}computeRotatePreviewPatches(e,t){const n={};for(const o of e.participants){const i=this.getAnnotationById(o.id,t);if(!i)continue;const r=zd({rect:o.rect,unrotatedRect:o.unrotatedRect,rotation:o.rotation}),a=lt(r,e.rotationCenter,e.delta),s={x:a.x-r.x,y:a.y-r.y},l=this.normalizeAngle(o.rotation+e.delta),c=this.transformAnnotation(i.object,{type:"rotate",changes:{rotation:l,unrotatedRect:this.translateRect(o.unrotatedRect??o.rect,s)},metadata:{rotationAngle:l,rotationDelta:e.delta,rotationCenter:e.rotationCenter}});c.rect||0===s.x&&0===s.y||(c.rect={origin:{x:i.object.rect.origin.x+s.x,y:i.object.rect.origin.y+s.y},size:{...i.object.rect.size}}),n[o.id]=c}return n}startRotation(e,t){const{annotationIds:n,cursorAngle:o,rotationCenter:i}=t,{participants:r,attachedLinkIds:a}=this.buildRotationParticipants(n,e);if(0===r.length)return;const s=r.map(e=>e.rect),l=this.computeUnifiedGroupBoundingBox(s),c=i??{x:l.origin.x+l.size.width/2,y:l.origin.y+l.size.height/2},d={documentId:e,isRotating:!0,primaryIds:n,attachedLinkIds:a,allParticipantIds:r.map(e=>e.id),rotationCenter:c,cursorStartAngle:o,currentAngle:o,delta:0,participants:r};this.unifiedRotateStates.set(e,d);const u=this.computeRotatePreviewPatches(d,e);this.unifiedRotate$.emit({documentId:e,type:"start",state:d,previewPatches:u})}updateRotation(e,t,n){const o=this.unifiedRotateStates.get(e);if(!(null==o?void 0:o.isRotating))return;const i=void 0!==n?n:this.normalizeDelta(t-o.cursorStartAngle),r={...o,currentAngle:t,delta:i};this.unifiedRotateStates.set(e,r);const a=this.computeRotatePreviewPatches(r,e);this.unifiedRotate$.emit({documentId:e,type:"update",state:r,previewPatches:a})}commitRotation(e){const t=this.unifiedRotateStates.get(e);if(!t)return;const n=this.computeRotatePreviewPatches(t,e),o=[];for(const[t,i]of Object.entries(n)){const n=this.getAnnotationById(t,e);n&&o.push({pageIndex:n.object.pageIndex,id:t,patch:i})}o.length>0&&this.updateAnnotationsMethod(o,e),this.unifiedRotate$.emit({documentId:e,type:"end",state:{...t,isRotating:!1},previewPatches:n}),this.unifiedRotateStates.delete(e)}cancelRotation(e){const t=this.unifiedRotateStates.get(e);t&&(this.unifiedRotate$.emit({documentId:e,type:"cancel",state:{...t,isRotating:!1,delta:0,currentAngle:t.cursorStartAngle},previewPatches:{}}),this.unifiedRotateStates.delete(e))}getRotateState(e){return this.unifiedRotateStates.get(e)??null}get onRotateChange(){return this.unifiedRotate$.on}updateAnnotationsMethod(e,t){const n=t??this.getActiveDocumentId();if(!this.checkPermission(n,Zt.ModifyAnnotations))return void this.logger.debug("AnnotationPlugin","UpdateAnnotations",`Cannot update annotations: document ${n} lacks ModifyAnnotations permission`);const o=this.getDocumentState(n),i=e.map(({pageIndex:e,id:t,patch:n})=>{var i;const r=null==(i=o.byUid[t])?void 0:i.object;if(!r)return null;return{pageIndex:e,id:t,patch:this.buildPatch(r,{...n,author:n.author??this.config.annotationAuthor}),originalObject:r}}).filter(e=>null!==e);if(0===i.length)return;const r=()=>{for(const{pageIndex:e,id:t,patch:o,originalObject:r}of i)this.dispatch(qc(n,e,t,o)),this.events$.emit({type:"update",documentId:n,annotation:r,pageIndex:e,patch:o,committed:!1})};if(!this.history)return r(),void(!1!==this.config.autoCommit&&this.commit(n));const a=i.map(({pageIndex:e,id:t,patch:n,originalObject:o})=>({pageIndex:e,id:t,originalPatch:Object.fromEntries(Object.keys(n).map(e=>[e,o[e]])),originalObject:o})),s={execute:r,undo:()=>{for(const{pageIndex:e,id:t,originalPatch:o,originalObject:i}of a)this.dispatch(qc(n,e,t,o)),this.events$.emit({type:"update",documentId:n,annotation:i,pageIndex:e,patch:o,committed:!1})},metadata:{annotationIds:i.map(e=>e.id)}};this.history.forDocument(n).register(s,this.ANNOTATION_HISTORY_TOPIC)}getActiveTool(e){const t=this.getDocumentState(e);return t.activeToolId?this.state.tools.find(e=>e.id===t.activeToolId)??null:null}setActiveTool(e,t){var n,o;const i=t??this.getActiveDocumentId();if(null!==e&&!this.checkPermission(i,Zt.ModifyAnnotations))return void this.logger.debug("AnnotationPlugin","SetActiveTool",`Cannot activate tool: document ${i} lacks ModifyAnnotations permission`);const r=this.getDocumentState(i);if(e===r.activeToolId)return;this.dispatch(Bc(i,e));const a=this.state.tools.find(t=>t.id===e);a?null==(n=this.interactionManager)||n.forDocument(i).activate(a.interaction.mode??a.id):null==(o=this.interactionManager)||o.forDocument(i).activateDefaultMode()}getTool(e){return this.state.tools.find(t=>t.id===e)}findToolForAnnotation(e){let t=null,n=0;for(const o of this.state.tools){const i=o.matchScore(e);i>n&&(n=i,t=o)}return t}collectPendingChanges(e,t){const n=this.getDocumentState(e),o=this.pendingContexts.get(e),i={creations:[],updates:[],deletions:[],committedUids:[],isEmpty:!0};for(const[e,r]of Object.entries(n.byUid)){if("synced"===r.commitState)continue;const n=t.pages.find(e=>e.index===r.object.pageIndex);if(n)switch(i.committedUids.push(e),i.isEmpty=!1,r.commitState){case"new":i.creations.push({uid:e,ta:r,ctx:null==o?void 0:o.get(r.object.id)});break;case"dirty":i.updates.push({uid:e,ta:r});break;case"deleted":i.deletions.push({uid:e,ta:r})}}return i}executeCommitBatch(e,t,n){const o=new Ct,i=this.pendingContexts.get(e),r=[];for(const{uid:e,ta:o,ctx:i}of n.creations){const n=t.pages.find(e=>e.index===o.object.pageIndex);if(!n)continue;const a=this.engine.createPageAnnotation(t,n,o.object,i);r.push({type:"create",task:a,ta:o,uid:e,ctx:i})}for(const{uid:e,ta:o}of n.updates){const n=t.pages.find(e=>e.index===o.object.pageIndex);if(!n)continue;const i=this.engine.updatePageAnnotation(t,n,o.object);r.push({type:"update",task:i,ta:o,uid:e})}for(const{uid:o,ta:i}of n.deletions){const n=t.pages.find(e=>e.index===i.object.pageIndex);if(n)if(i.object.id){const e=new Ct;this.engine.removePageAnnotation(t,n,i.object).wait(()=>e.resolve(!0),e.fail),r.push({type:"delete",task:e,ta:i,uid:o})}else this.dispatch(Vc(e,i.object.pageIndex,o))}const a=r.map(e=>e.task);return Ct.allSettled(a).wait(()=>{var t,a;this.emitCommitEvents(e,r,i),this.dispatch((t=e,a=n.committedUids,{type:_c,payload:{documentId:t,committedUids:a}})),o.resolve(!0)},e=>o.fail(e)),o}emitCommitEvents(e,t,n){for(const o of t)if(o.task.state.stage===bt.Resolved)switch(o.type){case"create":this.events$.emit({type:"create",documentId:e,annotation:o.ta.object,pageIndex:o.ta.object.pageIndex,ctx:o.ctx,committed:!0}),null==n||n.delete(o.ta.object.id);break;case"update":this.events$.emit({type:"update",documentId:e,annotation:o.ta.object,pageIndex:o.ta.object.pageIndex,patch:o.ta.object,committed:!0});break;case"delete":this.dispatch(Vc(e,o.ta.object.pageIndex,o.uid)),this.events$.emit({type:"delete",documentId:e,annotation:o.ta.object,pageIndex:o.ta.object.pageIndex,committed:!0})}}acquireCommitLock(e){return!this.commitInProgress.get(e)&&(this.commitInProgress.set(e,!0),!0)}releaseCommitLock(e){this.commitInProgress.set(e,!1)}commit(e){const t=e??this.getActiveDocumentId();if(!this.getDocumentState(t).hasPendingChanges)return Jt.resolve(!0);if(!this.acquireCommitLock(t))return Jt.resolve(!0);const n=this.getCoreDocument(t),o=null==n?void 0:n.document;if(!o)return this.releaseCommitLock(t),Jt.reject({code:Qt.NotFound,message:"Document not found"});const i=this.collectPendingChanges(t,o);if(i.isEmpty)return this.releaseCommitLock(t),Jt.resolve(!0);const r=new Ct;return this.executeCommitBatch(t,o,i).wait(()=>{this.releaseCommitLock(t);this.getDocumentState(t).hasPendingChanges?this.commit(t).wait(e=>r.resolve(e),e=>r.fail(e)):r.resolve(!0)},e=>{this.releaseCommitLock(t),r.fail(e)}),r}};au.id="annotation";let su=au;function lu(e,t,n){return void 0===e?n:"function"==typeof e?e(t):e}function cu(e){return t=>(null==t?void 0:t.id)===e}const du=cu("highlight"),uu=cu("squiggly"),hu=cu("underline"),mu=cu("strikeout"),gu={manifest:xc,create:(e,t)=>new su(wc,e,t),reducer:(e,t)=>{switch(t.type){case Cc:{const{documentId:n,state:o}=t.payload;return{...e,documents:{...e.documents,[n]:o},activeDocumentId:e.activeDocumentId??n}}case Ic:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i,activeDocumentId:e.activeDocumentId===n?null:e.activeDocumentId}}case"ANNOTATION/SET_ACTIVE_DOCUMENT":return{...e,activeDocumentId:t.payload};case kc:{const{documentId:n,annotations:o}=t.payload,i=e.documents[n];if(!i)return e;const r={},a={};for(const[e,t]of Object.entries(o)){const n=Number(e),o=i.pages[n]||[];for(const e of o)delete a[e];const s=t.map(e=>{const t=e.id;return a[t]={commitState:"synced",object:e},t});r[n]=s}return{...e,documents:{...e.documents,[n]:{...i,pages:r,byUid:a}}}}case Sc:{const{documentId:n,id:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,selectedUids:[o],selectedUid:o}}}:e}case Mc:{const{documentId:n}=t.payload,o=e.documents[n];return o?{...e,documents:{...e.documents,[n]:{...o,selectedUids:[],selectedUid:null}}}:e}case Ac:{const{documentId:n,id:o}=t.payload,i=e.documents[n];if(!i)return e;if(i.selectedUids.includes(o))return e;const r=[...i.selectedUids,o];return{...e,documents:{...e.documents,[n]:{...i,selectedUids:r,selectedUid:bd(r)}}}}case Pc:{const{documentId:n,id:o}=t.payload,i=e.documents[n];if(!i)return e;const r=i.selectedUids.filter(e=>e!==o);return{...e,documents:{...e.documents,[n]:{...i,selectedUids:r,selectedUid:bd(r)}}}}case Dc:{const{documentId:n,ids:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,selectedUids:o,selectedUid:bd(o)}}}:e}case Rc:{const{documentId:n,toolId:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,activeToolId:o}}}:e}case zc:{const{documentId:n,pageIndex:o,annotation:i}=t.payload,r=e.documents[n];if(!r)return e;const a=i.id;return{...e,documents:{...e.documents,[n]:{...r,pages:{...r.pages,[o]:[...r.pages[o]??[],a]},byUid:{...r.byUid,[a]:{commitState:"new",object:i}},hasPendingChanges:!0}}}}case Ec:{const{documentId:n,pageIndex:o,id:i}=t.payload,r=e.documents[n];return r&&r.byUid[i]?{...e,documents:{...e.documents,[n]:{...r,pages:{...r.pages,[o]:(r.pages[o]??[]).filter(e=>e!==i)},byUid:{...r.byUid,[i]:{...r.byUid[i],commitState:"deleted"}},hasPendingChanges:!0}}}:e}case Tc:{const{documentId:n,id:o,patch:i}=t.payload,r=e.documents[n];return r?{...e,documents:{...e.documents,[n]:wd(r,o,i)}}:e}case _c:{const{documentId:n,committedUids:o}=t.payload,i=e.documents[n];if(!i)return e;const r=new Set(o),a={};let s=!1;for(const[e,t]of Object.entries(i.byUid))r.has(e)?a[e]={...t,commitState:"dirty"===t.commitState||"new"===t.commitState?"synced":t.commitState}:(a[e]=t,"new"!==t.commitState&&"dirty"!==t.commitState&&"deleted"!==t.commitState||(s=!0));return{...e,documents:{...e.documents,[n]:{...i,byUid:a,hasPendingChanges:s}}}}case Nc:{const{documentId:n,pageIndex:o,uid:i}=t.payload,r=e.documents[n];if(!r||!r.byUid[i])return e;const{[i]:a,...s}=r.byUid;return{...e,documents:{...e.documents,[n]:{...r,pages:{...r.pages,[o]:(r.pages[o]??[]).filter(e=>e!==i)},byUid:s}}}}case $c:{const n=new Map(e.tools.map(e=>[e.id,e]));return n.set(t.payload.id,t.payload),{...e,tools:Array.from(n.values())}}case Lc:{const{toolId:n,patch:o}=t.payload;return{...e,tools:e.tools.map(e=>e.id===n?{...e,defaults:{...e.defaults,...o}}:e)}}case Oc:return e.colorPresets.includes(t.payload)?e:{...e,colorPresets:[...e.colorPresets,t.payload]};default:return e}},initialState:(e,t)=>(e=>{const t=new Map;vd.forEach(e=>t.set(e.id,e));const n=new Map(t);(e.tools||[]).forEach(e=>{const o=t.get(e.id);o?n.set(e.id,{...o,...e,defaults:{...o.defaults,...e.defaults},interaction:{...o.interaction,...e.interaction},behavior:{...o.behavior,...e.behavior},...o.clickBehavior||e.clickBehavior?{clickBehavior:{...o.clickBehavior,...e.clickBehavior}}:{}}):n.set(e.id,e)});const o=Array.from(n.values()).map(t=>{var n,o;return{...t,behavior:{...t.behavior,deactivateToolAfterCreate:(null==(n=t.behavior)?void 0:n.deactivateToolAfterCreate)??e.deactivateToolAfterCreate??!1,selectAfterCreate:(null==(o=t.behavior)?void 0:o.selectAfterCreate)??e.selectAfterCreate??!0}}});return{documents:{},activeDocumentId:null,tools:o,colorPresets:e.colorPresets??yd}})(t)};function pu(e,t){for(var n in e)if("__source"!==n&&!(n in t))return!0;for(var o in t)if("__source"!==o&&e[o]!==t[o])return!0;return!1}function fu(e,t){this.props=e,this.context=t}(fu.prototype=new B).isPureReactComponent=!0,fu.prototype.shouldComponentUpdate=function(e,t){return pu(this.props,e)||pu(this.state,t)};var vu=I.__b;I.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),vu&&vu(e)};var yu=I.__e;I.__e=function(e,t,n,o){if(e.then)for(var i,r=t;r=r.__;)if((i=r.__c)&&i.__c)return null==t.__e&&(t.__e=n.__e,t.__k=n.__k),i.__c(e,t);yu(e,t,n,o)};var bu=I.unmount;function wu(e,t,n){return e&&(e.__c&&e.__c.__H&&(e.__c.__H.__.forEach(function(e){"function"==typeof e.__c&&e.__c()}),e.__c.__H=null),null!=(e=function(e,t){for(var n in t)e[n]=t[n];return e}({},e)).__c&&(e.__c.__P===n&&(e.__c.__P=t),e.__c.__e=!0,e.__c=null),e.__k=e.__k&&e.__k.map(function(e){return wu(e,t,n)})),e}function xu(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(e){return xu(e,t,n)}),e.__c&&e.__c.__P===t&&(e.__e&&n.appendChild(e.__e),e.__c.__e=!0,e.__c.__P=n)),e}function Cu(){this.__u=0,this.o=null,this.__b=null}function Iu(e){if(!e.__)return null;var t=e.__.__c;return t&&t.__a&&t.__a(e)}function ku(){this.i=null,this.l=null}I.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),bu&&bu(e)},(Cu.prototype=new B).__c=function(e,t){var n=t.__c,o=this;null==o.o&&(o.o=[]),o.o.push(n);var i=Iu(o.__v),r=!1,a=function(){r||o.__z||(r=!0,n.__R=null,i?i(l):l())};n.__R=a;var s=n.__P;n.__P=null;var l=function(){if(! --o.__u){if(o.state.__a){var e=o.state.__a;o.__v.__k[0]=xu(e,e.__c.__P,e.__c.__O)}var t;for(o.setState({__a:o.__b=null});t=o.o.pop();)t.__P=s,t.forceUpdate()}};o.__u++||32&t.__u||o.setState({__a:o.__b=o.__v.__k[0]}),e.then(a,a)},Cu.prototype.componentWillUnmount=function(){this.o=[]},Cu.prototype.render=function(e,t){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),o=this.__v.__k[0].__c;this.__v.__k[0]=wu(this.__b,n,o.__O=o.__P)}this.__b=null}var i=t.__a&&F(H,null,e.fallback);return i&&(i.__u&=-33),[F(H,null,t.__a?null:e.children),i]};var Su=function(e,t,n){if(++n[1]===n[0]&&e.l.delete(t),e.props.revealOrder&&("t"!==e.props.revealOrder[0]||!e.l.size))for(n=e.i;n;){for(;n.length>3;)n.pop()();if(n[1]>>1,1),t.h.removeChild(e)}}}ce(F(Mu,{context:t.context},e.__v),t.v)}function Pu(e,t){var n=F(Au,{__v:e,h:t});return n.containerInfo=t,n}(ku.prototype=new B).__a=function(e){var t=this,n=Iu(t.__v),o=t.l.get(e);return o[0]++,function(i){var r=function(){t.props.revealOrder?(o.push(i),Su(t,e,o)):i()};n?n(r):r()}},ku.prototype.render=function(e){this.i=null,this.l=new Map;var t=Y(e.children);e.revealOrder&&"b"===e.revealOrder[0]&&t.reverse();for(var n=t.length;n--;)this.l.set(t[n],this.i=[1,0,this.i]);return e.children},ku.prototype.componentDidUpdate=ku.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){Su(e,n,t)})};var Du="undefined"!=typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103,Ru=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,zu=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Tu=/[A-Z0-9]/g,Eu="undefined"!=typeof document,_u=function(e){return("undefined"!=typeof Symbol&&"symbol"==typeof Symbol()?/fil|che|rad/:/fil|che|ra/).test(e)};B.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(B.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var Nu=I.event;function Ou(){}function Lu(){return this.cancelBubble}function $u(){return this.defaultPrevented}I.event=function(e){return Nu&&(e=Nu(e)),e.persist=Ou,e.isPropagationStopped=Lu,e.isDefaultPrevented=$u,e.nativeEvent=e};var ju={enumerable:!1,configurable:!0,get:function(){return this.class}},Fu=I.vnode;I.vnode=function(e){"string"==typeof e.type&&function(e){var t=e.props,n=e.type,o={},i=-1===n.indexOf("-");for(var r in t){var a=t[r];if(!("value"===r&&"defaultValue"in t&&null==a||Eu&&"children"===r&&"noscript"===n||"class"===r||"className"===r)){var s=r.toLowerCase();"defaultValue"===r&&"value"in t&&null==t.value?r="value":"download"===r&&!0===a?a="":"translate"===s&&"no"===a?a=!1:"o"===s[0]&&"n"===s[1]?"ondoubleclick"===s?r="ondblclick":"onchange"!==s||"input"!==n&&"textarea"!==n||_u(t.type)?"onfocus"===s?r="onfocusin":"onblur"===s?r="onfocusout":zu.test(r)&&(r=s):s=r="oninput":i&&Ru.test(r)?r=r.replace(Tu,"-$&").toLowerCase():null===a&&(a=void 0),"oninput"===s&&o[r=s]&&(r="oninputCapture"),o[r]=a}}"select"==n&&o.multiple&&Array.isArray(o.value)&&(o.value=Y(t.children).forEach(function(e){e.props.selected=-1!=o.value.indexOf(e.props.value)})),"select"==n&&null!=o.defaultValue&&(o.value=Y(t.children).forEach(function(e){e.props.selected=o.multiple?-1!=o.defaultValue.indexOf(e.props.value):o.defaultValue==e.props.value})),t.class&&!t.className?(o.class=t.class,Object.defineProperty(o,"className",ju)):(t.className&&!t.class||t.class&&t.className)&&(o.class=o.className=t.className),e.props=o}(e),e.$$typeof=Du,Fu&&Fu(e)};var Uu=I.__r;I.__r=function(e){Uu&&Uu(e),e.__c};var Hu=I.diffed;I.diffed=function(e){Hu&&Hu(e);var t=e.props,n=e.__e;null!=n&&"textarea"===e.type&&"value"in t&&t.value!==n.value&&(n.value=null==t.value?"":t.value)};const Bu="INTERACTION/INIT_STATE",Wu="INTERACTION/CLEANUP_STATE",qu="INTERACTION/ACTIVATE_MODE",Gu="INTERACTION/PAUSE",Vu="INTERACTION/RESUME",Ku="INTERACTION/SET_CURSOR",Zu="INTERACTION/SET_DEFAULT_MODE",Yu="INTERACTION/SET_EXCLUSION_RULES",Xu="INTERACTION/ADD_EXCLUSION_CLASS",Qu="INTERACTION/REMOVE_EXCLUSION_CLASS",Ju="INTERACTION/ADD_EXCLUSION_ATTRIBUTE",eh="INTERACTION/REMOVE_EXCLUSION_ATTRIBUTE";function th(e){return{type:Zu,payload:{mode:e}}}function nh(e){return{type:Yu,payload:{rules:e}}}const oh="pointerMode",ih=class extends fo{constructor(e,t,n){super(e,t),this.modes=new Map,this.cursorClaims=new Map,this.buckets=new Map,this.alwaysGlobal=new Map,this.alwaysPage=new Map,this.pageActivities=new Map,this.onModeChange$=So(),this.onHandlerChange$=So(),this.onCursorChange$=So(),this.onStateChange$=Mo(),this.onPageActivityChange$=So(),this.registerMode({id:oh,scope:"page",exclusive:!1,cursor:"auto"}),this.dispatch(th(oh)),n.exclusionRules&&this.dispatch(nh(n.exclusionRules))}onDocumentLoadingStarted(e){const t={activeMode:this.state.defaultMode,cursor:"auto",paused:!1};this.dispatch(function(e,t){return{type:Bu,payload:{documentId:e,state:t}}}(e,t)),this.cursorClaims.set(e,new Map),this.buckets.set(e,new Map),this.alwaysGlobal.set(e,new Set),this.alwaysPage.set(e,new Map),this.pageActivities.set(e,new Map);const n=this.buckets.get(e);for(const e of this.modes.keys())n.set(e,{global:new Set,page:new Map});this.logger.debug("InteractionManagerPlugin","DocumentOpened",`Initialized interaction state for document: ${e}`)}onDocumentClosed(e){const t=this.pageActivities.get(e);if(t){const n=new Set(t.values());t.clear();for(const t of n)this.onPageActivityChange$.emit({documentId:e,pageIndex:t,hasActivity:!1})}this.cursorClaims.delete(e),this.buckets.delete(e),this.alwaysGlobal.delete(e),this.alwaysPage.delete(e),this.pageActivities.delete(e),this.dispatch(function(e){return{type:Wu,payload:e}}(e)),this.logger.debug("InteractionManagerPlugin","DocumentClosed",`Cleaned up interaction state for document: ${e}`)}buildCapability(){return{getActiveMode:()=>this.getActiveMode(),getActiveInteractionMode:()=>this.getActiveInteractionMode(),activate:e=>this.activate(e),activateDefaultMode:()=>this.activateDefaultMode(),setCursor:(e,t,n)=>this.setCursor(e,t,n),getCurrentCursor:()=>this.getCurrentCursor(),removeCursor:e=>this.removeCursor(e),getHandlersForScope:e=>this.getHandlersForScope(e),activeModeIsExclusive:()=>this.activeModeIsExclusive(),pause:()=>this.pause(),resume:()=>this.resume(),isPaused:()=>this.registry.isDestroyed()||this.isPaused(),getState:()=>this.getDocumentStateOrThrow(),forDocument:e=>this.createInteractionScope(e),registerMode:e=>this.registerMode(e),registerHandlers:e=>this.registerHandlers(e),registerAlways:e=>this.registerAlways(e),setDefaultMode:e=>this.setDefaultMode(e),getDefaultMode:()=>this.state.defaultMode,getExclusionRules:()=>this.state.exclusionRules,setExclusionRules:e=>this.dispatch(nh(e)),addExclusionClass:e=>this.dispatch(function(e){return{type:Xu,payload:{className:e}}}(e)),removeExclusionClass:e=>this.dispatch(function(e){return{type:Qu,payload:{className:e}}}(e)),addExclusionAttribute:e=>this.dispatch(function(e){return{type:Ju,payload:{attribute:e}}}(e)),removeExclusionAttribute:e=>this.dispatch(function(e){return{type:eh,payload:{attribute:e}}}(e)),claimPageActivity:(e,t,n)=>this.claimPageActivity(e,t,n),releasePageActivity:(e,t)=>this.releasePageActivity(e,t),hasPageActivity:(e,t)=>this.hasPageActivity(e,t),onModeChange:this.onModeChange$.on,onCursorChange:this.onCursorChange$.on,onHandlerChange:this.onHandlerChange$.on,onStateChange:this.onStateChange$.on,onPageActivityChange:this.onPageActivityChange$.on}}createInteractionScope(e){return{getActiveMode:()=>this.getActiveMode(e),getActiveInteractionMode:()=>this.getActiveInteractionMode(e),activate:t=>this.activate(t,e),activateDefaultMode:()=>this.activateDefaultMode(e),setCursor:(t,n,o)=>this.setCursor(t,n,o,e),getCurrentCursor:()=>this.getCurrentCursor(e),removeCursor:t=>this.removeCursor(t,e),getHandlersForScope:e=>this.getHandlersForScope(e),activeModeIsExclusive:()=>this.activeModeIsExclusive(e),pause:()=>this.pause(e),resume:()=>this.resume(e),isPaused:()=>this.isPaused(e),getState:()=>this.getDocumentStateOrThrow(e),claimPageActivity:(t,n)=>this.claimPageActivity(e,t,n),releasePageActivity:t=>this.releasePageActivity(e,t),hasPageActivity:t=>this.hasPageActivity(e,t),onModeChange:t=>this.onModeChange$.on(n=>{n.documentId===e&&t(n.activeMode)}),onCursorChange:t=>this.onCursorChange$.on(n=>{n.documentId===e&&t(n.cursor)}),onStateChange:t=>this.onStateChange$.on(n=>{n.documentId===e&&t(n.state)}),onPageActivityChange:t=>this.onPageActivityChange$.on(n=>{n.documentId===e&&t({pageIndex:n.pageIndex,hasActivity:n.hasActivity})})}}getDocumentState(e){const t=e??this.getActiveDocumentId();return this.state.documents[t]??null}getDocumentStateOrThrow(e){const t=this.getDocumentState(e);if(!t)throw new Error(`Interaction state not found for document: ${e??"active"}`);return t}activate(e,t){var n;const o=t??this.getActiveDocumentId(),i=this.getDocumentStateOrThrow(o);if(!this.modes.has(e))throw new Error(`[interaction] unknown mode '${e}'`);if(e===i.activeMode)return;const r=i.activeMode;null==(n=this.cursorClaims.get(o))||n.clear(),this.notifyHandlersInactive(o,r),this.dispatch(function(e,t){return{type:qu,payload:{documentId:e,mode:t}}}(o,e)),this.emitCursor(o),this.notifyHandlersActive(o,e),this.onModeChange$.emit({documentId:o,activeMode:e,previousMode:r})}activateDefaultMode(e){const t=e??this.getActiveDocumentIdOrNull();t&&this.activate(this.state.defaultMode,t)}setDefaultMode(e){if(!this.modes.has(e))throw new Error(`[interaction] cannot set unknown mode '${e}' as default`);this.dispatch(th(e))}getActiveMode(e){return this.getDocumentStateOrThrow(e).activeMode}getActiveInteractionMode(e){const t=this.getDocumentState(e);return t?this.modes.get(t.activeMode)??null:null}activeModeIsExclusive(e){const t=this.getActiveInteractionMode(e);return!!(null==t?void 0:t.exclusive)}pause(e){const t=e??this.getActiveDocumentId();this.dispatch(function(e){return{type:Gu,payload:e}}(t))}resume(e){const t=e??this.getActiveDocumentId();this.dispatch(function(e){return{type:Vu,payload:e}}(t))}isPaused(e){return this.getDocumentStateOrThrow(e).paused}registerMode(e){this.modes.set(e.id,e);for(const t of this.buckets.keys()){const n=this.buckets.get(t);n.has(e.id)||n.set(e.id,{global:new Set,page:new Map})}}registerHandlers({documentId:e,modeId:t,handlers:n,pageIndex:o}){const i=Array.isArray(t)?t:[t],r=[],a=this.buckets.get(e);if(!a)throw new Error(`No buckets found for document: ${e}`);for(const e of i){const t=a.get(e);if(!t)throw new Error(`unknown mode '${e}'`);if(null==o)t.global.add(n);else{const e=t.page.get(o)??new Set;e.add(n),t.page.set(o,e)}r.push(()=>{if(null==o)t.global.delete(n);else{const e=t.page.get(o);e&&(e.delete(n),0===e.size&&t.page.delete(o))}})}return this.onHandlerChange$.emit({...this.state}),()=>{r.forEach(e=>e()),this.onHandlerChange$.emit({...this.state})}}registerAlways({scope:e,handlers:t}){if("global"===e.type){const n=this.alwaysGlobal.get(e.documentId)??new Set;return n.add(t),this.alwaysGlobal.set(e.documentId,n),this.onHandlerChange$.emit({...this.state}),()=>{n.delete(t),this.onHandlerChange$.emit({...this.state})}}const n=this.alwaysPage.get(e.documentId)??new Map,o=n.get(e.pageIndex)??new Set;return o.add(t),n.set(e.pageIndex,o),this.alwaysPage.set(e.documentId,n),this.onHandlerChange$.emit({...this.state}),()=>{o.delete(t),this.onHandlerChange$.emit({...this.state})}}getHandlersForScope(e){var t;const n=this.getDocumentState(e.documentId);if(!n)return null;const o=this.modes.get(n.activeMode);if(!o)return null;const i=this.buckets.get(e.documentId);if(!i)return null;const r=i.get(o.id);if(!r)return null;const a=(e,t)=>e.size||t.size?function(e){const t=["onPointerDown","onPointerUp","onPointerMove","onPointerEnter","onPointerLeave","onPointerCancel","onMouseDown","onMouseUp","onMouseMove","onMouseEnter","onMouseLeave","onMouseCancel","onClick","onDoubleClick"],n={};for(const o of t)n[o]=(t,n,i)=>{var r;for(const a of e){if(n.isImmediatePropagationStopped())break;null==(r=a[o])||r.call(a,t,n,i)}};return n}([...e,...t]):null;if("global"===e.type){return a(this.alwaysGlobal.get(e.documentId)??new Set,"global"===o.scope?r.global:new Set)}return a((null==(t=this.alwaysPage.get(e.documentId))?void 0:t.get(e.pageIndex))??new Set,"page"===o.scope?r.page.get(e.pageIndex)??new Set:new Set)}setCursor(e,t,n=0,o){const i=o??this.getActiveDocumentId(),r=this.cursorClaims.get(i);r&&(r.set(e,{cursor:t,priority:n}),this.emitCursor(i))}removeCursor(e,t){const n=t??this.getActiveDocumentId(),o=this.cursorClaims.get(n);o&&(o.delete(e),this.emitCursor(n))}getCurrentCursor(e){return this.getDocumentStateOrThrow(e).cursor}emitCursor(e){var t;const n=this.cursorClaims.get(e);if(!n)return;const o=this.getDocumentState(e);if(!o)return;const i=[...n.values()].sort((e,t)=>t.priority-e.priority)[0]??{cursor:(null==(t=this.modes.get(o.activeMode))?void 0:t.cursor)??"auto"};i.cursor!==o.cursor&&(this.dispatch(function(e,t){return{type:Ku,payload:{documentId:e,cursor:t}}}(e,i.cursor)),this.onCursorChange$.emit({documentId:e,cursor:i.cursor}))}claimPageActivity(e,t,n){let o=this.pageActivities.get(e);o||(o=new Map,this.pageActivities.set(e,o));const i=o.get(t);i!==n&&(o.set(t,n),void 0===i||this.pageHasAnyTopic(e,i)||this.onPageActivityChange$.emit({documentId:e,pageIndex:i,hasActivity:!1}),1===this.countTopicsOnPage(e,n)&&this.onPageActivityChange$.emit({documentId:e,pageIndex:n,hasActivity:!0}))}releasePageActivity(e,t){const n=this.pageActivities.get(e);if(!n)return;const o=n.get(t);void 0!==o&&(n.delete(t),this.pageHasAnyTopic(e,o)||this.onPageActivityChange$.emit({documentId:e,pageIndex:o,hasActivity:!1}))}hasPageActivity(e,t){return this.pageHasAnyTopic(e,t)}pageHasAnyTopic(e,t){const n=this.pageActivities.get(e);if(!n)return!1;for(const e of n.values())if(e===t)return!0;return!1}countTopicsOnPage(e,t){const n=this.pageActivities.get(e);if(!n)return 0;let o=0;for(const e of n.values())e===t&&o++;return o}notifyHandlersActive(e,t){var n,o;null==(n=this.alwaysGlobal.get(e))||n.forEach(e=>{var n;null==(n=e.onHandlerActiveStart)||n.call(e,t)}),null==(o=this.alwaysPage.get(e))||o.forEach(e=>{e.forEach(e=>{var n;null==(n=e.onHandlerActiveStart)||n.call(e,t)})});const i=this.modes.get(t);if(!i)return;const r=this.buckets.get(e);if(!r)return;const a=r.get(t);a&&("global"===i.scope&&a.global.forEach(e=>{var n;null==(n=e.onHandlerActiveStart)||n.call(e,t)}),"page"===i.scope&&a.page.forEach(e=>{e.forEach(e=>{var n;null==(n=e.onHandlerActiveStart)||n.call(e,t)})}))}notifyHandlersInactive(e,t){var n,o;null==(n=this.alwaysGlobal.get(e))||n.forEach(e=>{var n;null==(n=e.onHandlerActiveEnd)||n.call(e,t)}),null==(o=this.alwaysPage.get(e))||o.forEach(e=>{e.forEach(e=>{var n;null==(n=e.onHandlerActiveEnd)||n.call(e,t)})});const i=this.modes.get(t);if(!i)return;const r=this.buckets.get(e);if(!r)return;const a=r.get(t);a&&("global"===i.scope&&a.global.forEach(e=>{var n;null==(n=e.onHandlerActiveEnd)||n.call(e,t)}),"page"===i.scope&&a.page.forEach(e=>{e.forEach(e=>{var n;null==(n=e.onHandlerActiveEnd)||n.call(e,t)})}))}onStoreUpdated(e,t){for(const n in t.documents){const o=e.documents[n],i=t.documents[n];o!==i&&this.onStateChange$.emit({documentId:n,state:i})}}async initialize(e){this.logger.info("InteractionManagerPlugin","Initialize","Interaction Manager Plugin initialized")}async destroy(){this.pageActivities.clear(),this.onModeChange$.clear(),this.onCursorChange$.clear(),this.onHandlerChange$.clear(),this.onStateChange$.clear(),this.onPageActivityChange$.clear(),await super.destroy()}};ih.id="interaction-manager";let rh=ih;const ah="interaction-manager",sh={defaultMode:"pointerMode",exclusionRules:{classes:[],dataAttributes:["data-no-interaction"]},documents:{},activeDocumentId:null},lh={manifest:{id:ah,name:"Interaction Manager Plugin",version:"1.0.0",provides:["interaction-manager"],requires:[],optional:[],defaultConfig:{exclusionRules:{classes:[],dataAttributes:["data-no-interaction"]}}},create:(e,t)=>new rh(ah,e,t),reducer:(e=sh,t)=>{switch(t.type){case Bu:{const{documentId:n,state:o}=t.payload;return{...e,documents:{...e.documents,[n]:o},activeDocumentId:e.activeDocumentId??n}}case Wu:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i,activeDocumentId:e.activeDocumentId===n?null:e.activeDocumentId}}case"INTERACTION/SET_ACTIVE_DOCUMENT":return{...e,activeDocumentId:t.payload};case qu:{const{documentId:n,mode:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,activeMode:o}}}:e}case Ku:{const{documentId:n,cursor:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,cursor:o}}}:e}case Gu:{const n=t.payload,o=e.documents[n];return o?{...e,documents:{...e.documents,[n]:{...o,paused:!0}}}:e}case Vu:{const n=t.payload,o=e.documents[n];return o?{...e,documents:{...e.documents,[n]:{...o,paused:!1}}}:e}case Zu:return{...e,defaultMode:t.payload.mode};case Yu:return{...e,exclusionRules:t.payload.rules};case Xu:return{...e,exclusionRules:{...e.exclusionRules,classes:[...e.exclusionRules.classes||[],t.payload.className].filter((e,t,n)=>n.indexOf(e)===t)}};case Qu:return{...e,exclusionRules:{...e.exclusionRules,classes:(e.exclusionRules.classes||[]).filter(e=>e!==t.payload.className)}};case Ju:return{...e,exclusionRules:{...e.exclusionRules,dataAttributes:[...e.exclusionRules.dataAttributes||[],t.payload.attribute].filter((e,t,n)=>n.indexOf(e)===t)}};case eh:return{...e,exclusionRules:{...e.exclusionRules,dataAttributes:(e.exclusionRules.dataAttributes||[]).filter(e=>e!==t.payload.attribute)}};default:return e}},initialState:sh},ch=()=>_o(rh.id);const dh={pointerdown:"onPointerDown",pointerup:"onPointerUp",pointermove:"onPointerMove",pointerenter:"onPointerEnter",pointerleave:"onPointerLeave",pointercancel:"onPointerCancel",mousedown:"onMouseDown",mouseup:"onMouseUp",mousemove:"onMouseMove",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",mousecancel:"onMouseCancel",click:"onClick",dblclick:"onDoubleClick",touchstart:"onPointerDown",touchend:"onPointerUp",touchmove:"onPointerMove",touchcancel:"onPointerCancel"},uh=["pointerdown","pointerup","pointermove","pointerenter","pointerleave","pointercancel","mousedown","mouseup","mousemove","mouseenter","mouseleave","mousecancel","click","dblclick"],hh="undefined"!=typeof PointerEvent?uh:[...uh,"touchstart","touchend","touchmove","touchcancel"];function mh(e){return"undefined"!=typeof TouchEvent&&e instanceof TouchEvent}function gh(e,t,n,o){const i=e.forDocument(t.documentId);let r=e.getHandlersForScope(t);const a=()=>{var e;return!1!==(null==(e=i.getActiveInteractionMode())?void 0:e.wantsRawTouch)},s={};let l=a();const c=e=>{hh.forEach(t=>{const o=s[t]??(s[t]=v);var i;n.addEventListener(t,o,(i=e,t.startsWith("touch")?{passive:!i}:{passive:!1}))})},d=()=>{hh.forEach(e=>{const t=s[e];t&&n.removeEventListener(e,t)})};c(l),n.style.touchAction=l?"none":"";const u=i.onModeChange(()=>{if("global"===t.type){const e=i.getActiveInteractionMode();n.style.cursor="global"===(null==e?void 0:e.scope)?e.cursor??"auto":"auto"}r=e.getHandlersForScope(t);const o=a();o!==l&&(d(),c(o),l=o,n.style.touchAction=l?"none":"")}),h=e.onHandlerChange(()=>{r=e.getHandlersForScope(t)}),m=i.getActiveInteractionMode(),g=i.getCurrentCursor();n.style.cursor="global"===t.type&&"global"!==(null==m?void 0:m.scope)?"auto":g;const p=i.onCursorChange(e=>{var o;"global"===t.type&&"global"!==(null==(o=i.getActiveInteractionMode())?void 0:o.scope)||(n.style.cursor=e)}),f=(e,t)=>{if(o)return o(e,t);const n=t.getBoundingClientRect();return{x:e.clientX-n.left,y:e.clientY-n.top}};function v(t){var o;if(e.isPaused())return;const a=e.getExclusionRules();if(t.target&&function(e,t){var n,o,i;if(!e)return!1;let r=e;for(;r;){if(null==(n=t.classes)?void 0:n.length)for(const e of t.classes)if(null==(o=r.classList)?void 0:o.contains(e))return!0;if(null==(i=t.dataAttributes)?void 0:i.length)for(const e of t.dataAttributes)if(r.hasAttribute(e))return!0;r=r.parentElement}return!1}(t.target,a))return;const s=dh[t.type];if(!s||!(null==r?void 0:r[s]))return;let c,d;mh(t)&&l&&("touchmove"===t.type||"touchcancel"===t.type)&&t.preventDefault();let u=!1;if(mh(t)){const e="touchend"===t.type||"touchcancel"===t.type?t.changedTouches[0]:t.touches[0];if(!e)return;c=f(e,n),d={clientX:e.clientX,clientY:e.clientY,ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,target:t.target,currentTarget:t.currentTarget,setPointerCapture:()=>{},releasePointerCapture:()=>{},stopImmediatePropagation:()=>{u=!0},isImmediatePropagationStopped:()=>u}}else{const e=t;c=f(e,n),d={clientX:e.clientX,clientY:e.clientY,ctrlKey:e.ctrlKey,shiftKey:e.shiftKey,altKey:e.altKey,metaKey:e.metaKey,target:e.target,currentTarget:e.currentTarget,setPointerCapture:()=>{var t,n;null==(n=null==(t=e.target)?void 0:t.setPointerCapture)||n.call(t,e.pointerId)},releasePointerCapture:()=>{var t,n;null==(n=null==(t=e.target)?void 0:t.releasePointerCapture)||n.call(t,e.pointerId)},stopImmediatePropagation:()=>{u=!0},isImmediatePropagationStopped:()=>u}}null==(o=r[s])||o.call(r,c,d,i.getActiveMode())}return()=>{d(),u(),p(),h()}}const ph=({children:e,documentId:t,style:n,...o})=>{const i=De(null),{provides:r}=ch();return Ae(()=>{if(r&&i.current)return gh(r,{type:"global",documentId:t},i.current)},[r,t]),He("div",{ref:i,style:{width:"100%",height:"100%",...n},...o,children:e})},fh=({documentId:e,pageIndex:t,children:n,rotation:o,scale:i,convertEventToPoint:r,style:a,...s})=>{var l,c;const d=De(null),{provides:u}=ch(),h=function(e){const{provides:t}=ch(),[n,o]=Se(()=>{if(!t)return!1;const n=t.forDocument(e).getActiveInteractionMode();return"page"===(null==n?void 0:n.scope)&&!!n.exclusive});return Ae(()=>{if(!t)return;const n=t.forDocument(e);return n.onModeChange(()=>{const e=n.getActiveInteractionMode();o("page"===(null==e?void 0:e.scope)&&!!(null==e?void 0:e.exclusive))})},[t,e]),n}(e),m=Oo(e),g=null==(c=null==(l=null==m?void 0:m.document)?void 0:l.pages)?void 0:c[t],p=(null==g?void 0:g.size)??{width:0,height:0},f=(null==g?void 0:g.rotation)??0,v=(null==m?void 0:m.rotation)??0,y=void 0!==o?o:(f+v)%4,b=i??(null==m?void 0:m.scale)??1,w=Ke(p,0,b),x=ze((e,t)=>{const n=t.getBoundingClientRect(),o={x:e.clientX-n.left,y:e.clientY-n.top};return function(e,t,n,o){return Qe(Xe(e,t,(4-n)%4),1/o)}(Ke({width:w.width,height:w.height},y,1),o,y,b)},[p,y,b]);return Ae(()=>{if(u&&d.current)return gh(u,{type:"page",documentId:e,pageIndex:t},d.current,r||x)},[u,e,t,r,x]),He("div",{ref:d,style:{position:"relative",width:w.width,height:w.height,...a},...s,children:[n,h&&He("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10}})]})},vh={},yh=de(null),bh=de([]);const wh=()=>Eo(su.id),xh=()=>_o(su.id),Ch=e=>{var t;const{provides:n}=xh(),[o,i]=Se((null==(t=null==n?void 0:n.forDocument(e))?void 0:t.getState())??{pages:{},byUid:{},selectedUids:[],selectedUid:null,activeToolId:null,hasPendingChanges:!1});return Ae(()=>{if(!n)return;const t=n.forDocument(e);return i(t.getState()),t.onStateChange(e=>{i(e)})},[n,e]),{state:o,provides:(null==n?void 0:n.forDocument(e))??null}};function Ih({scale:e,documentId:t,pageIndex:n,rotation:o,pageWidth:i,pageHeight:r,trackedAnnotation:a,children:s,isSelected:l,isMultiSelected:c=!1,isDraggable:d,isResizable:u,isRotatable:h=!0,lockAspectRatio:m=!1,style:g={},vertexConfig:p,selectionMenu:f,outlineOffset:v=1,onDoubleClick:y,onSelect:b,zIndex:w=1,resizeUI:x,vertexUI:C,rotationUI:I,selectionOutlineColor:k,selectionOutline:S,customAnnotationRenderer:M,groupSelectionMenu:A,groupSelectionOutline:P,annotationRenderers:D,...R}){var z,T,E;const[_,N]=Se(a.object),[O,L]=Se(null),[$,j]=Se(null),[F,U]=Se(!1),{provides:B}=xh(),{plugin:W}=wh(),{canModifyAnnotations:q}=Uo(t),G=De(null),V=q&&d&&!c,K=q&&u&&!c,Z=q&&h&&!c,Y=Re(()=>B?B.forDocument(t):null,[B,t]),X=_?{...a.object,..._}:a.object,Q=(null==x?void 0:x.color)??"#007ACC",J=(null==C?void 0:C.color)??"#007ACC",ee=(null==I?void 0:I.color)??"white",te=(null==I?void 0:I.connectorColor)??"#007ACC",ne=(null==x?void 0:x.size)??12,oe=(null==C?void 0:C.size)??12,ie=(null==I?void 0:I.size)??32,re=null==I?void 0:I.margin,ae=(null==I?void 0:I.iconColor)??"#007ACC",se=(null==I?void 0:I.showConnector)??!1,le=(null==(z=null==I?void 0:I.border)?void 0:z.color)??"#007ACC",ce=(null==(T=null==I?void 0:I.border)?void 0:T.width)??1,de=(null==(E=null==I?void 0:I.border)?void 0:E.style)??"solid",ue=(null==S?void 0:S.color)??k??"#007ACC",he=(null==S?void 0:S.style)??"solid",me=(null==S?void 0:S.width)??1,ge=(null==S?void 0:S.offset)??v??1,pe=O??X.rotation??0,fe=O??X.rotation??0,ve=Number.isFinite(fe)?Math.round(10*fe)/10:0,ye=null!==O,be=De(null),we=ze(e=>{var o;if(!(null==(o=e.transformData)?void 0:o.type)||c||!W)return;const{type:s,changes:l,metadata:d}=e.transformData,u=a.object.id,h={width:i,height:r};if("start"===e.state&&(be.current=a.object.unrotatedRect??a.object.rect,G.current=a.object,"move"===s?W.startDrag(t,{annotationIds:[u],pageSize:h}):"resize"===s&&W.startResize(t,{annotationIds:[u],pageSize:h,resizeHandle:(null==d?void 0:d.handle)??"se"})),l.rect&&be.current)if("move"===s){const e={x:l.rect.origin.x-be.current.origin.x,y:l.rect.origin.y-be.current.origin.y};W.updateDrag(t,e)}else"resize"===s&&W.updateResize(t,l.rect);if("vertex-edit"===s&&l.vertices&&p){const t=G.current??a.object,o=p.transformAnnotation(t,l.vertices),i=null==B?void 0:B.transformAnnotation(t,{type:s,changes:o,metadata:d});i&&(N(e=>({...e,...i})),"end"===e.state&&(null==Y||Y.updateAnnotation(n,u,i)))}if("rotate"===s){const n=(null==d?void 0:d.rotationAngle)??pe,o=null==d?void 0:d.cursorPosition;return o&&j({x:o.clientX,y:o.clientY}),void("start"===e.state?(L(n),W.startRotation(t,{annotationIds:[u],cursorAngle:n,rotationCenter:null==d?void 0:d.rotationCenter})):"move"===e.state?(L(n),W.updateRotation(t,n,null==d?void 0:d.rotationDelta)):"end"===e.state&&(L(null),j(null),W.commitRotation(t)))}"end"===e.state&&(be.current=null,G.current=null,"move"===s?W.commitDrag(t):"resize"===s&&W.commitResize(t))},[W,t,a.object,i,r,n,c,p,B,Y,pe]),xe=X.unrotatedRect,Ce=xe??X.rect,Ie=xe&&0!==pe?ht(Ce,X.rect,pe):void 0,ke=Ce,{dragProps:Me,vertices:Pe,resize:Te,rotation:Ee}=Ol({controller:{element:ke,vertices:null==p?void 0:p.extractVertices(X),constraints:{minWidth:10,minHeight:10,boundingBox:{width:i,height:r}},maintainAspectRatio:m,pageRotation:o,annotationRotation:pe,rotationCenter:Ie,rotationElement:X.rect,scale:e,enabled:l&&!c,onUpdate:we},resizeUI:{handleSize:ne,spacing:ge,offsetMode:"outside",includeSides:!m,zIndex:w+1},vertexUI:{vertexSize:oe,zIndex:w+2},rotationUI:{handleSize:ie,margin:re,zIndex:w+3,showConnector:se},includeVertices:!!p,includeRotation:Z,currentRotation:pe}),_e=function(e,{delay:t=300,tolerancePx:n=18}={}){const o=De({t:0,x:0,y:0}),i=ze(i=>{if(!e)return;if("mouse"===i.pointerType||!1===i.isPrimary)return;const r=performance.now(),a=i.clientX,s=i.clientY,l=r-o.current.t<=t,c=a-o.current.x,d=s-o.current.y;l&&c*c+d*d<=n*n&&(null==e||e(i)),o.current={t:r,x:a,y:s}},[e,t,n]),r=ze(t=>{null==e||e(t)},[e]);return e?{[Ml]:r,onPointerUpCapture:i}:{}}(Re(()=>{if(q&&y)return y},[q,y]));Ae(()=>{N(a.object)},[a.object]),Ae(()=>{if(!W)return;const e=a.object.id,n=n=>{var o;if(n.documentId!==t)return;"end"!==n.type&&"cancel"!==n.type||L(null);const i=null==(o=n.previewPatches)?void 0:o[e];"update"===n.type&&i?N(e=>({...e,...i})):"cancel"===n.type&&N(a.object)},o=[W.onDragChange(n),W.onResizeChange(n),W.onRotateChange(n)];return()=>o.forEach(e=>e())},[W,t,a.object]);const Ne=l&&!c,Oe=X.rect.size.width*e,Le=X.rect.size.height*e,$e=Ce.size.width*e,je=Ce.size.height*e,Fe=Boolean(xe)&&0!==pe,Ue=Fe?(Ce.origin.x-X.rect.origin.x)*e:(Oe-$e)/2,Be=Fe?(Ce.origin.y-X.rect.origin.y)*e:(Le-je)/2,We=Fe&&Ie?`${(Ie.x-Ce.origin.x)*e}px ${(Ie.y-Ce.origin.y)*e}px`:"center center",qe=Ie?(Ie.x-X.rect.origin.x)*e:Oe/2,Ge=Ie?(Ie.y-X.rect.origin.y)*e:Le/2,Ve=Math.max(300,Math.max(Oe,Le)+80),Ke=Re(()=>xe?{...X,rect:xe}:X,[X,xe]);return He("div",{"data-no-interaction":!0,children:[He("div",{style:{position:"absolute",left:X.rect.origin.x*e,top:X.rect.origin.y*e,width:Oe,height:Le,pointerEvents:"none",zIndex:w,...g},...R,children:[ye&&He(H,{children:[He("div",{style:{position:"absolute",left:qe-Ve/2,top:Ge,width:Ve,height:1,backgroundColor:te,opacity:.35,pointerEvents:"none"}}),He("div",{style:{position:"absolute",left:qe,top:Ge-Ve/2,width:1,height:Ve,backgroundColor:te,opacity:.35,pointerEvents:"none"}}),He("div",{style:{position:"absolute",left:qe-Ve/2,top:Ge,width:Ve,height:1,transformOrigin:"center center",transform:`rotate(${pe}deg)`,backgroundColor:te,opacity:.8,pointerEvents:"none"}})]}),l&&Z&&Ee&&((null==I?void 0:I.component)?He("div",{onPointerEnter:()=>U(!0),onPointerLeave:()=>{U(!1),j(null)},onPointerMove:e=>{ye||j({x:e.clientX,y:e.clientY})},style:{display:"contents"},children:I.component({...Ee.handle,backgroundColor:ee,iconColor:ae,connectorStyle:{...Ee.connector.style,backgroundColor:te,opacity:ye?0:1},showConnector:se,opacity:ye?0:1,border:{color:le,width:ce,style:de}})}):He("div",{onPointerEnter:()=>U(!0),onPointerLeave:()=>{U(!1),j(null)},onPointerMove:e=>{ye||j({x:e.clientX,y:e.clientY})},style:{display:"contents"},children:[se&&He("div",{style:{...Ee.connector.style,backgroundColor:te,opacity:ye?0:1}}),He("div",{...Ee.handle,style:{...Ee.handle.style,backgroundColor:ee,border:`${ce}px ${de} ${le}`,boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"auto",opacity:ye?0:1},children:He("svg",{width:Math.round(.6*ie),height:Math.round(.6*ie),viewBox:"0 0 24 24",fill:"none",stroke:ae,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[He("path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}),He("path",{d:"M21 3v5h-5"})]})})]})),He("div",{...V&&l?Me:{},..._e,style:{position:"absolute",left:Ue,top:Be,width:$e,height:je,transform:0!==pe?`rotate(${pe}deg)`:void 0,transformOrigin:We,outline:Ne?`${me}px ${he} ${ue}`:"none",outlineOffset:Ne?`${ge}px`:"0px",pointerEvents:l&&!c?"auto":"none",touchAction:"none",cursor:l&&V?"move":"default"},children:[(()=>{const t="function"==typeof s?s(Ke):s,a=null==M?void 0:M({annotation:Ke,children:t,isSelected:l,scale:e,rotation:o,pageWidth:i,pageHeight:r,pageIndex:n,onSelect:b});return null!=a?a:t})(),l&&K&&!ye&&Te.map(({key:e,...t})=>(null==x?void 0:x.component)?x.component({key:e,...t,backgroundColor:Q}):He("div",{...t,style:{...t.style,backgroundColor:Q}},e)),l&&q&&!c&&!ye&&Pe.map(({key:e,...t})=>(null==C?void 0:C.component)?C.component({key:e,...t,backgroundColor:J}):He("div",{...t,style:{...t.style,backgroundColor:J}},e))]})]}),f&&!c&&!ye&&He(Al,{rect:{origin:{x:X.rect.origin.x*e,y:X.rect.origin.y*e},size:{width:X.rect.size.width*e,height:X.rect.size.height*e}},rotation:o,children:e=>{const t=((pe+90*o)%360+360)%360;return f({...e,context:{type:"annotation",annotation:a,pageIndex:n},selected:l,placement:{suggestTop:Z&&t>90&&t<270}})}}),(ye||F)&&$&&Pu(He("div",{style:{position:"fixed",left:$.x+16,top:$.y-16,background:"rgba(0,0,0,0.8)",color:"#fff",padding:"4px 8px",borderRadius:4,fontSize:12,fontFamily:"monospace",pointerEvents:"none",zIndex:1e4,whiteSpace:"nowrap"},children:[ve.toFixed(0),"°"]}),document.body)]})}function kh({documentId:e,pageIndex:t,scale:n,rotation:o,pageWidth:i,pageHeight:r,selectedAnnotations:a,isDraggable:s,isResizable:l,isRotatable:c=!0,lockAspectRatio:d=!1,resizeUI:u,rotationUI:h,selectionOutlineColor:m,outlineOffset:g,selectionOutline:p,zIndex:f=2,groupSelectionMenu:v}){var y,b,w;const{plugin:x}=wh(),{canModifyAnnotations:C}=Uo(e),I=De(null),k=De(!1),S=De(!1),[M,A]=Se(null),[P,D]=Se(null),[R,z]=Se(!1),T=C&&s,E=C&&l,_=C&&c,N=Re(()=>function(e){return rt(e)??it}(a.map(e=>e.object.rect)),[a]),[O,L]=Se(N);Ae(()=>{k.current||S.current||L(N)},[N]),Ae(()=>{if(!x)return;return x.onRotateChange(t=>{t.documentId===e&&("end"!==t.type&&"cancel"!==t.type||A(null))})},[x,e]);const $=ze(t=>{var n,o,s,l,d,u;if(!(null==(n=t.transformData)?void 0:n.type))return;if(!x)return;const h=t.transformData.type,m="move"===h,g="resize"===h;if(m&&!T)return;if("start"===t.state&&(I.current=N,m?(k.current=!0,x.startDrag(e,{annotationIds:a.map(e=>e.object.id),pageSize:{width:i,height:r}})):g&&(S.current=!0,x.startResize(e,{annotationIds:a.map(e=>e.object.id),pageSize:{width:i,height:r},resizeHandle:(null==(o=t.transformData.metadata)?void 0:o.handle)??"se"}))),"rotate"===h){if(!c)return;const n=a.map(e=>e.object.id),o=(null==(s=t.transformData.metadata)?void 0:s.rotationAngle)??0,i=null==(l=t.transformData.metadata)?void 0:l.cursorPosition;return i&&D({x:i.clientX,y:i.clientY}),void("start"===t.state?(A(o),x.startRotation(e,{annotationIds:n,cursorAngle:o,rotationCenter:null==(d=t.transformData.metadata)?void 0:d.rotationCenter})):"move"===t.state?(A(o),x.updateRotation(e,o,null==(u=t.transformData.metadata)?void 0:u.rotationDelta)):"end"===t.state&&(A(null),D(null),x.commitRotation(e)))}const p=I.current??N;if(m&&t.transformData.changes.rect){const n=t.transformData.changes.rect,o={x:n.origin.x-p.origin.x,y:n.origin.y-p.origin.y},i=x.updateDrag(e,o);L({...p,origin:{x:p.origin.x+i.x,y:p.origin.y+i.y}})}else if(g&&t.transformData.changes.rect){const n=t.transformData.changes.rect;x.updateResize(e,n),L(n)}"end"===t.state&&(I.current=null,m&&k.current?(k.current=!1,x.commitDrag(e)):g&&S.current&&(S.current=!1,x.commitResize(e)))},[x,e,i,r,N,T,a,c]),j=M??0,F=null!==M,U=Number.isFinite(j)?Math.round(10*j)/10:0,B=(null==u?void 0:u.color)??"#007ACC",W=(null==u?void 0:u.size)??12,q=(null==h?void 0:h.color)??"white",G=(null==h?void 0:h.connectorColor)??"#007ACC",V=(null==h?void 0:h.size)??32,K=null==h?void 0:h.margin,Z=(null==h?void 0:h.iconColor)??"#007ACC",Y=(null==h?void 0:h.showConnector)??!1,X=(null==(y=null==h?void 0:h.border)?void 0:y.color)??"#007ACC",Q=(null==(b=null==h?void 0:h.border)?void 0:b.width)??1,J=(null==(w=null==h?void 0:h.border)?void 0:w.style)??"solid",ee=(null==p?void 0:p.color)??m??"#007ACC",te=(null==p?void 0:p.style)??"dashed",ne=(null==p?void 0:p.width)??2,oe=(null==p?void 0:p.offset)??g??2,{dragProps:ie,resize:re,rotation:ae}=Ol({controller:{element:O,constraints:{minWidth:20,minHeight:20,boundingBox:{width:i,height:r}},maintainAspectRatio:d,pageRotation:o,scale:n,enabled:!0,onUpdate:$},resizeUI:{handleSize:W,spacing:oe,offsetMode:"outside",includeSides:!d,zIndex:f+1},vertexUI:{vertexSize:0,zIndex:f},rotationUI:{handleSize:V,margin:K,zIndex:f+2,showConnector:Y},includeVertices:!1,includeRotation:_,currentRotation:M??0});if(a.length<2)return null;const se=O.size.width*n,le=O.size.height*n,ce=se/2,de=le/2,ue=Math.max(300,Math.max(se,le)+80);return He("div",{"data-group-selection-box":!0,"data-no-interaction":!0,children:[He("div",{style:{position:"absolute",left:O.origin.x*n,top:O.origin.y*n,width:se,height:le,pointerEvents:"none",zIndex:f},children:[F&&He(H,{children:[He("div",{style:{position:"absolute",left:ce-ue/2,top:de,width:ue,height:1,backgroundColor:B,opacity:.35,pointerEvents:"none"}}),He("div",{style:{position:"absolute",left:ce,top:de-ue/2,width:1,height:ue,backgroundColor:B,opacity:.35,pointerEvents:"none"}}),He("div",{style:{position:"absolute",left:ce-ue/2,top:de,width:ue,height:1,transformOrigin:"center center",transform:`rotate(${j}deg)`,backgroundColor:B,opacity:.8,pointerEvents:"none"}})]}),_&&ae&&((null==h?void 0:h.component)?He("div",{onPointerEnter:()=>z(!0),onPointerLeave:()=>{z(!1),D(null)},onPointerMove:e=>{F||D({x:e.clientX,y:e.clientY})},style:{display:"contents"},children:h.component({...ae.handle,backgroundColor:q,iconColor:Z,connectorStyle:{...ae.connector.style,backgroundColor:G,opacity:F?0:1},showConnector:Y,opacity:F?0:1,border:{color:X,width:Q,style:J}})}):He("div",{onPointerEnter:()=>z(!0),onPointerLeave:()=>{z(!1),D(null)},onPointerMove:e=>{F||D({x:e.clientX,y:e.clientY})},style:{display:"contents"},children:[Y&&He("div",{style:{...ae.connector.style,backgroundColor:G,opacity:F?0:1}}),He("div",{...ae.handle,style:{...ae.handle.style,backgroundColor:q,border:`${Q}px ${J} ${X}`,boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"auto",opacity:F?0:1},children:He("svg",{width:Math.round(.6*V),height:Math.round(.6*V),viewBox:"0 0 24 24",fill:"none",stroke:Z,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[He("path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}),He("path",{d:"M21 3v5h-5"})]})})]})),He("div",{...T?ie:{onPointerDown:e=>e.stopPropagation()},style:{position:"absolute",left:0,top:0,width:se,height:le,outline:F?"none":`${ne}px ${te} ${ee}`,outlineOffset:oe-1,cursor:T?"move":"default",touchAction:"none",pointerEvents:"auto"},children:E&&!F&&re.map(({key:e,...t})=>(null==u?void 0:u.component)?u.component({key:e,...t,backgroundColor:B}):He("div",{...t,style:{...t.style,backgroundColor:B}},e))})]}),(F||R)&&P&&Pu(He("div",{style:{position:"fixed",left:P.x+16,top:P.y-16,background:"rgba(0,0,0,0.8)",color:"#fff",padding:"4px 8px",borderRadius:4,fontSize:12,fontFamily:"monospace",pointerEvents:"none",zIndex:1e4,whiteSpace:"nowrap"},children:[U.toFixed(0),"°"]}),document.body),v&&He(Al,{rect:{origin:{x:O.origin.x*n,y:O.origin.y*n},size:{width:O.size.width*n,height:O.size.height*n}},rotation:o,children:e=>{const n=((j+90*o)%360+360)%360;return v({...e,context:{type:"group",annotations:a,pageIndex:t},selected:!0,placement:{suggestTop:_&&n>90&&n<270}})}})]})}function Sh({strokeColor:e,opacity:t=.5,segmentRects:n,rect:o,scale:i,onClick:r,style:a}){const s=e??"#FFFF00";return He(H,{children:n.map((e,n)=>He("div",{onPointerDown:r,onTouchStart:r,style:{position:"absolute",left:(o?e.origin.x-o.origin.x:e.origin.x)*i,top:(o?e.origin.y-o.origin.y:e.origin.y)*i,width:e.size.width*i,height:e.size.height*i,background:s,opacity:t,pointerEvents:r?"auto":"none",cursor:r?"pointer":"default",zIndex:r?1:void 0,...a}},n))})}function Mh({strokeColor:e,opacity:t=.5,segmentRects:n,rect:o,scale:i,onClick:r,style:a}){const s=e??"#FFFF00",l=2*i;return He(H,{children:n.map((e,n)=>He("div",{onPointerDown:r,onTouchStart:r,style:{position:"absolute",left:(o?e.origin.x-o.origin.x:e.origin.x)*i,top:(o?e.origin.y-o.origin.y:e.origin.y)*i,width:e.size.width*i,height:e.size.height*i,background:"transparent",pointerEvents:r?"auto":"none",cursor:r?"pointer":"default",zIndex:r?1:0,...a},children:He("div",{style:{position:"absolute",left:0,bottom:0,width:"100%",height:l,background:s,opacity:t,pointerEvents:"none"}})},n))})}function Ah({strokeColor:e,opacity:t=.5,segmentRects:n,rect:o,scale:i,onClick:r,style:a}){const s=e??"#FFFF00",l=2*i;return He(H,{children:n.map((e,n)=>He("div",{onPointerDown:r,onTouchStart:r,style:{position:"absolute",left:(o?e.origin.x-o.origin.x:e.origin.x)*i,top:(o?e.origin.y-o.origin.y:e.origin.y)*i,width:e.size.width*i,height:e.size.height*i,background:"transparent",pointerEvents:r?"auto":"none",cursor:r?"pointer":"default",zIndex:r?1:0,...a},children:He("div",{style:{position:"absolute",left:0,top:"50%",width:"100%",height:l,background:s,opacity:t,transform:"translateY(-50%)",pointerEvents:"none"}})},n))})}function Ph({strokeColor:e,opacity:t=.5,segmentRects:n,rect:o,scale:i,onClick:r,style:a}){const s=2*i,l=6*i,c=`url("data:image/svg+xml;utf8,${encodeURIComponent(`\n \n `)}")`;return He(H,{children:n.map((e,n)=>He("div",{onPointerDown:r,onTouchStart:r,style:{position:"absolute",left:(o?e.origin.x-o.origin.x:e.origin.x)*i,top:(o?e.origin.y-o.origin.y:e.origin.y)*i,width:e.size.width*i,height:e.size.height*i,background:"transparent",pointerEvents:r?"auto":"none",cursor:r?"pointer":"default",zIndex:r?1:0,...a},children:He("div",{style:{position:"absolute",left:0,bottom:0,width:"100%",height:2*s,backgroundImage:c,backgroundRepeat:"repeat-x",backgroundSize:`${l}px ${2*s}px`,opacity:t,pointerEvents:"none"}})},n))})}function Dh({isSelected:e,strokeColor:t,opacity:n=1,strokeWidth:o,inkList:i,rect:r,scale:a,onClick:s}){const l=t??"#000000",c=Re(()=>i.map(({points:e})=>{let t="";return e.forEach(({x:e,y:n},o)=>{const i=e-r.origin.x,a=n-r.origin.y;t+=(0===o?"M":"L")+i+" "+a+" "}),t.trim()}),[i,r]),d=r.size.width*a,u=r.size.height*a;return He("svg",{style:{position:"absolute",width:d,height:u,pointerEvents:"none",zIndex:2,overflow:"visible"},width:d,height:u,viewBox:`0 0 ${r.size.width} ${r.size.height}`,children:c.map((t,i)=>He("path",{d:t,fill:"none",opacity:n,onPointerDown:s,onTouchStart:s,style:{cursor:e?"move":"pointer",pointerEvents:e?"none":"visibleStroke",stroke:l,strokeWidth:o,strokeLinecap:"round",strokeLinejoin:"round"}},i))})}function Rh({isSelected:e,color:t="#000000",strokeColor:n,opacity:o=1,strokeWidth:i,strokeStyle:r=Ut.SOLID,strokeDashArray:a,rect:s,scale:l,onClick:c}){const{width:d,height:u,x:h,y:m}=Re(()=>{const e=s.size.width,t=s.size.height;return{width:Math.max(e-i,0),height:Math.max(t-i,0),x:i/2,y:i/2}},[s,i]),g=(d+i)*l,p=(u+i)*l;return He("svg",{style:{position:"absolute",width:g,height:p,pointerEvents:"none",zIndex:2},width:g,height:p,viewBox:`0 0 ${d+i} ${u+i}`,children:He("rect",{x:h,y:m,width:d,height:u,fill:t,opacity:o,onPointerDown:c,onTouchStart:c,style:{cursor:e?"move":"pointer",pointerEvents:e?"none":"transparent"===t?"visibleStroke":"visible",stroke:n??t,strokeWidth:i,...r===Ut.DASHED&&{strokeDasharray:null==a?void 0:a.join(",")}}})})}function zh({color:e="#000000",strokeColor:t,opacity:n=1,strokeWidth:o,strokeStyle:i=Ut.SOLID,strokeDashArray:r,rect:a,scale:s,onClick:l,isSelected:c}){const{width:d,height:u,cx:h,cy:m,rx:g,ry:p}=Re(()=>{const e=a.size.width,t=a.size.height,n=Math.max(e-o,0),i=Math.max(t-o,0);return{width:e,height:t,cx:o/2+n/2,cy:o/2+i/2,rx:n/2,ry:i/2}},[a,o]),f=d*s,v=u*s;return He("svg",{style:{position:"absolute",width:f,height:v,pointerEvents:"none",zIndex:2},width:f,height:v,viewBox:`0 0 ${d} ${u}`,children:He("ellipse",{cx:h,cy:m,rx:g,ry:p,fill:e,opacity:n,onPointerDown:l,onTouchStart:l,style:{cursor:c?"move":"pointer",pointerEvents:c?"none":"transparent"===e?"visibleStroke":"visible",stroke:t??e,strokeWidth:o,...i===Ut.DASHED&&{strokeDasharray:null==r?void 0:r.join(",")}}})})}function Th({color:e="transparent",opacity:t=1,strokeWidth:n,strokeColor:o="#000000",strokeStyle:i=Ut.SOLID,strokeDashArray:r,rect:a,linePoints:s,lineEndings:l,scale:c,onClick:d,isSelected:u}){const{x1:h,y1:m,x2:g,y2:p}=Re(()=>({x1:s.start.x-a.origin.x,y1:s.start.y-a.origin.y,x2:s.end.x-a.origin.x,y2:s.end.y-a.origin.y}),[s,a]),f=Re(()=>{const e=Math.atan2(p-m,g-h);return{start:Bd.createEnding(null==l?void 0:l.start,n,e+Math.PI,h,m),end:Bd.createEnding(null==l?void 0:l.end,n,e,g,p)}},[l,n,h,m,g,p]),v=a.size.width*c,y=a.size.height*c;return He("svg",{style:{position:"absolute",width:v,height:y,pointerEvents:"none",zIndex:2,overflow:"visible"},width:v,height:y,viewBox:`0 0 ${a.size.width} ${a.size.height}`,children:[He("line",{x1:h,y1:m,x2:g,y2:p,opacity:t,onPointerDown:d,onTouchStart:d,style:{cursor:u?"move":"pointer",pointerEvents:u?"none":"visibleStroke",stroke:o,strokeWidth:n,strokeLinecap:"butt",...i===Ut.DASHED&&{strokeDasharray:null==r?void 0:r.join(",")}}}),f.start&&He("path",{d:f.start.d,transform:f.start.transform,onPointerDown:d,onTouchStart:d,stroke:o,style:{cursor:u?"move":"pointer",strokeWidth:n,strokeLinecap:"butt",pointerEvents:u?"none":f.start.filled?"visible":"visibleStroke",...i===Ut.DASHED&&{strokeDasharray:null==r?void 0:r.join(",")}},fill:f.start.filled?e:"none"}),f.end&&He("path",{d:f.end.d,transform:f.end.transform,stroke:o,onPointerDown:d,onTouchStart:d,style:{cursor:u?"move":"pointer",strokeWidth:n,strokeLinecap:"butt",pointerEvents:u?"none":f.end.filled?"visible":"visibleStroke",...i===Ut.DASHED&&{strokeDasharray:null==r?void 0:r.join(",")}},fill:f.end.filled?e:"none"})]})}function Eh({rect:e,vertices:t,color:n="transparent",strokeColor:o="#000000",opacity:i=1,strokeWidth:r,scale:a,isSelected:s,onClick:l,lineEndings:c}){const d=Re(()=>t.map(({x:t,y:n})=>({x:t-e.origin.x,y:n-e.origin.y})),[t,e]),u=Re(()=>{if(!d.length)return"";const[e,...t]=d;return`M ${e.x} ${e.y} `+t.map(e=>`L ${e.x} ${e.y} `).join("").trim()},[d]),h=Re(()=>{if(d.length<2)return{start:null,end:null};const e=(e,t)=>Math.atan2(t.y-e.y,t.x-e.x),t=e(d[0],d[1]),n=e(d[d.length-2],d[d.length-1]);return{start:Bd.createEnding(null==c?void 0:c.start,r,t+Math.PI,d[0].x,d[0].y),end:Bd.createEnding(null==c?void 0:c.end,r,n,d[d.length-1].x,d[d.length-1].y)}},[d,c,r]),m=e.size.width*a,g=e.size.height*a;return He("svg",{style:{position:"absolute",width:m,height:g,pointerEvents:"none",zIndex:2,overflow:"visible"},width:m,height:g,viewBox:`0 0 ${e.size.width} ${e.size.height}`,children:[He("path",{d:u,onPointerDown:l,onTouchStart:l,opacity:i,style:{fill:"none",stroke:o??n,strokeWidth:r,cursor:s?"move":"pointer",pointerEvents:s?"none":"visibleStroke",strokeLinecap:"butt",strokeLinejoin:"miter"}}),h.start&&He("path",{d:h.start.d,transform:h.start.transform,stroke:o,fill:h.start.filled?n:"none",onPointerDown:l,onTouchStart:l,style:{cursor:s?"move":"pointer",strokeWidth:r,pointerEvents:s?"none":h.start.filled?"visible":"visibleStroke",strokeLinecap:"butt"}}),h.end&&He("path",{d:h.end.d,transform:h.end.transform,stroke:o,fill:h.end.filled?n:"none",onPointerDown:l,onTouchStart:l,style:{cursor:s?"move":"pointer",strokeWidth:r,pointerEvents:s?"none":h.end.filled?"visible":"visibleStroke",strokeLinecap:"butt"}})]})}function _h({rect:e,vertices:t,color:n="transparent",strokeColor:o="#000000",opacity:i=1,strokeWidth:r,strokeStyle:a=Ut.SOLID,strokeDashArray:s,scale:l,isSelected:c,onClick:d,currentVertex:u,handleSize:h=14}){const m=u?[...t,u]:t,g=Re(()=>m.map(({x:t,y:n})=>({x:t-e.origin.x,y:n-e.origin.y})),[m,e]),p=Re(()=>{if(!g.length)return"";const[e,...t]=g,n=!!u;return(`M ${e.x} ${e.y} `+t.map(e=>`L ${e.x} ${e.y}`).join(" ")+(n?"":" Z")).trim()},[g,u]),f=u&&t.length>0,v=e.size.width*l,y=e.size.height*l;return He("svg",{style:{position:"absolute",width:v,height:y,pointerEvents:"none",zIndex:2,overflow:"visible"},width:v,height:y,viewBox:`0 0 ${e.size.width} ${e.size.height}`,children:[He("path",{d:p,onPointerDown:d,onTouchStart:d,opacity:i,style:{fill:u?"none":n,stroke:o??n,strokeWidth:r,cursor:c?"move":"pointer",pointerEvents:c?"none":"transparent"===n?"visibleStroke":"visible",strokeLinecap:"butt",strokeLinejoin:"miter",...a===Ut.DASHED&&{strokeDasharray:null==s?void 0:s.join(",")}}}),f&&t.length>1&&He("path",{d:`M ${g[g.length-1].x} ${g[g.length-1].y} L ${g[0].x} ${g[0].y}`,fill:"none",style:{stroke:o,strokeWidth:r,strokeDasharray:"4,4",opacity:.7}}),f&&t.length>=2&&He("rect",{x:g[0].x-h/l/2,y:g[0].y-h/l/2,width:h/l,height:h/l,fill:o,opacity:.4,stroke:o,strokeWidth:r/2})]})}function Nh({isSelected:e,isEditing:t,annotation:n,pageIndex:o,scale:i,onClick:r}){const a=De(null),{provides:s}=xh(),[l,c]=Se(!1);Ae(()=>{if(t&&a.current){const e=a.current;e.focus();const t=window.getSelection();if(t){const n=document.createRange();n.selectNodeContents(e),n.collapse(!1),t.removeAllRanges(),t.addRange(n)}}},[t]),Pe(()=>{try{const e=navigator,t=/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&(null==e?void 0:e.maxTouchPoints)>1;c(t)}catch{c(!1)}},[]);const d=n.object.fontSize*i,u=l&&t&&d>0&&d<16,h=u?16:d,m=u?d/16:1,g=u?100/m:100;return He("div",{style:{position:"absolute",width:n.object.rect.size.width*i,height:n.object.rect.size.height*i,cursor:e&&!t?"move":"default",pointerEvents:e&&!t?"none":"auto",zIndex:2},onPointerDown:r,onTouchStart:r,children:He("span",{ref:a,onBlur:()=>{s&&a.current&&s.updateAnnotation(o,n.object.id,{contents:a.current.innerText})},tabIndex:0,style:{color:n.object.fontColor,fontSize:h,...xn(n.object.fontFamily),textAlign:cn(n.object.textAlign),flexDirection:"column",justifyContent:n.object.verticalAlign===Rt.Top?"flex-start":n.object.verticalAlign===Rt.Middle?"center":"flex-end",display:"flex",backgroundColor:n.object.color??n.object.backgroundColor,opacity:n.object.opacity,width:u?`${g}%`:"100%",height:u?`${g}%`:"100%",lineHeight:"1.18",overflow:"hidden",cursor:t?"text":"pointer",outline:"none",transform:u?`scale(${m})`:void 0,transformOrigin:"top left"},contentEditable:t,...vh,children:n.object.contents})})}function Oh({documentId:e,pageIndex:t,annotation:n,scaleFactor:o=1,unrotated:i,style:r,...a}){const{provides:s}=xh(),[l,c]=Se(null),d=De(null),{width:u,height:h}=n.rect.size;Ae(()=>{if(s){const r=s.forDocument(e).renderAnnotation({pageIndex:t,annotation:n,options:{scaleFactor:o,dpr:window.devicePixelRatio,unrotated:i}});return r.wait(e=>{const t=URL.createObjectURL(e);c(t),d.current=t},En),()=>{d.current?(URL.revokeObjectURL(d.current),d.current=null):r.abort({code:Qt.Cancelled,message:"canceled render task"})}}},[t,o,i,s,e,n.id,u,h]);return He(H,{children:l&&He("img",{src:l,onLoad:()=>{d.current&&(URL.revokeObjectURL(d.current),d.current=null)},...a,style:{width:"100%",height:"100%",display:"block",...r||{}}})})}function Lh({isSelected:e,annotation:t,documentId:n,pageIndex:o,scale:i,onClick:r}){const a=!!t.object.rotation&&!!t.object.unrotatedRect;return He("div",{style:{position:"absolute",width:"100%",height:"100%",zIndex:2,pointerEvents:e?"none":"auto",cursor:"pointer"},onPointerDown:r,onTouchStart:r,children:He(Oh,{documentId:n,pageIndex:o,annotation:{...t.object,id:t.object.id},scaleFactor:i,unrotated:a})})}function $h({isSelected:e,strokeColor:t="#0000FF",strokeWidth:n=2,strokeStyle:o=Ut.UNDERLINE,strokeDashArray:i,rect:r,scale:a,onClick:s,hasIRT:l=!1}){const{width:c,height:d}=Re(()=>({width:r.size.width,height:r.size.height}),[r]),u=c*a,h=d*a,m=Re(()=>{if(o===Ut.DASHED)return(null==i?void 0:i.join(","))??`${3*n},${n}`},[o,i,n]),g=o===Ut.UNDERLINE;return He("svg",{style:{position:"absolute",width:u,height:h,pointerEvents:"none",zIndex:2},width:u,height:h,viewBox:`0 0 ${c} ${d}`,children:[He("rect",{x:0,y:0,width:c,height:d,fill:"transparent",onPointerDown:l?void 0:s,onTouchStart:l?void 0:s,style:{cursor:l?"default":e?"move":"pointer",pointerEvents:l||e?"none":"visible"}}),g?He("line",{x1:1,y1:d-1,x2:c-1,y2:d-1,stroke:t,strokeWidth:n,strokeDasharray:m,style:{pointerEvents:"none"}}):He("rect",{x:n/2,y:n/2,width:Math.max(c-n,0),height:Math.max(d-n,0),fill:"transparent",stroke:t,strokeWidth:n,strokeDasharray:m,style:{pointerEvents:"none"}})]})}function jh(e){const{documentId:t,pageIndex:n,scale:o,pageWidth:i,pageHeight:r,selectionMenu:a}=e,{provides:s}=xh(),{provides:l}=Ll(),[c,d]=Se([]),{register:u}=function({modeId:e,pageIndex:t,documentId:n}){const{provides:o}=ch();return{register:(i,r)=>{const a=(null==r?void 0:r.modeId)??e,s=(null==r?void 0:r.pageIndex)??t,l=(null==r?void 0:r.documentId)??n;return a?null==o?void 0:o.registerHandlers({modeId:a,handlers:i,pageIndex:s,documentId:l}):null==o?void 0:o.registerAlways({scope:void 0!==s?{type:"page",documentId:l,pageIndex:s}:{type:"global",documentId:l},handlers:i})}}}({documentId:t,pageIndex:n}),[h,m]=Se([]),[g,p]=Se(null),f=Re(()=>s?s.forDocument(t):null,[s,t]),v=h.length>1;Ae(()=>{if(f){const e=f.getState();return d(cd(e,n)),m(ud(e)),f.onStateChange(e=>{d(cd(e,n)),m(ud(e))})}},[f,n]);const y=Re(()=>({onPointerDown:(e,t)=>{t.target===t.currentTarget&&f&&(f.deselectAnnotation(),p(null))}}),[f]),b=ze((e,t)=>{if(e.stopPropagation(),f&&l){l.clear();"metaKey"in e&&(e.metaKey||e.ctrlKey)?f.toggleSelection(n,t.object.id):f.selectAnnotation(n,t.object.id),t.object.id!==g&&p(null)}},[f,l,g,n]),w=ze((e,t)=>{if(e.stopPropagation(),f&&l){if(l.clear(),t.object.inReplyToId){const e=t.object.inReplyToId,n=c.find(t=>t.object.id===e);if(n)return void f.selectAnnotation(n.object.pageIndex,e)}f.selectAnnotation(n,t.object.id)}},[f,l,c,n]);Ae(()=>u(y,{documentId:t}),[u,y]);const x=Re(()=>c.filter(e=>h.includes(e.object.id)),[c,h]),C=Re(()=>!(x.length<2)&&x.every(e=>{const t=null==f?void 0:f.findToolForAnnotation(e.object),n=lu(null==t?void 0:t.interaction.isGroupDraggable,e.object,!0),o=lu(null==t?void 0:t.interaction.isDraggable,e.object,!0);return void 0!==(null==t?void 0:t.interaction.isGroupDraggable)?n:o}),[x,f]),I=Re(()=>!(x.length<2)&&x.every(e=>{const t=null==f?void 0:f.findToolForAnnotation(e.object),n=lu(null==t?void 0:t.interaction.isGroupResizable,e.object,!0),o=lu(null==t?void 0:t.interaction.isResizable,e.object,!0);return void 0!==(null==t?void 0:t.interaction.isGroupResizable)?n:o}),[x,f]),k=Re(()=>!(x.length<2)&&x.every(e=>{const t=null==f?void 0:f.findToolForAnnotation(e.object),n=lu(null==t?void 0:t.interaction.isGroupRotatable,e.object,!0),o=lu(null==t?void 0:t.interaction.isRotatable,e.object,!0);return void 0!==(null==t?void 0:t.interaction.isGroupRotatable)?n:o}),[x,f]),S=Re(()=>!(x.length<2)&&x.some(e=>{const t=null==f?void 0:f.findToolForAnnotation(e.object),n=lu(null==t?void 0:t.interaction.lockGroupAspectRatio,e.object,!1),o=lu(null==t?void 0:t.interaction.lockAspectRatio,e.object,!1);return void 0!==(null==t?void 0:t.interaction.lockGroupAspectRatio)?n:o}),[x,f]),M=Re(()=>{if(!f)return!1;const e=f.getSelectedAnnotations();return e.length>1&&e.every(e=>e.object.pageIndex===n)},[f,n,h]);return He(H,{children:[c.map(i=>{const r=h.includes(i.object.id),s=g===i.object.id,l=null==f?void 0:f.findToolForAnnotation(i.object);for(const t of e.annotationRenderers??[]){const s=t.tryRender(i,{isSelected:r,scale:o,pageIndex:n,onClick:e=>b(e,i)});if(s)return He(Ih,{trackedAnnotation:i,isSelected:r,isMultiSelected:v,isDraggable:lu(null==l?void 0:l.interaction.isDraggable,i.object,!1),isResizable:lu(null==l?void 0:l.interaction.isResizable,i.object,!1),lockAspectRatio:lu(null==l?void 0:l.interaction.lockAspectRatio,i.object,!1),isRotatable:lu(null==l?void 0:l.interaction.isRotatable,i.object,!1),selectionMenu:a,onSelect:e=>b(e,i),style:{mixBlendMode:Mn(i.object.blendMode??zt.Normal)},...e,children:()=>s},i.object.id)}if(Kc(i))return He(Ih,{trackedAnnotation:i,isSelected:r,isMultiSelected:v,isDraggable:lu(null==l?void 0:l.interaction.isDraggable,i.object,!0),isResizable:lu(null==l?void 0:l.interaction.isResizable,i.object,!0),lockAspectRatio:lu(null==l?void 0:l.interaction.lockAspectRatio,i.object,!1),isRotatable:lu(null==l?void 0:l.interaction.isRotatable,i.object,!0),selectionMenu:a,onSelect:e=>b(e,i),style:{mixBlendMode:Mn(i.object.blendMode??zt.Normal)},...e,children:e=>He(Dh,{...e,isSelected:r,scale:o,onClick:e=>b(e,i)})},i.object.id);if(Xc(i))return He(Ih,{trackedAnnotation:i,isSelected:r,isMultiSelected:v,isDraggable:lu(null==l?void 0:l.interaction.isDraggable,i.object,!0),isResizable:lu(null==l?void 0:l.interaction.isResizable,i.object,!0),lockAspectRatio:lu(null==l?void 0:l.interaction.lockAspectRatio,i.object,!1),isRotatable:lu(null==l?void 0:l.interaction.isRotatable,i.object,!0),selectionMenu:a,onSelect:e=>b(e,i),style:{mixBlendMode:Mn(i.object.blendMode??zt.Normal)},...e,children:e=>He(Rh,{...e,isSelected:r,scale:o,onClick:e=>b(e,i)})},i.object.id);if(Zc(i))return He(Ih,{trackedAnnotation:i,isSelected:r,isMultiSelected:v,isDraggable:lu(null==l?void 0:l.interaction.isDraggable,i.object,!0),isResizable:lu(null==l?void 0:l.interaction.isResizable,i.object,!0),lockAspectRatio:lu(null==l?void 0:l.interaction.lockAspectRatio,i.object,!1),isRotatable:lu(null==l?void 0:l.interaction.isRotatable,i.object,!0),selectionMenu:a,onSelect:e=>b(e,i),style:{mixBlendMode:Mn(i.object.blendMode??zt.Normal)},...e,children:e=>He(zh,{...e,isSelected:r,scale:o,onClick:e=>b(e,i)})},i.object.id);if(td(i))return He(Ih,{trackedAnnotation:i,isSelected:r,isMultiSelected:v,isDraggable:lu(null==l?void 0:l.interaction.isDraggable,i.object,!1),isResizable:lu(null==l?void 0:l.interaction.isResizable,i.object,!1),lockAspectRatio:lu(null==l?void 0:l.interaction.lockAspectRatio,i.object,!1),isRotatable:lu(null==l?void 0:l.interaction.isRotatable,i.object,!1),selectionMenu:a,onSelect:e=>b(e,i),zIndex:0,style:{mixBlendMode:Mn(i.object.blendMode??zt.Normal)},...e,children:e=>He(Mh,{...e,scale:o,onClick:e=>b(e,i)})},i.object.id);if(nd(i))return He(Ih,{trackedAnnotation:i,isSelected:r,isMultiSelected:v,isDraggable:lu(null==l?void 0:l.interaction.isDraggable,i.object,!1),isResizable:lu(null==l?void 0:l.interaction.isResizable,i.object,!1),lockAspectRatio:lu(null==l?void 0:l.interaction.lockAspectRatio,i.object,!1),isRotatable:lu(null==l?void 0:l.interaction.isRotatable,i.object,!1),selectionMenu:a,onSelect:e=>b(e,i),zIndex:0,style:{mixBlendMode:Mn(i.object.blendMode??zt.Normal)},...e,children:e=>He(Ah,{...e,scale:o,onClick:e=>b(e,i)})},i.object.id);if(od(i))return He(Ih,{trackedAnnotation:i,isSelected:r,isMultiSelected:v,isDraggable:lu(null==l?void 0:l.interaction.isDraggable,i.object,!1),isResizable:lu(null==l?void 0:l.interaction.isResizable,i.object,!1),lockAspectRatio:lu(null==l?void 0:l.interaction.lockAspectRatio,i.object,!1),isRotatable:lu(null==l?void 0:l.interaction.isRotatable,i.object,!1),selectionMenu:a,onSelect:e=>b(e,i),zIndex:0,style:{mixBlendMode:Mn(i.object.blendMode??zt.Normal)},...e,children:e=>He(Ph,{...e,scale:o,onClick:e=>b(e,i)})},i.object.id);if(ed(i))return He(Ih,{trackedAnnotation:i,isSelected:r,isMultiSelected:v,isDraggable:lu(null==l?void 0:l.interaction.isDraggable,i.object,!1),isResizable:lu(null==l?void 0:l.interaction.isResizable,i.object,!1),lockAspectRatio:lu(null==l?void 0:l.interaction.lockAspectRatio,i.object,!1),isRotatable:lu(null==l?void 0:l.interaction.isRotatable,i.object,!1),selectionMenu:a,onSelect:e=>b(e,i),zIndex:0,style:{mixBlendMode:Mn(i.object.blendMode??zt.Multiply)},...e,children:e=>He(Sh,{...e,scale:o,onClick:e=>b(e,i)})},i.object.id);if(Qc(i))return He(Ih,{trackedAnnotation:i,isSelected:r,isMultiSelected:v,isDraggable:lu(null==l?void 0:l.interaction.isDraggable,i.object,!0),isResizable:lu(null==l?void 0:l.interaction.isResizable,i.object,!1),lockAspectRatio:lu(null==l?void 0:l.interaction.lockAspectRatio,i.object,!1),isRotatable:lu(null==l?void 0:l.interaction.isRotatable,i.object,!0),selectionMenu:a,onSelect:e=>b(e,i),vertexConfig:{extractVertices:e=>[e.linePoints.start,e.linePoints.end],transformAnnotation:(e,t)=>({...e,linePoints:{start:t[0],end:t[1]}})},style:{mixBlendMode:Mn(i.object.blendMode??zt.Normal)},...e,children:e=>He(H,{children:He(Th,{...e,isSelected:r,scale:o,onClick:e=>b(e,i)})})},i.object.id);if(Jc(i))return He(Ih,{trackedAnnotation:i,isSelected:r,isMultiSelected:v,isDraggable:lu(null==l?void 0:l.interaction.isDraggable,i.object,!0),isResizable:lu(null==l?void 0:l.interaction.isResizable,i.object,!1),lockAspectRatio:lu(null==l?void 0:l.interaction.lockAspectRatio,i.object,!1),isRotatable:lu(null==l?void 0:l.interaction.isRotatable,i.object,!0),selectionMenu:a,onSelect:e=>b(e,i),vertexConfig:{extractVertices:e=>e.vertices,transformAnnotation:(e,t)=>({...e,vertices:t})},style:{mixBlendMode:Mn(i.object.blendMode??zt.Normal)},...e,children:e=>He(H,{children:He(Eh,{...e,isSelected:r,scale:o,onClick:e=>b(e,i)})})},i.object.id);if(Yc(i))return He(Ih,{trackedAnnotation:i,isSelected:r,isMultiSelected:v,isDraggable:lu(null==l?void 0:l.interaction.isDraggable,i.object,!0),isResizable:lu(null==l?void 0:l.interaction.isResizable,i.object,!1),lockAspectRatio:lu(null==l?void 0:l.interaction.lockAspectRatio,i.object,!1),isRotatable:lu(null==l?void 0:l.interaction.isRotatable,i.object,!0),selectionMenu:a,onSelect:e=>b(e,i),vertexConfig:{extractVertices:e=>e.vertices,transformAnnotation:(e,t)=>({...e,vertices:t})},style:{mixBlendMode:Mn(i.object.blendMode??zt.Normal)},...e,children:e=>He(H,{children:He(_h,{...e,isSelected:r,scale:o,onClick:e=>b(e,i)})})},i.object.id);if(id(i))return He(Ih,{trackedAnnotation:i,isSelected:r,isMultiSelected:v,isDraggable:lu(null==l?void 0:l.interaction.isDraggable,i.object,!0)&&!s,isResizable:lu(null==l?void 0:l.interaction.isResizable,i.object,!0),lockAspectRatio:lu(null==l?void 0:l.interaction.lockAspectRatio,i.object,!1),isRotatable:lu(null==l?void 0:l.interaction.isRotatable,i.object,!0),selectionMenu:a,onSelect:e=>b(e,i),style:{mixBlendMode:Mn(i.object.blendMode??zt.Normal)},onDoubleClick:e=>{e.stopPropagation(),p(i.object.id)},...e,children:e=>He(Nh,{isSelected:r,isEditing:s,annotation:{...i,object:e},pageIndex:n,scale:o,onClick:e=>b(e,i)})},i.object.id);if(rd(i))return He(Ih,{trackedAnnotation:i,isSelected:r,isMultiSelected:v,isDraggable:lu(null==l?void 0:l.interaction.isDraggable,i.object,!0),isResizable:lu(null==l?void 0:l.interaction.isResizable,i.object,!0),lockAspectRatio:lu(null==l?void 0:l.interaction.lockAspectRatio,i.object,!1),isRotatable:lu(null==l?void 0:l.interaction.isRotatable,i.object,!0),selectionMenu:a,onSelect:e=>b(e,i),style:{mixBlendMode:Mn(i.object.blendMode??zt.Normal)},...e,children:e=>He(Lh,{isSelected:r,annotation:i,documentId:t,pageIndex:n,scale:o,onClick:e=>b(e,i)})},i.object.id);if(sd(i)){const t=!!i.object.inReplyToId;return He(Ih,{trackedAnnotation:i,isSelected:r,isMultiSelected:v,isDraggable:!1,isResizable:!1,lockAspectRatio:!1,isRotatable:!1,selectionMenu:t?void 0:a,onSelect:e=>w(e,i),...e,children:e=>He($h,{...e,isSelected:r,scale:o,onClick:e=>w(e,i),hasIRT:t})},i.object.id)}return null}),M&&x.length>=2&&He(kh,{documentId:t,pageIndex:n,scale:o,rotation:e.rotation,pageWidth:i,pageHeight:r,selectedAnnotations:x,isDraggable:C,isResizable:I,isRotatable:k,lockAspectRatio:S,resizeUI:e.resizeUI,rotationUI:e.rotationUI,selectionOutlineColor:e.selectionOutlineColor,selectionOutline:e.groupSelectionOutline??e.selectionOutline,groupSelectionMenu:e.groupSelectionMenu})]})}function Fh({documentId:e,pageIndex:t,scale:n}){var o,i,r,a,s,l,c,d,u,h,m,g;const{provides:p}=Ll(),{provides:f}=xh(),[v,y]=Se([]),[b,w]=Se(null),[x,C]=Se(null);if(Ae(()=>{if(p)return p.forDocument(e).onSelectionChange(()=>{y(p.forDocument(e).getHighlightRectsForPage(t)),w(p.forDocument(e).getBoundingRectForPage(t))})},[p,e,t]),Ae(()=>{if(f)return C(f.forDocument(e).getActiveTool()),f.forDocument(e).onActiveToolChange(e=>C(e))},[f,e]),!b)return null;if(!x||!x.defaults)return null;switch(x.defaults.type){case _t.UNDERLINE:return He("div",{style:{mixBlendMode:Mn((null==(o=x.defaults)?void 0:o.blendMode)??zt.Normal),pointerEvents:"none",position:"absolute",inset:0},children:He(Mh,{strokeColor:null==(i=x.defaults)?void 0:i.strokeColor,opacity:null==(r=x.defaults)?void 0:r.opacity,segmentRects:v,scale:n})});case _t.HIGHLIGHT:return He("div",{style:{mixBlendMode:Mn((null==(a=x.defaults)?void 0:a.blendMode)??zt.Multiply),pointerEvents:"none",position:"absolute",inset:0},children:He(Sh,{strokeColor:null==(s=x.defaults)?void 0:s.strokeColor,opacity:null==(l=x.defaults)?void 0:l.opacity,segmentRects:v,scale:n})});case _t.STRIKEOUT:return He("div",{style:{mixBlendMode:Mn((null==(c=x.defaults)?void 0:c.blendMode)??zt.Normal),pointerEvents:"none",position:"absolute",inset:0},children:He(Ah,{strokeColor:null==(d=x.defaults)?void 0:d.strokeColor,opacity:null==(u=x.defaults)?void 0:u.opacity,segmentRects:v,scale:n})});case _t.SQUIGGLY:return He("div",{style:{mixBlendMode:Mn((null==(h=x.defaults)?void 0:h.blendMode)??zt.Normal),pointerEvents:"none",position:"absolute",inset:0},children:He(Ph,{strokeColor:null==(m=x.defaults)?void 0:m.strokeColor,opacity:null==(g=x.defaults)?void 0:g.opacity,segmentRects:v,scale:n})});default:return null}}function Uh({preview:e,scale:t}){const{bounds:n}=e,o={position:"absolute",left:n.origin.x*t,top:n.origin.y*t,width:n.size.width*t,height:n.size.height*t,pointerEvents:"none",zIndex:10};return e.type===_t.CIRCLE?He("div",{style:o,children:He(zh,{isSelected:!1,scale:t,...e.data})}):e.type===_t.SQUARE?He("div",{style:o,children:He(Rh,{isSelected:!1,scale:t,...e.data})}):e.type===_t.POLYGON?He("div",{style:o,children:He(_h,{isSelected:!1,scale:t,...e.data})}):e.type===_t.POLYLINE?He("div",{style:o,children:He(Eh,{isSelected:!1,scale:t,...e.data})}):e.type===_t.LINE?He("div",{style:o,children:He(Th,{isSelected:!1,scale:t,...e.data})}):e.type===_t.INK?He("div",{style:o,children:He(Dh,{isSelected:!1,scale:t,...e.data})}):e.type===_t.FREETEXT?He("div",{style:o,children:He("div",{style:{width:"100%",height:"100%",border:`1px dashed ${e.data.fontColor||"#000000"}`,backgroundColor:"transparent"}})}):null}function Hh({documentId:e,pageIndex:t,scale:n}){const{plugin:o}=wh(),[i,r]=Se(new Map),a=De(null),s=De(null),l=Re(()=>({requestFile:({accept:e,onFile:t})=>{if(!a.current)return;const n=a.current;n.accept=e,n.onchange=e=>{var o;const i=null==(o=e.target.files)?void 0:o[0];i&&(t(i),n.value="")},n.click()},processImage:({source:e,maxWidth:t,maxHeight:n,onComplete:o})=>{const i=s.current;if(!i||!i.getContext)return;const r=i.getContext("2d");if(!r)return;const a=new Image;a.crossOrigin="Anonymous",a.onload=()=>{let{naturalWidth:s,naturalHeight:l}=a;const c=t?t/s:1,d=n?n/l:1,u=Math.min(c,d,1),h=s*u,m=l*u;i.width=h,i.height=m,r.drawImage(a,0,0,h,m);const g=r.getImageData(0,0,h,m);"string"!=typeof e&&URL.revokeObjectURL(a.src),o({imageData:g,width:h,height:m})},a.src="string"==typeof e?e:URL.createObjectURL(e)}}),[]);return Ae(()=>{if(o)return o.registerPageHandlers(e,t,n,{services:l,onPreview:(e,t)=>{r(n=>{const o=new Map(n);return t?o.set(e,t):o.delete(e),o})}})},[e,t,n,o,l]),He(H,{children:[He("input",{ref:a,type:"file",style:{display:"none"}}),He("canvas",{ref:s,style:{display:"none"}}),Array.from(i.entries()).map(([e,t])=>He(Uh,{preview:t,scale:n},e))]})}function Bh({style:e,documentId:t,pageIndex:n,scale:o,rotation:i,selectionMenu:r,groupSelectionMenu:a,resizeUI:s,vertexUI:l,rotationUI:c,selectionOutlineColor:d,selectionOutline:u,groupSelectionOutline:h,customAnnotationRenderer:m,annotationRenderers:g,...p}){var f,v,y,b;const w=Oo(t),x=null==(v=null==(f=null==w?void 0:w.document)?void 0:f.pages)?void 0:v[n],C=(null==(y=null==x?void 0:x.size)?void 0:y.width)??0,I=(null==(b=null==x?void 0:x.size)?void 0:b.height)??0,k=Te(bh),S=Re(()=>{const e=[...k];for(const t of g??[]){const n=e.findIndex(e=>e.id===t.id);n>=0?e[n]=t:e.push(t)}return e},[k,g]),M=Re(()=>void 0!==o?o:(null==w?void 0:w.scale)??1,[o,null==w?void 0:w.scale]);return He("div",{style:{...e},...p,children:[He(jh,{documentId:t,selectionMenu:r,groupSelectionMenu:a,pageIndex:n,scale:M,rotation:Re(()=>{if(void 0!==i)return i;return(((null==x?void 0:x.rotation)??0)+((null==w?void 0:w.rotation)??0))%4},[i,null==x?void 0:x.rotation,null==w?void 0:w.rotation]),pageWidth:C,pageHeight:I,resizeUI:s,vertexUI:l,rotationUI:c,selectionOutlineColor:d,selectionOutline:u,groupSelectionOutline:h,customAnnotationRenderer:m,annotationRenderers:S}),He(Fh,{documentId:t,pageIndex:n,scale:M}),He(Hh,{documentId:t,pageIndex:n,scale:M})]})}function Wh(e){return{id:e.id,tryRender:(t,n)=>e.matches(t.object)?e.render({...n,annotation:t}):null}}const qh=Do(gu).addWrapper(function({children:e}){const[t,n]=Se([]),o=ze(e=>(n(t=>{const n=new Set(e.map(e=>e.id));return[...t.filter(e=>!n.has(e.id)),...e]}),()=>n(t=>t.filter(t=>!e.some(e=>e.id===t.id)))),[]);return He(yh.Provider,{value:o,children:He(bh.Provider,{value:t,children:e})})}).build(),Gh="print",Vh={id:Gh,name:"Print Plugin",version:"1.0.0",provides:["print"],requires:[],optional:[],defaultConfig:{}},Kh=class extends fo{constructor(e,t,n){super(e,t),this.printReady$=So()}buildCapability(){return{print:e=>this.print(e),forDocument:e=>this.createPrintScope(e)}}createPrintScope(e){return{print:t=>this.print(t,e)}}print(e,t){const n=t??this.getActiveDocumentId();if(!this.checkPermission(n,Zt.Print))return this.logger.debug("PrintPlugin","Print",`Cannot print: document ${n} lacks Print permission`),Jt.reject({code:Qt.Security,message:"Document lacks Print permission"});const o=e??{},i=new Ct;i.progress({stage:"preparing",message:"Preparing document..."});return this.preparePrintDocument(o,n).wait(e=>{i.progress({stage:"document-ready",message:"Document prepared successfully"}),this.printReady$.emit({documentId:n,options:o,buffer:e,task:i})},e=>i.fail(e)),i}preparePrintDocument(e,t){const n=this.coreState.core.documents[t];return(null==n?void 0:n.document)?this.engine.preparePrintDocument(n.document,e):Jt.reject({code:Qt.DocNotOpen,message:`Document ${t} not found`})}onPrintRequest(e){return this.printReady$.on(e)}async initialize(e){this.logger.info("PrintPlugin","Initialize","Print plugin initialized")}async destroy(){this.printReady$.clear(),await super.destroy()}};Kh.id="print";let Zh=Kh;const Yh=()=>_o(Zh.id);const Xh=Do({manifest:Vh,create:(e,t)=>new Zh(Gh,e,t),reducer:()=>{},initialState:{}}).addUtility(function(){const{provides:e}=Yh(),{plugin:t}=Eo(Zh.id),n=De(null),o=De(null);return Ae(()=>{if(!e||!t)return;const i=t.onPrintRequest(({buffer:e,task:t})=>{const i=n.current;if(!i)return;o.current&&(URL.revokeObjectURL(o.current),o.current=null);const r=URL.createObjectURL(new Blob([e],{type:"application/pdf"}));o.current=r,i.onload=()=>{var n,o;i.src===r&&(t.progress({stage:"iframe-ready",message:"Ready to print"}),null==(n=i.contentWindow)||n.focus(),null==(o=i.contentWindow)||o.print(),t.progress({stage:"printing",message:"Print dialog opened"}),t.resolve(e))},i.src=r});return()=>{i(),o.current&&URL.revokeObjectURL(o.current)}},[e,t]),He("iframe",{ref:n,style:{position:"absolute",display:"none"},title:"Print Document",src:"about:blank"})}).build(),Qh="fullscreen",Jh={id:Qh,name:"Fullscreen Plugin",version:"1.0.0",provides:["fullscreen"],requires:[],optional:[],defaultConfig:{}},em="SET_FULLSCREEN";const tm=class extends fo{constructor(e,t,n){super(e,t),this.onStateChange$=Mo(),this.fullscreenRequest$=So(),this.config=n}async initialize(e){}buildCapability(){return{isFullscreen:()=>this.state.isFullscreen,enableFullscreen:e=>this.enableFullscreen(e),exitFullscreen:()=>this.exitFullscreen(),toggleFullscreen:e=>this.toggleFullscreen(e),onRequest:this.fullscreenRequest$.on,onStateChange:this.onStateChange$.on}}getTargetSelector(){return this.currentTargetElement??this.config.targetElement}toggleFullscreen(e){this.state.isFullscreen?this.exitFullscreen():this.enableFullscreen(e)}enableFullscreen(e){this.currentTargetElement=e??this.config.targetElement,this.fullscreenRequest$.emit({action:"enter",targetElement:this.currentTargetElement})}exitFullscreen(){this.fullscreenRequest$.emit({action:"exit"}),this.currentTargetElement=void 0}onStoreUpdated(e,t){this.onStateChange$.emit(t)}setFullscreenState(e){this.dispatch({type:em,payload:e})}async destroy(){this.fullscreenRequest$.clear(),super.destroy()}};tm.id="fullscreen";let nm=tm;const om=()=>Eo(nm.id);async function im(e,t,n){if("enter"===e.action){const o=function(e,t,n){if(!t||"enter"!==e.action)return t;let o=null;return n&&(o=t.querySelector(n),o||console.warn(`Fullscreen: Could not find element with selector "${n}" within the wrapper. Falling back to wrapper element.`)),o||(o=t),o}(e,t,n);o&&!document.fullscreenElement&&await o.requestFullscreen()}else document.fullscreenElement&&await document.exitFullscreen()}const rm=Do({manifest:Jh,create:(e,t)=>new nm(Qh,e,t),reducer:(e,t)=>t.type===em?{...e,isFullscreen:t.payload}:e,initialState:{isFullscreen:!1}}).addWrapper(function({children:e,...t}){const{provides:n}=_o(nm.id),{plugin:o}=om(),{plugin:i}=om(),r=De(null);return Ae(()=>{if(!n||!o)return;return n.onRequest(async e=>{const t=o.getTargetSelector();await im(e,r.current,t)})},[n,o]),Ae(()=>{if(!i)return;const e=()=>i.setFullscreenState(!!document.fullscreenElement);return document.addEventListener("fullscreenchange",e),()=>document.removeEventListener("fullscreenchange",e)},[i]),He("div",{...t,style:{position:"relative",width:"100%",height:"100%",...t.style},ref:r,children:e})}).build(),am="bookmark",sm={id:am,name:"Bookmark Plugin",version:"1.0.0",provides:["bookmark"],requires:[],optional:[],defaultConfig:{}},lm=class extends fo{constructor(e,t){super(e,t)}async initialize(e){}buildCapability(){return{getBookmarks:()=>this.getBookmarks(),forDocument:e=>this.createBookmarkScope(e)}}createBookmarkScope(e){return{getBookmarks:()=>this.getBookmarks(e)}}getBookmarks(e){const t=e??this.getActiveDocumentId(),n=this.coreState.core.documents[t];if(!(null==n?void 0:n.document))throw new Error(`Document ${t} not loaded`);return this.engine.getBookmarks(n.document)}};lm.id="bookmark";let cm=lm;const dm={manifest:sm,create:e=>new cm(am,e),reducer:()=>{},initialState:{}},um=class extends fo{constructor(e,t,n){super(e,t),this.downloadRequest$=So(),this.config=n}buildCapability(){return{saveAsCopy:()=>this.saveAsCopy(),download:()=>this.download(),forDocument:e=>this.createExportScope(e)}}createExportScope(e){return{saveAsCopy:()=>this.saveAsCopy(e),download:()=>this.download(e)}}download(e){const t=e??this.getActiveDocumentId();this.downloadRequest$.emit({documentId:t})}saveAsCopy(e){const t=e??this.getActiveDocumentId(),n=this.coreState.core.documents[t];return(null==n?void 0:n.document)?this.engine.saveAsCopy(n.document):Jt.reject({code:Qt.DocNotOpen,message:`Document ${t} not found`})}saveAsCopyAndGetBufferAndName(e){const t=new Ct,n=this.coreState.core.documents[e];return(null==n?void 0:n.document)?(this.saveAsCopy(e).wait(e=>{t.resolve({buffer:e,name:n.name??this.config.defaultFileName})},e=>t.fail(e)),t):Jt.reject({code:Qt.DocNotOpen,message:`Document ${e} not found`})}onRequest(e){return this.downloadRequest$.on(e)}async initialize(e){this.logger.info("ExportPlugin","Initialize","Export plugin initialized")}async destroy(){this.downloadRequest$.clear(),await super.destroy()}};um.id="export";let hm=um;const mm="export";const gm=Do({manifest:{id:mm,name:"Export Plugin",version:"1.0.0",provides:["export"],requires:[],optional:[],defaultConfig:{defaultFileName:"document.pdf"}},create:(e,t)=>new hm(mm,e,t),reducer:()=>{},initialState:{}}).addUtility(function(){const{plugin:e}=Eo(hm.id),t=De(null);return Ae(()=>{if(!e)return;return e.onRequest(n=>{const o=t.current;if(!o)return;e.saveAsCopyAndGetBufferAndName(n.documentId).wait(({buffer:e,name:t})=>{const n=URL.createObjectURL(new Blob([e]));o.href=n,o.download=t,o.click(),URL.revokeObjectURL(n)},En)})},[e]),He("a",{style:{display:"none"},ref:t})}).build(),pm="PAN/INIT_STATE",fm="PAN/CLEANUP_STATE",vm="PAN/SET_PAN_MODE";const ym=class extends fo{constructor(e,t,n){var o,i,r;super(e,t),this.panMode$=Mo(),this.documentHandlers=new Map,this.config=n,this.interactionManager=null==(o=t.getPlugin(rh.id))?void 0:o.provides(),this.viewport=null==(i=t.getPlugin(ai.id))?void 0:i.provides(),this.interactionManager&&(this.interactionManager.registerMode({id:"panMode",scope:"global",exclusive:!1,cursor:"grab",wantsRawTouch:!1}),null==(r=this.interactionManager)||r.onModeChange(e=>{const t="panMode"===e.activeMode,n=this.getDocumentState(e.documentId);n&&n.isPanMode!==t&&this.dispatch(function(e,t){return{type:vm,payload:{documentId:e,isPanMode:t}}}(e.documentId,t))}))}onDocumentLoadingStarted(e){this.dispatch(function(e,t){return{type:pm,payload:{documentId:e,state:t}}}(e,{isPanMode:!1})),this.registerPanHandlersForDocument(e),"always"===this.config.defaultMode&&this.makePanDefault(!0),this.logger.debug("PanPlugin","DocumentOpened",`Initialized pan state for document: ${e}`)}onDocumentClosed(e){const t=this.documentHandlers.get(e);t&&(t(),this.documentHandlers.delete(e)),this.dispatch(function(e){return{type:fm,payload:e}}(e)),this.logger.debug("PanPlugin","DocumentClosed",`Cleaned up pan state for document: ${e}`)}buildCapability(){return{enablePan:()=>this.enablePan(),disablePan:()=>this.disablePan(),togglePan:()=>this.togglePan(),makePanDefault:e=>this.makePanDefault(e),isPanMode:()=>this.isPanMode(),forDocument:e=>this.createPanScope(e),onPanModeChange:this.panMode$.on}}createPanScope(e){return{enablePan:()=>this.enablePan(e),disablePan:()=>this.disablePan(e),togglePan:()=>this.togglePan(e),isPanMode:()=>this.isPanMode(e),onPanModeChange:t=>this.panMode$.on(n=>{n.documentId===e&&t(n.isPanMode)})}}getDocumentState(e){const t=e??this.getActiveDocumentId();return this.state.documents[t]??null}getDocumentStateOrThrow(e){const t=this.getDocumentState(e);if(!t)throw new Error(`Pan state not found for document: ${e??"active"}`);return t}enablePan(e){const t=e??this.getActiveDocumentId();this.interactionManager.forDocument(t).activate("panMode")}disablePan(e){const t=e??this.getActiveDocumentId();this.interactionManager.forDocument(t).activateDefaultMode()}togglePan(e){const t=e??this.getActiveDocumentId(),n=this.interactionManager.forDocument(t);"panMode"===n.getActiveMode()?n.activateDefaultMode():n.activate("panMode")}makePanDefault(e=!0){this.interactionManager&&(this.interactionManager.setDefaultMode("panMode"),e&&this.interactionManager.activateDefaultMode())}isPanMode(e){return this.getDocumentStateOrThrow(e).isPanMode}registerPanHandlersForDocument(e){if(!this.interactionManager||!this.viewport)return;let t=null;const n=this.interactionManager.forDocument(e),o=this.viewport.forDocument(e),i={onMouseDown:(e,i)=>{const r=o.getMetrics();t={startX:i.clientX,startY:i.clientY,startLeft:r.scrollLeft,startTop:r.scrollTop},n.setCursor("panMode","grabbing",10)},onMouseMove:(e,n)=>{if(!t)return;const i=n.clientX-t.startX,r=n.clientY-t.startY;o.scrollTo({x:t.startLeft-i,y:t.startTop-r})},onMouseUp:()=>{t&&(t=null,n.removeCursor("panMode"))},onMouseLeave:()=>{t&&(t=null,n.removeCursor("panMode"))},onMouseCancel:()=>{t&&(t=null,n.removeCursor("panMode"))}},r=this.interactionManager.registerHandlers({documentId:e,modeId:"panMode",handlers:i});this.documentHandlers.set(e,r)}onStoreUpdated(e,t){for(const n in t.documents){const o=e.documents[n],i=t.documents[n];(null==o?void 0:o.isPanMode)!==i.isPanMode&&(this.panMode$.emit({documentId:n,isPanMode:i.isPanMode}),this.logger.debug("PanPlugin","PanModeChanged",`Pan mode changed for document ${n}: ${(null==o?void 0:o.isPanMode)??!1} -> ${i.isPanMode}`))}}async initialize(e){this.logger.info("PanPlugin","Initialize","Pan plugin initialized")}async destroy(){this.documentHandlers.forEach(e=>e()),this.documentHandlers.clear(),this.panMode$.clear(),await super.destroy()}};ym.id="pan";let bm=ym;const wm={documents:{},activeDocumentId:null},xm=Do({manifest:{id:"pan",name:"Pan Plugin",version:"1.0.0",provides:["pan"],requires:["interaction-manager","viewport"],optional:[],defaultConfig:{defaultMode:"mobile"}},create:(e,t)=>new bm("pan",e,t),reducer:(e=wm,t)=>{switch(t.type){case pm:{const{documentId:n,state:o}=t.payload;return{...e,documents:{...e.documents,[n]:o},activeDocumentId:e.activeDocumentId??n}}case fm:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i,activeDocumentId:e.activeDocumentId===n?null:e.activeDocumentId}}case"PAN/SET_ACTIVE_DOCUMENT":return{...e,activeDocumentId:t.payload};case vm:{const{documentId:n,isPanMode:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,isPanMode:o}}}:e}default:return e}},initialState:wm}).addUtility(()=>{const{provides:e}=_o(bm.id),{plugin:t}=Eo(bm.id);return Ae(()=>{var n;if(!e||!t)return;const o=(null==(n=t.config)?void 0:n.defaultMode)??"never",i="undefined"!=typeof window&&("ontouchstart"in window||navigator.maxTouchPoints>0);"mobile"===o&&i&&e.makePanDefault()},[e,t]),null}).build(),Cm="capture",Im={id:Cm,name:"Capture Plugin",version:"1.0.0",provides:["capture"],requires:["render"],optional:["interaction-manager"],defaultConfig:{scale:1,imageType:"image/png",withAnnotations:!1}};const km="CAPTURE/INIT_STATE",Sm="CAPTURE/CLEANUP_STATE",Mm="CAPTURE/SET_MARQUEE_CAPTURE_ACTIVE";const Am={isMarqueeCaptureActive:!1},Pm={documents:{},activeDocumentId:null},Dm=class extends fo{constructor(e,t,n){var o;super(e,t),this.captureArea$=So(),this.state$=Mo(),this.config=n,this.renderCapability=this.registry.getPlugin("render").provides(),this.interactionManagerCapability=null==(o=this.registry.getPlugin("interaction-manager"))?void 0:o.provides(),this.interactionManagerCapability&&(this.interactionManagerCapability.registerMode({id:"marqueeCapture",scope:"page",exclusive:!0,cursor:"crosshair"}),this.interactionManagerCapability.onModeChange(e=>{const t="marqueeCapture"===e.activeMode,n=this.getDocumentState(e.documentId);var o;n&&n.isMarqueeCaptureActive!==t&&this.dispatch((o=e.documentId,{type:Mm,payload:{documentId:o,isActive:t}}))}))}onDocumentLoadingStarted(e){const t={...Am};this.dispatch(function(e,t){return{type:km,payload:{documentId:e,state:t}}}(e,t)),this.logger.debug("CapturePlugin","DocumentOpened",`Initialized capture state for document: ${e}`)}onDocumentClosed(e){this.dispatch(function(e){return{type:Sm,payload:e}}(e)),this.logger.debug("CapturePlugin","DocumentClosed",`Cleaned up capture state for document: ${e}`)}async initialize(e){}buildCapability(){return{captureArea:(e,t)=>this.captureArea(e,t),enableMarqueeCapture:()=>this.enableMarqueeCapture(),disableMarqueeCapture:()=>this.disableMarqueeCapture(),toggleMarqueeCapture:()=>this.toggleMarqueeCapture(),isMarqueeCaptureActive:()=>this.isMarqueeCaptureActive(),getState:()=>this.getDocumentStateOrThrow(),forDocument:e=>this.createCaptureScope(e),registerMarqueeOnPage:e=>this.registerMarqueeOnPage(e),onCaptureArea:this.captureArea$.on,onStateChange:this.state$.on}}createCaptureScope(e){return{captureArea:(t,n)=>this.captureArea(t,n,e),enableMarqueeCapture:()=>this.enableMarqueeCapture(e),disableMarqueeCapture:()=>this.disableMarqueeCapture(e),toggleMarqueeCapture:()=>this.toggleMarqueeCapture(e),isMarqueeCaptureActive:()=>this.isMarqueeCaptureActive(e),getState:()=>this.getDocumentStateOrThrow(e),onCaptureArea:t=>this.captureArea$.on(n=>{n.documentId===e&&t(n)}),onStateChange:t=>this.state$.on(n=>{n.documentId===e&&t(n.state)})}}getDocumentState(e){const t=e??this.getActiveDocumentId();return this.state.documents[t]??null}getDocumentStateOrThrow(e){const t=this.getDocumentState(e);if(!t)throw new Error(`Capture state not found for document: ${e??"active"}`);return t}registerMarqueeOnPage(e){if(!this.interactionManagerCapability)return this.logger.warn("CapturePlugin","MissingDependency","Interaction manager plugin not loaded, marquee capture disabled"),()=>{};const t=this.coreState.core.documents[e.documentId];if(!t||!t.document)return this.logger.warn("CapturePlugin","DocumentNotFound","Document not found"),()=>{};const n=t.document.pages[e.pageIndex];if(!n)return this.logger.warn("CapturePlugin","PageNotFound",`Page ${e.pageIndex} not found`),()=>{};const o=function(e){const{pageSize:t,scale:n,minDragPx:o=5,onPreview:i,onCommit:r}=e;let a=null,s=null;return{onPointerDown:(e,t)=>{var n;a=e,s={origin:{x:e.x,y:e.y},size:{width:0,height:0}},null==i||i(s),null==(n=t.setPointerCapture)||n.call(t)},onPointerMove:e=>{if(!a)return;const n=wo(e.x,0,t.width),o=wo(e.y,0,t.height);s={origin:{x:Math.min(a.x,n),y:Math.min(a.y,o)},size:{width:Math.abs(n-a.x),height:Math.abs(o-a.y)}},null==i||i(s)},onPointerUp:(e,t)=>{var l;s&&Math.max(s.size.width,s.size.height)*n>o&&(null==r||r(s)),a=null,s=null,null==i||i(null),null==(l=t.releasePointerCapture)||l.call(t)},onPointerCancel:(e,t)=>{var n;a=null,s=null,null==i||i(null),null==(n=t.releasePointerCapture)||n.call(t)}}}({pageSize:n.size,scale:e.scale,onPreview:e.callback.onPreview,onCommit:t=>{var n,o;this.captureArea(e.pageIndex,t,e.documentId),null==(o=(n=e.callback).onCommit)||o.call(n,t)}});return this.interactionManagerCapability.registerHandlers({documentId:e.documentId,modeId:"marqueeCapture",handlers:o,pageIndex:e.pageIndex})}captureArea(e,t,n){const o=n??this.getActiveDocumentId();this.disableMarqueeCapture(o);this.renderCapability.forDocument(o).renderPageRect({pageIndex:e,rect:t,options:{imageType:this.config.imageType,scaleFactor:this.config.scale,withAnnotations:this.config.withAnnotations||!1}}).wait(n=>{this.captureArea$.emit({documentId:o,pageIndex:e,rect:t,blob:n,imageType:this.config.imageType||"image/png",scale:this.config.scale||1,withAnnotations:this.config.withAnnotations||!1})},En)}enableMarqueeCapture(e){var t;const n=e??this.getActiveDocumentId();null==(t=this.interactionManagerCapability)||t.forDocument(n).activate("marqueeCapture")}disableMarqueeCapture(e){var t;const n=e??this.getActiveDocumentId();null==(t=this.interactionManagerCapability)||t.forDocument(n).activateDefaultMode()}toggleMarqueeCapture(e){var t;const n=e??this.getActiveDocumentId(),o=null==(t=this.interactionManagerCapability)?void 0:t.forDocument(n);"marqueeCapture"===(null==o?void 0:o.getActiveMode())?o.activateDefaultMode():null==o||o.activate("marqueeCapture")}isMarqueeCaptureActive(e){var t;const n=e??this.getActiveDocumentId();return"marqueeCapture"===(null==(t=this.interactionManagerCapability)?void 0:t.forDocument(n).getActiveMode())}onStoreUpdated(e,t){for(const n in t.documents){const o=e.documents[n],i=t.documents[n];o&&i&&o.isMarqueeCaptureActive!==i.isMarqueeCaptureActive&&this.state$.emit({documentId:n,state:i})}}async destroy(){this.captureArea$.clear(),this.state$.clear(),super.destroy()}};Dm.id="capture";let Rm=Dm;const zm={manifest:Im,create:(e,t)=>new Rm(Cm,e,t),reducer:(e=Pm,t)=>{switch(t.type){case km:{const{documentId:n,state:o}=t.payload;return{...e,documents:{...e.documents,[n]:o},activeDocumentId:e.activeDocumentId??n}}case Sm:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i,activeDocumentId:e.activeDocumentId===n?null:e.activeDocumentId}}case"CAPTURE/SET_ACTIVE_DOCUMENT":return{...e,activeDocumentId:t.payload};case Mm:{const{documentId:n,isActive:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,isMarqueeCaptureActive:o}}}:e}default:return e}},initialState:Pm},Tm=()=>_o(Rm.id),Em=({documentId:e,pageIndex:t,scale:n,className:o,stroke:i="rgba(33,150,243,0.8)",fill:r="rgba(33,150,243,0.15)"})=>{const{provides:a}=Tm(),s=Oo(e),[l,c]=Se(null),d=Re(()=>void 0!==n?n:(null==s?void 0:s.scale)??1,[n,null==s?void 0:s.scale]);return Ae(()=>{if(a)return a.registerMarqueeOnPage({documentId:e,pageIndex:t,scale:d,callback:{onPreview:c}})},[a,e,t,d]),l?He("div",{style:{position:"absolute",pointerEvents:"none",left:l.origin.x*d,top:l.origin.y*d,width:l.size.width*d,height:l.size.height*d,border:`1px solid ${i}`,background:r,boxSizing:"border-box"},className:o}):null},_m="history",Nm={id:_m,name:"History Plugin",version:"1.0.0",provides:["history"],requires:[],optional:[],defaultConfig:{}},Om="HISTORY/INIT_STATE",Lm="HISTORY/CLEANUP_STATE",$m="HISTORY/SET_DOCUMENT_STATE",jm=class extends fo{constructor(e,t){super(e,t),this.documentHistories=new Map,this.historyChange$=So()}async initialize(e){this.logger.info("HistoryPlugin","Initialize","History plugin initialized")}onDocumentLoadingStarted(e){this.dispatch((e=>({type:Om,payload:{documentId:e}}))(e)),this.documentHistories.set(e,{topicHistories:new Map,globalTimeline:[],globalIndex:-1}),this.logger.debug("HistoryPlugin","DocumentOpened",`Initialized history state for document: ${e}`)}onDocumentClosed(e){this.dispatch((e=>({type:Lm,payload:{documentId:e}}))(e)),this.documentHistories.delete(e),this.logger.debug("HistoryPlugin","DocumentClosed",`Cleaned up history state for document: ${e}`)}getDocumentHistoryData(e){const t=e??this.getActiveDocumentId(),n=this.documentHistories.get(t);if(!n)throw new Error(`History data not found for document: ${t}`);return n}getDocumentHistoryState(e){const t=this.documentHistories.get(e);if(!t)throw new Error(`History data not found for document: ${e}`);const n={};return Array.from(t.topicHistories.entries()).forEach(([e,t])=>{n[e]={canUndo:t.currentIndex>-1,canRedo:t.currentIndex-1,canRedo:t.globalIndex({type:$m,payload:{documentId:e,state:t}}))(e,n)),this.historyChange$.emit({documentId:e,topic:t,state:n})}register(e,t,n){const o=this.getDocumentHistoryData(n);o.topicHistories.has(t)||o.topicHistories.set(t,{commands:[],currentIndex:-1});const i=o.topicHistories.get(t);i.commands.splice(i.currentIndex+1),i.commands.push(e),i.currentIndex++;const r={command:e,topic:t};o.globalTimeline.splice(o.globalIndex+1),o.globalTimeline.push(r),o.globalIndex++,e.execute(),this.emitHistoryChange(n,t)}undo(e,t){const n=this.getDocumentHistoryData(t);let o;if(e){const t=n.topicHistories.get(e);t&&t.currentIndex>-1&&(t.commands[t.currentIndex].undo(),t.currentIndex--,o=e)}else if(n.globalIndex>-1){const e=n.globalTimeline[n.globalIndex];e.command.undo(),n.topicHistories.get(e.topic).currentIndex--,n.globalIndex--,o=e.topic}o&&this.emitHistoryChange(t,o)}redo(e,t){const n=this.getDocumentHistoryData(t);let o;if(e){const t=n.topicHistories.get(e);t&&t.currentIndex-1}return n.globalIndex>-1}canRedo(e,t){const n=this.getDocumentHistoryData(t);if(e){const t=n.topicHistories.get(e);return!!t&&t.currentIndexe(t.metadata),a=t?[t]:Array.from(o.topicHistories.keys());for(const e of a){const t=o.topicHistories.get(e);if(!t)continue;const n=[];let a=0;for(let e=0;e0&&(this.emitHistoryChange(n,t),this.logger.debug("HistoryPlugin","PurgeByMetadata",`Purged ${i} history entries for document: ${n}${t?`, topic: ${t}`:""}`)),i}createHistoryScope(e){return{register:(t,n)=>this.register(t,n,e),undo:t=>this.undo(t,e),redo:t=>this.redo(t,e),canUndo:t=>this.canUndo(t,e),canRedo:t=>this.canRedo(t,e),getHistoryState:()=>this.getDocumentHistoryState(e),onHistoryChange:t=>this.historyChange$.on(n=>{n.documentId===e&&t(n.topic)}),purgeByMetadata:(t,n)=>this.purgeByMetadata(t,n,e)}}buildCapability(){return{register:(e,t)=>{const n=this.getActiveDocumentId();this.register(e,t,n)},undo:e=>{const t=this.getActiveDocumentId();this.undo(e,t)},redo:e=>{const t=this.getActiveDocumentId();this.redo(e,t)},canUndo:e=>{const t=this.getActiveDocumentId();return this.canUndo(e,t)},canRedo:e=>{const t=this.getActiveDocumentId();return this.canRedo(e,t)},getHistoryState:()=>{const e=this.getActiveDocumentId();return this.getDocumentHistoryState(e)},forDocument:e=>this.createHistoryScope(e),onHistoryChange:this.historyChange$.on,purgeByMetadata:(e,t)=>{const n=this.getActiveDocumentId();return this.purgeByMetadata(e,t,n)}}}async destroy(){this.historyChange$.clear(),this.documentHistories.clear(),super.destroy()}};jm.id="history";let Fm=jm;const Um={global:{canUndo:!1,canRedo:!1},topics:{}},Hm={documents:{},activeDocumentId:null},Bm={manifest:Nm,create:e=>new Fm(_m,e),reducer:(e=Hm,t)=>{switch(t.type){case Om:{const{documentId:n}=t.payload;return{...e,documents:{...e.documents,[n]:{...Um}}}}case Lm:{const{documentId:n}=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i,activeDocumentId:e.activeDocumentId===n?null:e.activeDocumentId}}case $m:{const{documentId:n,state:o}=t.payload;return e.documents[n]?{...e,documents:{...e.documents,[n]:o}}:e}case"HISTORY/SET_ACTIVE_DOCUMENT":return{...e,activeDocumentId:t.payload};default:return e}},initialState:Hm};var Wm=(e=>(e.Redact="redact",e.MarqueeRedact="marqueeRedact",e.RedactSelection="redactSelection",e))(Wm||{});const qm="REDACTION/INIT_STATE",Gm="REDACTION/CLEANUP_STATE",Vm="START_REDACTION",Km="END_REDACTION",Zm="ADD_PENDING",Ym="REMOVE_PENDING",Xm="UPDATE_PENDING",Qm="CLEAR_PENDING",Jm="SELECT_PENDING",eg="DESELECT_PENDING";const tg=(e,t)=>({type:Zm,payload:{documentId:e,items:t}}),ng=(e,t,n)=>({type:Ym,payload:{documentId:e,page:t,id:n}}),og=e=>({type:Qm,payload:e}),ig=(e,t,n,o)=>({type:Xm,payload:{documentId:e,page:t,id:n,patch:o}}),rg=(e,t,n)=>({type:Jm,payload:{documentId:e,page:t,id:n}}),ag=e=>({type:eg,payload:e}),sg=e=>Object.values(e).reduce((e,t)=>e+t.length,0),lg={isRedacting:!1,activeType:null,pending:{},pendingCount:0,selected:null},cg={documents:{},activeDocumentId:null},dg={id:"redact",name:"Redact",matchScore:e=>e.type===_t.REDACT?10:0,interaction:{mode:Wm.Redact,exclusive:!1,cursor:"crosshair",textSelection:!0,isDraggable:e=>{var t;return e.type!==_t.REDACT||!(null==(t=e.segmentRects)?void 0:t.length)},isResizable:e=>{var t;return e.type!==_t.REDACT||!(null==(t=e.segmentRects)?void 0:t.length)},isRotatable:!1,lockAspectRatio:!1,isGroupDraggable:!1,isGroupResizable:!1,isGroupRotatable:!1},defaults:{type:_t.REDACT,color:"#000000",overlayColor:"#FFFFFF",strokeColor:"#E44234",opacity:1}},ug=[dg],hg=class extends fo{constructor(e,t,n){var o,i,r,a;if(super(e,t),this.redactionSelection$=new Map,this.redactionMarquee$=new Map,this.pending$=Mo(),this.selected$=Mo(),this.state$=Mo(),this.events$=Mo(),this.documentUnsubscribers=new Map,this.config=n,this.selectionCapability=null==(o=this.registry.getPlugin("selection"))?void 0:o.provides(),this.interactionManagerCapability=null==(i=this.registry.getPlugin("interaction-manager"))?void 0:i.provides(),this.annotationCapability=null==(r=this.registry.getPlugin("annotation"))?void 0:r.provides(),this.historyCapability=null==(a=this.registry.getPlugin("history"))?void 0:a.provides(),this.config.useAnnotationMode?this.annotationCapability?this.useAnnotationMode=!0:(this.logger.warn("RedactionPlugin","ConfigError","useAnnotationMode is enabled but annotation plugin is not available. Falling back to legacy mode."),this.useAnnotationMode=!1):this.useAnnotationMode=!1,this.useAnnotationMode)for(const e of ug)this.annotationCapability.addTool(e);this.setupRedactionModes(),!this.useAnnotationMode&&this.annotationCapability&&this.logger.info("RedactionPlugin","LegacyMode","Using legacy redaction mode. Set useAnnotationMode: true in config to use annotation-based redactions."),this.setupModeChangeListener()}setupRedactionModes(){this.interactionManagerCapability&&(this.interactionManagerCapability.registerMode({id:Wm.Redact,scope:"page",exclusive:!1,cursor:"crosshair"}),this.interactionManagerCapability.registerMode({id:Wm.MarqueeRedact,scope:"page",exclusive:!1,cursor:"crosshair"}),this.interactionManagerCapability.registerMode({id:Wm.RedactSelection,scope:"page",exclusive:!1}))}setupModeChangeListener(){var e;null==(e=this.interactionManagerCapability)||e.onModeChange(e=>{const t=e.documentId;if(e.activeMode===Wm.Redact||e.activeMode===Wm.MarqueeRedact||e.activeMode===Wm.RedactSelection)this.dispatch(((e,t)=>({type:Vm,payload:{documentId:e,mode:t}}))(t,e.activeMode));else{const e=this.getDocumentState(t);(null==e?void 0:e.isRedacting)&&this.dispatch((e=>({type:Km,payload:e}))(t))}})}onDocumentLoadingStarted(e){this.dispatch(function(e,t){return{type:qm,payload:{documentId:e,state:t}}}(e,{...lg})),this.redactionSelection$.set(e,Mo()),this.redactionMarquee$.set(e,Mo());const t=[];if(this.selectionCapability){const n=this.selectionCapability.forDocument(e),o=n.onSelectionChange(()=>{const t=this.getDocumentState(e);if(!(null==t?void 0:t.isRedacting))return;const o=n.getFormattedSelection(),i=this.redactionSelection$.get(e);null==i||i.emit(o)}),i=n.onEndSelection(()=>{const t=this.getDocumentState(e);if(!(null==t?void 0:t.isRedacting))return;if(!this.checkPermission(e,Zt.ModifyContents))return;const o=n.getFormattedSelection();if(!o.length)return;const i=n.getSelectedText(),r=this.redactionSelection$.get(e);null==r||r.emit([]),n.clear(),i.wait(t=>{const n=t.join(" ");this.createRedactionsFromSelection(e,o,n)},()=>{this.createRedactionsFromSelection(e,o)})}),r=n.onMarqueeChange(t=>{var n;const o=this.getDocumentState(e);(null==o?void 0:o.isRedacting)&&(null==(n=this.redactionMarquee$.get(e))||n.emit({pageIndex:t.pageIndex,rect:t.rect,modeId:t.modeId}))}),a=n.onMarqueeEnd(t=>{const n=this.getDocumentState(e);if((null==n?void 0:n.isRedacting)&&this.checkPermission(e,Zt.ModifyContents))if(this.useAnnotationMode)this.createRedactAnnotationFromArea(e,t.pageIndex,t.rect);else{const n=this.config.drawBlackBoxes?"#000000":"transparent",o={id:zn(),kind:"area",page:t.pageIndex,rect:t.rect,source:"legacy",markColor:"#FF0000",redactionColor:n};this.dispatch(tg(e,[o])),this.selectPending(t.pageIndex,o.id,e)}}),s=n.onEmptySpaceClick(()=>{this.deselectPending(e)});t.push(o,i,r,a,s)}if(this.useAnnotationMode&&this.annotationCapability){const n=this.annotationCapability.forDocument(e),o=n.onAnnotationEvent(t=>{var n;if("loaded"===t.type)return void this.syncFromAnnotationLoad(e);if((null==(n=t.annotation)?void 0:n.type)!==_t.REDACT)return;const o=t.annotation;"create"===t.type?(this.syncFromAnnotationCreate(e,o),this.events$.emit({type:"add",documentId:e,items:[this.annotationToRedactionItem(o)]})):"update"===t.type?(this.logger.debug("RedactionPlugin","AnnotationUpdated",{documentId:e,redactAnno:o,patch:t.patch}),this.syncFromAnnotationUpdate(e,o,t.patch)):"delete"===t.type&&(this.syncFromAnnotationDelete(e,o),this.events$.emit({type:"remove",documentId:e,page:o.pageIndex,id:o.id}))}),i=n.onStateChange(()=>{this.syncSelectionFromAnnotation(e)});t.push(o,i)}this.documentUnsubscribers.set(e,t),this.logger.debug("RedactionPlugin","DocumentOpened",`Initialized redaction state for document: ${e}`)}onDocumentLoaded(e){var t,n,o;null==(t=this.selectionCapability)||t.enableForMode(Wm.Redact,{enableSelection:!0,showSelectionRects:!1,enableMarquee:!0,showMarqueeRects:!1},e),null==(n=this.selectionCapability)||n.enableForMode(Wm.MarqueeRedact,{enableSelection:!1,enableMarquee:!0,showMarqueeRects:!1},e),null==(o=this.selectionCapability)||o.enableForMode(Wm.RedactSelection,{enableSelection:!0,showSelectionRects:!1},e)}onDocumentClosed(e){this.dispatch(function(e){return{type:Gm,payload:e}}(e));const t=this.redactionSelection$.get(e);null==t||t.clear(),this.redactionSelection$.delete(e);const n=this.redactionMarquee$.get(e);null==n||n.clear(),this.redactionMarquee$.delete(e);const o=this.documentUnsubscribers.get(e);o&&(o.forEach(e=>e()),this.documentUnsubscribers.delete(e)),this.logger.debug("RedactionPlugin","DocumentClosed",`Cleaned up redaction state for document: ${e}`)}async initialize(e){this.logger.info("RedactionPlugin","Initialize","Redaction plugin initialized")}buildCapability(){return{queueCurrentSelectionAsPending:()=>this.queueCurrentSelectionAsPending(),enableRedact:()=>this.enableRedact(),toggleRedact:()=>this.toggleRedact(),isRedactActive:()=>this.isRedactActive(),endRedact:()=>this.endRedact(),enableMarqueeRedact:()=>this.enableMarqueeRedact(),toggleMarqueeRedact:()=>this.toggleMarqueeRedact(),isMarqueeRedactActive:()=>this.isMarqueeRedactActive(),enableRedactSelection:()=>this.enableRedactSelection(),toggleRedactSelection:()=>this.toggleRedactSelection(),isRedactSelectionActive:()=>this.isRedactSelectionActive(),addPending:e=>this.addPendingItems(e),removePending:(e,t)=>this.removePendingItem(e,t),clearPending:()=>this.clearPendingItems(),commitAllPending:()=>this.commitAllPending(),commitPending:(e,t)=>this.commitPendingOne(e,t),selectPending:(e,t)=>this.selectPending(e,t),getSelectedPending:()=>this.getSelectedPending(),deselectPending:()=>this.deselectPending(),getState:()=>this.getDocumentStateOrThrow(),forDocument:e=>this.createRedactionScope(e),onPendingChange:this.pending$.on,onSelectedChange:this.selected$.on,onRedactionEvent:this.events$.on,onStateChange:this.state$.on}}createRedactionScope(e){return{queueCurrentSelectionAsPending:()=>this.queueCurrentSelectionAsPending(e),enableRedact:()=>this.enableRedact(e),toggleRedact:()=>this.toggleRedact(e),isRedactActive:()=>this.isRedactActive(e),endRedact:()=>this.endRedact(e),enableMarqueeRedact:()=>this.enableMarqueeRedact(e),toggleMarqueeRedact:()=>this.toggleMarqueeRedact(e),isMarqueeRedactActive:()=>this.isMarqueeRedactActive(e),enableRedactSelection:()=>this.enableRedactSelection(e),toggleRedactSelection:()=>this.toggleRedactSelection(e),isRedactSelectionActive:()=>this.isRedactSelectionActive(e),addPending:t=>this.addPendingItems(t,e),removePending:(t,n)=>this.removePendingItem(t,n,e),clearPending:()=>this.clearPendingItems(e),commitAllPending:()=>this.commitAllPending(e),commitPending:(t,n)=>this.commitPendingOne(t,n,e),selectPending:(t,n)=>this.selectPending(t,n,e),getSelectedPending:()=>this.getSelectedPending(e),deselectPending:()=>this.deselectPending(e),getState:()=>this.getDocumentStateOrThrow(e),onPendingChange:t=>this.pending$.on(n=>{n.documentId===e&&t(n.pending)}),onSelectedChange:t=>this.selected$.on(n=>{n.documentId===e&&t(n.selected)}),onRedactionEvent:t=>this.events$.on(n=>{n.documentId===e&&t(n)}),onStateChange:t=>this.state$.on(n=>{n.documentId===e&&t(n.state)})}}getPendingFromAnnotations(e){if(!this.annotationCapability)return{};try{const t=this.annotationCapability.forDocument(e).getState(),n={};for(const e of Object.values(t.byUid))if(e.object.type===_t.REDACT){const t=this.annotationToRedactionItem(e.object),o=e.object.pageIndex;(n[o]??(n[o]=[])).push(t)}return n}catch{return{}}}getDocumentState(e){const t=e??this.getActiveDocumentId();return this.state.documents[t]??null}getDocumentStateOrThrow(e){const t=this.getDocumentState(e);if(!t)throw new Error(`Redaction state not found for document: ${e??"active"}`);return t}syncFromAnnotationCreate(e,t){const n=this.annotationToRedactionItem(t);this.dispatch(tg(e,[n]))}syncFromAnnotationUpdate(e,t,n){if(!("rect"in n||"segmentRects"in n||"strokeColor"in n||"color"in n))return;const o={};n.rect&&(o.rect=n.rect),n.segmentRects&&(o.rects=n.segmentRects),n.strokeColor&&(o.markColor=n.strokeColor),n.color&&(o.redactionColor=n.color),this.logger.debug("RedactionPlugin","AnnotationUpdated",{documentId:e,annotation:t,patch:o}),this.dispatch(ig(e,t.pageIndex,t.id,o))}syncFromAnnotationDelete(e,t){this.dispatch(ng(e,t.pageIndex,t.id))}syncFromAnnotationLoad(e){const t=this.getPendingFromAnnotations(e);this.dispatch(og(e));for(const[,n]of Object.entries(t))n.length>0&&this.dispatch(tg(e,n))}syncSelectionFromAnnotation(e){var t;const n=null==(t=this.annotationCapability)?void 0:t.forDocument(e).getState();if(!n)return;const o=n.selectedUids.map(e=>n.byUid[e]).find(e=>(null==e?void 0:e.object.type)===_t.REDACT);if(o){const t=o.object;this.dispatch(rg(e,t.pageIndex,t.id))}else{const t=this.getDocumentState(e);(null==t?void 0:t.selected)&&this.dispatch(ag(e))}}addPendingItems(e,t){const n=t??this.getActiveDocumentId();if(this.checkPermission(n,Zt.ModifyContents)){if(this.useAnnotationMode){const t=this.annotationCapability.forDocument(n);for(const n of e){const e=this.redactionItemToAnnotation(n);t.createAnnotation(n.page,e)}if(e.length>0){const n=e[e.length-1];t.selectAnnotation(n.page,n.id)}}else this.dispatch(tg(n,e));this.events$.emit({type:"add",documentId:n,items:e})}else this.logger.debug("RedactionPlugin","AddPendingItems",`Cannot add redactions: document ${n} lacks ModifyContents permission`)}removePendingItem(e,t,n){var o;const i=n??this.getActiveDocumentId();this.useAnnotationMode?null==(o=this.annotationCapability)||o.forDocument(i).deleteAnnotation(e,t):this.dispatch(ng(i,e,t)),this.events$.emit({type:"remove",documentId:i,page:e,id:t})}clearPendingItems(e){var t;const n=e??this.getActiveDocumentId();if(this.useAnnotationMode){const e=this.getPendingFromAnnotations(n),o=null==(t=this.annotationCapability)?void 0:t.forDocument(n);for(const[t,n]of Object.entries(e)){const e=Number(t);for(const t of n)null==o||o.deleteAnnotation(e,t.id)}}else this.dispatch(og(n));this.events$.emit({type:"clear",documentId:n})}selectPending(e,t,n){var o,i,r;const a=n??this.getActiveDocumentId();this.useAnnotationMode?null==(o=this.annotationCapability)||o.forDocument(a).selectAnnotation(e,t):(this.dispatch(rg(a,e,t)),null==(i=this.interactionManagerCapability)||i.claimPageActivity(a,"redaction-selection",e)),null==(r=this.selectionCapability)||r.forDocument(a).clear()}getSelectedPending(e){var t;const n=e??this.getActiveDocumentId();return(null==(t=this.getDocumentState(n))?void 0:t.selected)??null}deselectPending(e){var t,n;const o=e??this.getActiveDocumentId();this.useAnnotationMode?null==(t=this.annotationCapability)||t.forDocument(o).deselectAnnotation():(this.dispatch(ag(o)),null==(n=this.interactionManagerCapability)||n.releasePageActivity(o,"redaction-selection"))}enableRedactSelection(e){var t;const n=e??this.getActiveDocumentId();this.checkPermission(n,Zt.ModifyContents)?null==(t=this.interactionManagerCapability)||t.forDocument(n).activate(Wm.RedactSelection):this.logger.debug("RedactionPlugin","EnableRedactSelection",`Cannot enable redact selection: document ${n} lacks ModifyContents permission`)}toggleRedactSelection(e){var t;const n=e??this.getActiveDocumentId(),o=null==(t=this.interactionManagerCapability)?void 0:t.forDocument(n);if((null==o?void 0:o.getActiveMode())===Wm.RedactSelection)null==o||o.activateDefaultMode();else{if(!this.checkPermission(n,Zt.ModifyContents))return;null==o||o.activate(Wm.RedactSelection)}}isRedactSelectionActive(e){var t;const n=e??this.getActiveDocumentId(),o=null==(t=this.interactionManagerCapability)?void 0:t.forDocument(n).getActiveMode();return o===Wm.Redact||o===Wm.RedactSelection}enableMarqueeRedact(e){var t;const n=e??this.getActiveDocumentId();this.checkPermission(n,Zt.ModifyContents)?null==(t=this.interactionManagerCapability)||t.forDocument(n).activate(Wm.MarqueeRedact):this.logger.debug("RedactionPlugin","EnableMarqueeRedact",`Cannot enable marquee redact: document ${n} lacks ModifyContents permission`)}toggleMarqueeRedact(e){var t;const n=e??this.getActiveDocumentId(),o=null==(t=this.interactionManagerCapability)?void 0:t.forDocument(n);if((null==o?void 0:o.getActiveMode())===Wm.MarqueeRedact)null==o||o.activateDefaultMode();else{if(!this.checkPermission(n,Zt.ModifyContents))return;null==o||o.activate(Wm.MarqueeRedact)}}isMarqueeRedactActive(e){var t;const n=e??this.getActiveDocumentId(),o=null==(t=this.interactionManagerCapability)?void 0:t.forDocument(n).getActiveMode();return o===Wm.Redact||o===Wm.MarqueeRedact}enableRedact(e){var t;const n=e??this.getActiveDocumentId();this.checkPermission(n,Zt.ModifyContents)?null==(t=this.interactionManagerCapability)||t.forDocument(n).activate(Wm.Redact):this.logger.debug("RedactionPlugin","EnableRedact",`Cannot enable redact mode: document ${n} lacks ModifyContents permission`)}toggleRedact(e){var t;const n=e??this.getActiveDocumentId(),o=null==(t=this.interactionManagerCapability)?void 0:t.forDocument(n);if((null==o?void 0:o.getActiveMode())===Wm.Redact)null==o||o.activateDefaultMode();else{if(!this.checkPermission(n,Zt.ModifyContents))return;null==o||o.activate(Wm.Redact)}}isRedactActive(e){var t;const n=e??this.getActiveDocumentId();return(null==(t=this.interactionManagerCapability)?void 0:t.forDocument(n).getActiveMode())===Wm.Redact}endRedact(e){var t;const n=e??this.getActiveDocumentId();null==(t=this.interactionManagerCapability)||t.forDocument(n).activateDefaultMode()}onRedactionSelectionChange(e,t){const n=this.redactionSelection$.get(e);return(null==n?void 0:n.on(t))??(()=>{})}onRedactionMarqueeChange(e,t){const n=this.redactionMarquee$.get(e);return(null==n?void 0:n.on(t))??(()=>{})}getPreviewStrokeColor(){if(this.useAnnotationMode&&this.annotationCapability){const e=this.annotationCapability.getTool("redact");return(null==e?void 0:e.defaults.strokeColor)??"#FF0000"}return"#FF0000"}queueCurrentSelectionAsPending(e){const t=e??this.getActiveDocumentId();if(!this.selectionCapability)return Jt.reject({code:Qt.NotFound,message:"[RedactionPlugin] selection plugin required"});const n=this.coreState.core.documents[t];if(!(null==n?void 0:n.document))return Jt.reject({code:Qt.NotFound,message:"Document not found"});const o=this.selectionCapability.forDocument(t),i=o.getFormattedSelection();if(!i.length)return Jt.resolve(!0);const r=o.getSelectedText(),a=this.redactionSelection$.get(t);null==a||a.emit([]),o.clear(),this.useAnnotationMode||this.enableRedactSelection(t);const s=new Ct;return r.wait(e=>{const n=e.join(" ");this.createRedactionsFromSelection(t,i,n),s.resolve(!0)},()=>{this.createRedactionsFromSelection(t,i),s.resolve(!0)}),s}commitPendingOne(e,t,n){const o=n??this.getActiveDocumentId();if(!this.checkPermission(o,Zt.ModifyContents))return this.logger.debug("RedactionPlugin","CommitPendingOne",`Cannot commit redaction: document ${o} lacks ModifyContents permission`),Jt.reject({code:Qt.Security,message:"Document lacks ModifyContents permission"});const i=this.coreState.core.documents[o];if(!(null==i?void 0:i.document))return Jt.reject({code:Qt.NotFound,message:"Document not found"});const r=i.document.pages[e];if(!r)return Jt.reject({code:Qt.NotFound,message:"Page not found"});if(this.useAnnotationMode)return this.logger.debug("RedactionPlugin","CommitPendingOne",`Applying redaction in annotation mode: page ${e}, id ${t}`),this.applyRedactionAnnotationMode(o,i.document,r,t);const a=this.getDocumentState(o);if(!a)return Jt.reject({code:Qt.NotFound,message:"Document state not found"});const s=(a.pending[e]??[]).find(e=>e.id===t);return s?this.commitPendingOneLegacy(o,i.document,r,e,s):(this.logger.debug("RedactionPlugin","CommitPendingOne",`No pending item found for page ${e}, id ${t}`),Jt.resolve(!0))}commitPendingOneLegacy(e,t,n,o,i){const r="text"===i.kind?i.rects:[i.rect],a=new Ct;return this.engine.redactTextInRects(t,n,r,{drawBlackBoxes:this.config.drawBlackBoxes}).wait(()=>{this.dispatch(ng(e,o,i.id)),this.dispatchCoreAction(no(e,[o])),this.events$.emit({type:"commit",documentId:e,success:!0}),a.resolve(!0)},t=>{this.events$.emit({type:"commit",documentId:e,success:!1,error:t.reason}),a.reject({code:Qt.Unknown,message:"Failed to commit redactions"})}),a}applyRedactionAnnotationMode(e,t,n,o){var i;const r=new Ct,a=null==(i=this.annotationCapability)?void 0:i.forDocument(e).getAnnotationById(o);return this.logger.debug("RedactionPlugin","ApplyRedactionAnnotationMode",`Looking for annotation ${o}, found: ${!!a}, type: ${null==a?void 0:a.object.type}`),a&&a.object.type===_t.REDACT?(this.logger.debug("RedactionPlugin","ApplyRedactionAnnotationMode",`Calling engine.applyRedaction for annotation ${o} on page ${n.index}`),this.engine.applyRedaction(t,n,a.object).wait(()=>{var t,i;this.logger.debug("RedactionPlugin","ApplyRedactionAnnotationMode",`Successfully applied redaction ${o} on page ${n.index}`),null==(t=this.annotationCapability)||t.forDocument(e).purgeAnnotation(n.index,o),this.dispatch(ng(e,n.index,o)),null==(i=this.historyCapability)||i.forDocument(e).purgeByMetadata(e=>{var t;return(null==(t=null==e?void 0:e.annotationIds)?void 0:t.includes(o))??!1},"annotations"),this.dispatchCoreAction(no(e,[n.index])),this.events$.emit({type:"commit",documentId:e,success:!0}),r.resolve(!0)},t=>{var n;this.logger.error("RedactionPlugin","ApplyRedactionAnnotationMode",`Failed to apply redaction ${o}: ${(null==(n=t.reason)?void 0:n.message)??"Unknown error"}`),this.events$.emit({type:"commit",documentId:e,success:!1,error:t.reason}),r.reject({code:Qt.Unknown,message:"Failed to apply redaction"})}),r):(this.logger.warn("RedactionPlugin","ApplyRedactionAnnotationMode",`Redaction annotation not found or wrong type: ${o}`),Jt.reject({code:Qt.NotFound,message:"Redaction annotation not found"}))}commitAllPending(e){const t=e??this.getActiveDocumentId();if(!this.checkPermission(t,Zt.ModifyContents))return this.logger.debug("RedactionPlugin","CommitAllPending",`Cannot commit redactions: document ${t} lacks ModifyContents permission`),Jt.reject({code:Qt.Security,message:"Document lacks ModifyContents permission"});const n=this.coreState.core.documents[t];if(!(null==n?void 0:n.document))return Jt.reject({code:Qt.NotFound,message:"Document not found"});const o=this.getDocumentState(t);return o?this.useAnnotationMode?this.applyAllRedactionsAnnotationMode(t,n.document):this.commitAllPendingLegacy(t,n.document,o):Jt.reject({code:Qt.NotFound,message:"Document state not found"})}commitAllPendingLegacy(e,t,n){const o=new Map;for(const[e,t]of Object.entries(n.pending)){const n=Number(e),i=o.get(n)??[];for(const e of t)"text"===e.kind?i.push(...e.rects):i.push(e.rect);o.set(n,i)}const i=Array.from(o.entries()).filter(([e,t])=>t.length>0).map(([e])=>e),r=[];for(const[e,n]of o){const o=t.pages[e];o&&(n.length&&r.push(this.engine.redactTextInRects(t,o,n,{drawBlackBoxes:this.config.drawBlackBoxes})))}const a=new Ct;return Ct.all(r).wait(()=>{this.dispatch(og(e)),this.dispatchCoreAction(no(e,i)),this.events$.emit({type:"commit",documentId:e,success:!0}),a.resolve(!0)},t=>{this.events$.emit({type:"commit",documentId:e,success:!1,error:t.reason}),a.reject({code:Qt.Unknown,message:"Failed to commit redactions"})}),a}applyAllRedactionsAnnotationMode(e,t){const n=this.annotationCapability.forDocument(e).getState(),o=new Map;for(const e of Object.values(n.byUid))if(e.object.type===_t.REDACT){const t=o.get(e.object.pageIndex)??[];t.push(e.object.id),o.set(e.object.pageIndex,t)}const i=Array.from(o.keys());if(0===i.length)return Jt.resolve(!0);const r=[];for(const e of i){const n=t.pages[e];n&&r.push(this.engine.applyAllRedactions(t,n))}const a=new Ct;return Ct.all(r).wait(()=>{var t,n;const r=null==(t=this.annotationCapability)?void 0:t.forDocument(e),s=[];for(const[t,n]of o)for(const o of n)null==r||r.purgeAnnotation(t,o),this.dispatch(ng(e,t,o)),s.push(o);s.length>0&&(null==(n=this.historyCapability)||n.forDocument(e).purgeByMetadata(e=>{var t;return(null==(t=null==e?void 0:e.annotationIds)?void 0:t.some(e=>s.includes(e)))??!1},"annotations")),this.dispatchCoreAction(no(e,i)),this.events$.emit({type:"commit",documentId:e,success:!0}),a.resolve(!0)},t=>{this.events$.emit({type:"commit",documentId:e,success:!1,error:t.reason}),a.reject({code:Qt.Unknown,message:"Failed to apply redactions"})}),a}createRedactAnnotationsFromSelection(e,t,n){if(!this.annotationCapability)return[];const o=this.annotationCapability.forDocument(e),i=this.annotationCapability.getTool("redact"),r=null==i?void 0:i.defaults,a=[];for(const e of t){const i=zn();a.push(i);const s={...r,id:i,type:_t.REDACT,pageIndex:e.pageIndex,rect:e.rect,segmentRects:e.segmentRects,...n?{custom:{text:n}}:{},created:new Date};o.createAnnotation(e.pageIndex,s),e===t[t.length-1]&&o.selectAnnotation(e.pageIndex,i)}if(n)for(let o=0;o({id:zn(),kind:"text",page:e.pageIndex,rect:e.rect,rects:e.segmentRects,source:"legacy",markColor:"#FF0000",redactionColor:o,text:n}));this.dispatch(tg(e,i)),i.length&&this.selectPending(i[i.length-1].page,i[i.length-1].id,e)}createRedactionsFromSelection(e,t,n){this.useAnnotationMode?this.createRedactAnnotationsFromSelection(e,t,n):this.createLegacyRedactionsFromSelection(e,t,n)}createRedactAnnotationFromArea(e,t,n){if(!this.annotationCapability)return;const o=this.annotationCapability.forDocument(e),i=this.annotationCapability.getTool("redact"),r=null==i?void 0:i.defaults,a=zn(),s={...r,id:a,type:_t.REDACT,pageIndex:t,rect:n,segmentRects:[],created:new Date};o.createAnnotation(t,s),o.selectAnnotation(t,a)}redactionItemToAnnotation(e){var t;const n=null==(t=this.annotationCapability)?void 0:t.getTool("redact");return{...(null==n?void 0:n.defaults)??{},id:e.id,type:_t.REDACT,pageIndex:e.page,rect:e.rect,segmentRects:"text"===e.kind?e.rects:[],created:new Date}}annotationToRedactionItem(e){var t;const n=e.strokeColor??"#FF0000",o=e.color??"transparent";return e.segmentRects&&e.segmentRects.length>0?{id:e.id,kind:"text",page:e.pageIndex,rect:e.rect,rects:e.segmentRects,source:"annotation",markColor:n,redactionColor:o,...(null==(t=e.custom)?void 0:t.text)?{text:e.custom.text}:{}}:{id:e.id,kind:"area",page:e.pageIndex,rect:e.rect,source:"annotation",markColor:n,redactionColor:o}}emitPendingChange(e){const t=this.getDocumentState(e);t&&this.pending$.emit({documentId:e,pending:t.pending})}emitSelectedChange(e){const t=this.getDocumentState(e);t&&this.selected$.emit({documentId:e,selected:t.selected})}emitStateChange(e){const t=this.getDocumentState(e);t&&this.state$.emit({documentId:e,state:t})}onStoreUpdated(e,t){for(const e in t.documents){t.documents[e]&&(this.emitPendingChange(e),this.emitSelectedChange(e),this.emitStateChange(e))}}async destroy(){this.pending$.clear(),this.selected$.clear(),this.state$.clear(),this.events$.clear(),this.redactionSelection$.forEach(e=>e.clear()),this.redactionSelection$.clear(),this.redactionMarquee$.forEach(e=>e.clear()),this.redactionMarquee$.clear(),this.documentUnsubscribers.forEach(e=>{e.forEach(e=>e())}),this.documentUnsubscribers.clear(),await super.destroy()}};hg.id="redaction";let mg=hg;const gg="redaction",pg={manifest:{id:gg,name:"Redaction Plugin",version:"1.0.0",provides:["redaction"],requires:[],optional:["interaction-manager","selection","annotation"],defaultConfig:{drawBlackBoxes:!0}},create:(e,t)=>new mg(gg,e,t),reducer:(e=cg,t)=>{switch(t.type){case qm:{const{documentId:n,state:o}=t.payload;return{...e,documents:{...e.documents,[n]:o},activeDocumentId:e.activeDocumentId??n}}case Gm:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i,activeDocumentId:e.activeDocumentId===n?null:e.activeDocumentId}}case"REDACTION/SET_ACTIVE_DOCUMENT":return{...e,activeDocumentId:t.payload};case Zm:{const{documentId:n,items:o}=t.payload,i=e.documents[n];if(!i)return e;const r={...i.pending};for(const e of o){const t=r[e.page]??[];t.some(t=>t.id===e.id)||(r[e.page]=t.concat(e))}return{...e,documents:{...e.documents,[n]:{...i,pending:r,pendingCount:sg(r)}}}}case Ym:{const{documentId:n,page:o,id:i}=t.payload,r=e.documents[n];if(!r)return e;const a=(r.pending[o]??[]).filter(e=>e.id!==i),s={...r.pending,[o]:a},l=r.selected&&!(r.selected.page===o&&r.selected.id===i);return{...e,documents:{...e.documents,[n]:{...r,pending:s,pendingCount:sg(s),selected:l?r.selected:null}}}}case Xm:{const{documentId:n,page:o,id:i,patch:r}=t.payload,a=e.documents[n];if(!a)return e;const s=(a.pending[o]??[]).map(e=>e.id===i?{...e,...r}:e);return{...e,documents:{...e.documents,[n]:{...a,pending:{...a.pending,[o]:s}}}}}case Qm:{const n=t.payload,o=e.documents[n];return o?{...e,documents:{...e.documents,[n]:{...o,pending:{},pendingCount:0,selected:null}}}:e}case Jm:{const{documentId:n,page:o,id:i}=t.payload,r=e.documents[n];return r?{...e,documents:{...e.documents,[n]:{...r,selected:{page:o,id:i}}}}:e}case eg:{const n=t.payload,o=e.documents[n];return o?{...e,documents:{...e.documents,[n]:{...o,selected:null}}}:e}case Vm:{const{documentId:n,mode:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,isRedacting:!0,activeType:o}}}:e}case Km:{const n=t.payload,o=e.documents[n];return o?{...e,documents:{...e.documents,[n]:{...o,isRedacting:!1,activeType:null}}}:e}case"SET_ACTIVE_TYPE":{const{documentId:n,mode:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,activeType:o}}}:e}default:return e}},initialState:cg};function fg({annotation:e,isSelected:t,scale:n,onClick:o,style:i}){const[r,a]=Se(!1),{object:s}=e,l=s.segmentRects??[],c=s.rect,d=s.strokeColor??"#FF0000",u=s.color??"#000000",h=s.opacity??1,m=s.fontColor??s.overlayColor??"#FFFFFF",g=s.overlayText,p=s.overlayTextRepeat??!1,f=s.fontSize??12,v=s.fontFamily??Pt.Helvetica,y=s.textAlign??Dt.Center,b=()=>{if(!g)return null;if(!p)return g;return Array(10).fill(g).join(" ")};return He("div",{onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{position:"absolute",inset:0},children:l.map((e,t)=>He("div",{onPointerDown:o,onTouchStart:o,style:{position:"absolute",left:(c?e.origin.x-c.origin.x:e.origin.x)*n,top:(c?e.origin.y-c.origin.y:e.origin.y)*n,width:e.size.width*n,height:e.size.height*n,background:r?u:"transparent",border:r?"none":`2px solid ${d}`,opacity:r?h:1,boxSizing:"border-box",pointerEvents:"auto",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:y===Dt.Left?"flex-start":y===Dt.Right?"flex-end":"center",overflow:"hidden",...i},children:r&&g&&He("span",{style:{color:m,fontSize:Math.min(f*n,e.size.height*n*.8),...xn(v),textAlign:cn(y),whiteSpace:p?"normal":"nowrap",overflow:"hidden",textOverflow:"ellipsis",lineHeight:1},children:b()})},t))})}function vg({annotation:e,isSelected:t,scale:n,onClick:o,style:i}){const[r,a]=Se(!1),{object:s}=e,l=s.strokeColor??"#FF0000",c=s.color??"#000000",d=s.opacity??1,u=s.fontColor??s.overlayColor??"#FFFFFF",h=s.overlayText,m=s.overlayTextRepeat??!1,g=s.fontSize??12,p=s.fontFamily??Pt.Helvetica,f=s.textAlign??Dt.Center;return He("div",{onPointerDown:t?void 0:o,onTouchStart:t?void 0:o,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{position:"absolute",inset:0,background:r?c:"transparent",border:r?"none":`2px solid ${l}`,opacity:r?d:1,boxSizing:"border-box",pointerEvents:"auto",cursor:t?"move":"pointer",display:"flex",alignItems:"center",justifyContent:f===Dt.Left?"flex-start":f===Dt.Right?"flex-end":"center",overflow:"hidden",...i},children:r&&h&&He("span",{style:{color:u,fontSize:g*n,...xn(p),textAlign:cn(f),whiteSpace:m?"normal":"nowrap",overflow:"hidden",textOverflow:"ellipsis",padding:"4px"},children:(()=>{if(!h)return null;if(!m)return h;return Array(10).fill(h).join(" ")})()})})}const yg=[Wh({id:"redactHighlight",matches:e=>{var t;return e.type===_t.REDACT&&"segmentRects"in e&&((null==(t=e.segmentRects)?void 0:t.length)??0)>0},render:e=>He(fg,{...e})}),Wh({id:"redactArea",matches:e=>{var t;return!(e.type!==_t.REDACT||"segmentRects"in e&&(null==(t=e.segmentRects)?void 0:t.length))},render:e=>He(vg,{...e})})];const bg=()=>Eo(mg.id),wg=()=>_o(mg.id),xg=({documentId:e,pageIndex:t,scale:n,className:o,stroke:i,fill:r="transparent"})=>{const{plugin:a}=bg(),s=Oo(e),[l,c]=Se(null),d=n??(null==s?void 0:s.scale)??1,u=i??(null==a?void 0:a.getPreviewStrokeColor())??"red";return Ae(()=>{if(a&&e)return a.onRedactionMarqueeChange(e,e=>{c(e.pageIndex===t?e.rect:null)})},[a,e,t]),l?He("div",{style:{position:"absolute",pointerEvents:"none",left:l.origin.x*d,top:l.origin.y*d,width:l.size.width*d,height:l.size.height*d,border:`1px solid ${u}`,background:r,boxSizing:"border-box"},className:o}):null};function Cg({color:e="#FFFF00",opacity:t=1,border:n="1px solid red",rects:o,rect:i,scale:r,onClick:a,style:s,...l}){return He(H,{children:o.map((o,c)=>He("div",{onPointerDown:a,onTouchStart:a,style:{position:"absolute",border:n,left:(i?o.origin.x-i.origin.x:o.origin.x)*r,top:(i?o.origin.y-i.origin.y:o.origin.y)*r,width:o.size.width*r,height:o.size.height*r,background:e,opacity:t,pointerEvents:a?"auto":"none",cursor:a?"pointer":"default",zIndex:a?1:void 0,...s},...l},c))})}function Ig({documentId:e,pageIndex:t,scale:n}){const{plugin:o}=bg(),[i,r]=Se([]),[a,s]=Se(null),l=(null==o?void 0:o.getPreviewStrokeColor())??"red";return Ae(()=>{if(o)return o.onRedactionSelectionChange(e,e=>{const n=e.find(e=>e.pageIndex===t);r((null==n?void 0:n.segmentRects)??[]),s((null==n?void 0:n.rect)??null)})},[o,e,t]),a?He("div",{style:{mixBlendMode:"normal",pointerEvents:"none",position:"absolute",inset:0},children:He(Cg,{color:"transparent",opacity:1,rects:i,scale:n,border:`1px solid ${l}`})}):null}function kg({documentId:e,pageIndex:t,scale:n,bboxStroke:o="rgba(0,0,0,0.8)",rotation:i=Be.Degree0,selectionMenu:r}){const{provides:a}=wg(),[s,l]=Se([]),[c,d]=Se(null);Ae(()=>{if(!a)return;const n=a.forDocument(e),o=n.getState();l((o.pending[t]??[]).filter(e=>"legacy"===e.source)),d(o.selected&&o.selected.page===t?o.selected.id:null);const i=n.onPendingChange(e=>{l((e[t]??[]).filter(e=>"legacy"===e.source))}),r=n.onSelectedChange(e=>{d(e&&e.page===t?e.id:null)});return()=>{null==i||i(),null==r||r()}},[a,e,t]);const u=ze((n,o)=>{n.stopPropagation(),a&&a.forDocument(e).selectPending(t,o)},[a,e,t]);return s.length?He("div",{style:{position:"absolute",inset:0,pointerEvents:"none"},children:s.map(e=>{if("area"===e.kind){const a=e.rect;return He(H,{children:[He("div",{style:{position:"absolute",left:a.origin.x*n,top:a.origin.y*n,width:a.size.width*n,height:a.size.height*n,background:"transparent",outline:c===e.id?`1px solid ${o}`:"none",outlineOffset:"2px",border:`1px solid ${e.markColor}`,pointerEvents:"auto",cursor:"pointer"},onPointerDown:t=>u(t,e.id),onTouchStart:t=>u(t,e.id)}),r&&He(Al,{rect:{origin:{x:a.origin.x*n,y:a.origin.y*n},size:{width:a.size.width*n,height:a.size.height*n}},rotation:i,children:n=>r({...n,context:{type:"redaction",item:e,pageIndex:t},selected:c===e.id,placement:{suggestTop:!1}})})]},e.id)}const a=e.rect;return He(H,{children:[He("div",{style:{position:"absolute",left:a.origin.x*n,top:a.origin.y*n,width:a.size.width*n,height:a.size.height*n,background:"transparent",outline:c===e.id?`1px solid ${o}`:"none",outlineOffset:"2px",pointerEvents:"auto",cursor:c===e.id?"pointer":"default"},children:He(Cg,{rect:a,rects:e.rects,color:"transparent",border:`1px solid ${e.markColor}`,scale:n,onClick:t=>u(t,e.id)})}),r&&He(Al,{rect:{origin:{x:a.origin.x*n,y:a.origin.y*n},size:{width:a.size.width*n,height:a.size.height*n}},rotation:i,children:n=>r({...n,context:{type:"redaction",item:e,pageIndex:t},selected:c===e.id,placement:{suggestTop:!1}})})]},e.id)})}):null}const Sg=({documentId:e,pageIndex:t,scale:n,rotation:o,selectionMenu:i})=>{var r,a;const s=Oo(e),l=null==(a=null==(r=null==s?void 0:s.document)?void 0:r.pages)?void 0:a[t],c=Re(()=>void 0!==n?n:(null==s?void 0:s.scale)??1,[n,null==s?void 0:s.scale]);return He(H,{children:[He(kg,{documentId:e,pageIndex:t,scale:c,rotation:Re(()=>{if(void 0!==o)return o;return(((null==l?void 0:l.rotation)??0)+((null==s?void 0:s.rotation)??0))%4},[o,null==l?void 0:l.rotation,null==s?void 0:s.rotation]),selectionMenu:i}),He(xg,{documentId:e,pageIndex:t,scale:c}),He(Ig,{documentId:e,pageIndex:t,scale:c})]})},Mg=Do(pg).addUtility(function(){return function(e){const t=Te(yh),n=De(e);Ae(()=>{if(t)return t(n.current)},[t])}(yg),null}).build(),Ag=class extends fo{constructor(e,t){super(e,t)}async initialize(e){}buildCapability(){return{getAttachments:()=>this.getAttachments(),downloadAttachment:e=>this.downloadAttachment(e),forDocument:e=>this.createAttachmentScope(e)}}createAttachmentScope(e){return{getAttachments:()=>this.getAttachments(e),downloadAttachment:t=>this.downloadAttachment(t,e)}}downloadAttachment(e,t){const n=t??this.getActiveDocumentId(),o=this.coreState.core.documents[n];return(null==o?void 0:o.document)?this.engine.readAttachmentContent(o.document,e):Jt.reject({code:Qt.NotFound,message:`Document ${n} not found`})}getAttachments(e){const t=e??this.getActiveDocumentId(),n=this.coreState.core.documents[t];return(null==n?void 0:n.document)?this.engine.getAttachments(n.document):Jt.reject({code:Qt.NotFound,message:`Document ${t} not found`})}};Ag.id="attachment";let Pg=Ag;const Dg="attachment",Rg={manifest:{id:Dg,name:"Attachment Plugin",version:"1.0.0",provides:["attachment"],requires:[],optional:[],defaultConfig:{}},create:e=>new Pg(Dg,e),reducer:()=>{},initialState:{}},zg=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Tg="-",Eg=[],_g=e=>{const t=Lg(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:o}=e;return{getClassGroupId:e=>{if(e.startsWith("[")&&e.endsWith("]"))return Og(e);const n=e.split(Tg),o=""===n[0]&&n.length>1?1:0;return Ng(n,o,t)},getConflictingClassGroupIds:(e,t)=>{if(t){const t=o[e],i=n[e];return t?i?((e,t)=>{const n=new Array(e.length+t.length);for(let t=0;t{if(0===e.length-t)return n.classGroupId;const o=e[t],i=n.nextPart.get(o);if(i){const n=Ng(e,t+1,i);if(n)return n}const r=n.validators;if(null===r)return;const a=0===t?e.join(Tg):e.slice(t).join(Tg),s=r.length;for(let e=0;e-1===e.slice(1,-1).indexOf(":")?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),o=t.slice(0,n);return o?"arbitrary.."+o:void 0})(),Lg=e=>{const{theme:t,classGroups:n}=e;return $g(n,t)},$g=(e,t)=>{const n=zg();for(const o in e){const i=e[o];jg(i,n,o,t)}return n},jg=(e,t,n,o)=>{const i=e.length;for(let r=0;r{"string"!=typeof e?"function"!=typeof e?Bg(e,t,n,o):Hg(e,t,n,o):Ug(e,t,n)},Ug=(e,t,n)=>{(""===e?t:Wg(t,e)).classGroupId=n},Hg=(e,t,n,o)=>{qg(e)?jg(e(o),t,n,o):(null===t.validators&&(t.validators=[]),t.validators.push(((e,t)=>({classGroupId:e,validator:t}))(n,e)))},Bg=(e,t,n,o)=>{const i=Object.entries(e),r=i.length;for(let e=0;e{let n=e;const o=t.split(Tg),i=o.length;for(let e=0;e"isThemeGetter"in e&&!0===e.isThemeGetter,Gg=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),o=Object.create(null);const i=(i,r)=>{n[i]=r,t++,t>e&&(t=0,o=n,n=Object.create(null))};return{get(e){let t=n[e];return void 0!==t?t:void 0!==(t=o[e])?(i(e,t),t):void 0},set(e,t){e in n?n[e]=t:i(e,t)}}},Vg=[],Kg=(e,t,n,o,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:o,isExternal:i}),Zg=e=>{const{prefix:t,experimentalParseClassName:n}=e;let o=e=>{const t=[];let n,o=0,i=0,r=0;const a=e.length;for(let s=0;sr?n-r:void 0)};if(t){const e=t+":",n=o;o=t=>t.startsWith(e)?n(t.slice(e.length)):Kg(Vg,!1,t,void 0,!0)}if(n){const e=o;o=t=>n({className:t,parseClassName:e})}return o},Yg=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((e,n)=>{t.set(e,1e6+n)}),e=>{const n=[];let o=[];for(let i=0;i0&&(o.sort(),n.push(...o),o=[]),n.push(r)):o.push(r)}return o.length>0&&(o.sort(),n.push(...o)),n}},Xg=/\s+/,Qg=e=>{if("string"==typeof e)return e;let t,n="";for(let o=0;o{let n,o,i,r;const a=e=>{const t=o(e);if(t)return t;const r=((e,t)=>{const{parseClassName:n,getClassGroupId:o,getConflictingClassGroupIds:i,sortModifiers:r}=t,a=[],s=e.trim().split(Xg);let l="";for(let e=s.length-1;e>=0;e-=1){const t=s[e],{isExternal:c,modifiers:d,hasImportantModifier:u,baseClassName:h,maybePostfixModifierPosition:m}=n(t);if(c){l=t+(l.length>0?" "+l:l);continue}let g=!!m,p=o(g?h.substring(0,m):h);if(!p){if(!g){l=t+(l.length>0?" "+l:l);continue}if(p=o(h),!p){l=t+(l.length>0?" "+l:l);continue}g=!1}const f=0===d.length?"":1===d.length?d[0]:r(d).join(":"),v=u?f+"!":f,y=v+p;if(a.indexOf(y)>-1)continue;a.push(y);const b=i(p,g);for(let e=0;e0?" "+l:l)}return l})(e,n);return i(e,r),r};return r=s=>{const l=t.reduce((e,t)=>t(e),e());return n=(e=>({cache:Gg(e.cacheSize),parseClassName:Zg(e),sortModifiers:Yg(e),..._g(e)}))(l),o=n.cache.get,i=n.cache.set,r=a,a(s)},(...e)=>r(((...e)=>{let t,n,o=0,i="";for(;o{const t=t=>t[e]||ep;return t.isThemeGetter=!0,t},np=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,op=/^\((?:(\w[\w-]*):)?(.+)\)$/i,ip=/^\d+\/\d+$/,rp=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,ap=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,sp=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,lp=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,cp=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,dp=e=>ip.test(e),up=e=>!!e&&!Number.isNaN(Number(e)),hp=e=>!!e&&Number.isInteger(Number(e)),mp=e=>e.endsWith("%")&&up(e.slice(0,-1)),gp=e=>rp.test(e),pp=()=>!0,fp=e=>ap.test(e)&&!sp.test(e),vp=()=>!1,yp=e=>lp.test(e),bp=e=>cp.test(e),wp=e=>!Cp(e)&&!Pp(e),xp=e=>Np(e,jp,vp),Cp=e=>np.test(e),Ip=e=>Np(e,Fp,fp),kp=e=>Np(e,Up,up),Sp=e=>Np(e,Lp,vp),Mp=e=>Np(e,$p,bp),Ap=e=>Np(e,Bp,yp),Pp=e=>op.test(e),Dp=e=>Op(e,Fp),Rp=e=>Op(e,Hp),zp=e=>Op(e,Lp),Tp=e=>Op(e,jp),Ep=e=>Op(e,$p),_p=e=>Op(e,Bp,!0),Np=(e,t,n)=>{const o=np.exec(e);return!!o&&(o[1]?t(o[1]):n(o[2]))},Op=(e,t,n=!1)=>{const o=op.exec(e);return!!o&&(o[1]?t(o[1]):n)},Lp=e=>"position"===e||"percentage"===e,$p=e=>"image"===e||"url"===e,jp=e=>"length"===e||"size"===e||"bg-size"===e,Fp=e=>"length"===e,Up=e=>"number"===e,Hp=e=>"family-name"===e,Bp=e=>"shadow"===e,Wp=Jg(()=>{const e=tp("color"),t=tp("font"),n=tp("text"),o=tp("font-weight"),i=tp("tracking"),r=tp("leading"),a=tp("breakpoint"),s=tp("container"),l=tp("spacing"),c=tp("radius"),d=tp("shadow"),u=tp("inset-shadow"),h=tp("text-shadow"),m=tp("drop-shadow"),g=tp("blur"),p=tp("perspective"),f=tp("aspect"),v=tp("ease"),y=tp("animate"),b=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom",Pp,Cp],w=()=>[Pp,Cp,l],x=()=>[dp,"full","auto",...w()],C=()=>[hp,"none","subgrid",Pp,Cp],I=()=>["auto",{span:["full",hp,Pp,Cp]},hp,Pp,Cp],k=()=>[hp,"auto",Pp,Cp],S=()=>["auto","min","max","fr",Pp,Cp],M=()=>["auto",...w()],A=()=>[dp,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...w()],P=()=>[e,Pp,Cp],D=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom",zp,Sp,{position:[Pp,Cp]}],R=()=>["auto","cover","contain",Tp,xp,{size:[Pp,Cp]}],z=()=>[mp,Dp,Ip],T=()=>["","none","full",c,Pp,Cp],E=()=>["",up,Dp,Ip],_=()=>[up,mp,zp,Sp],N=()=>["","none",g,Pp,Cp],O=()=>["none",up,Pp,Cp],L=()=>["none",up,Pp,Cp],$=()=>[up,Pp,Cp],j=()=>[dp,"full",...w()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[gp],breakpoint:[gp],color:[pp],container:[gp],"drop-shadow":[gp],ease:["in","out","in-out"],font:[wp],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[gp],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[gp],shadow:[gp],spacing:["px",up],text:[gp],"text-shadow":[gp],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",dp,Cp,Pp,f]}],container:["container"],columns:[{columns:[up,Cp,Pp,s]}],"break-after":[{"break-after":["auto","avoid","all","avoid-page","page","left","right","column"]}],"break-before":[{"break-before":["auto","avoid","all","avoid-page","page","left","right","column"]}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:b()}],overflow:[{overflow:["auto","hidden","clip","visible","scroll"]}],"overflow-x":[{"overflow-x":["auto","hidden","clip","visible","scroll"]}],"overflow-y":[{"overflow-y":["auto","hidden","clip","visible","scroll"]}],overscroll:[{overscroll:["auto","contain","none"]}],"overscroll-x":[{"overscroll-x":["auto","contain","none"]}],"overscroll-y":[{"overscroll-y":["auto","contain","none"]}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:x()}],"inset-x":[{"inset-x":x()}],"inset-y":[{"inset-y":x()}],start:[{start:x()}],end:[{end:x()}],top:[{top:x()}],right:[{right:x()}],bottom:[{bottom:x()}],left:[{left:x()}],visibility:["visible","invisible","collapse"],z:[{z:[hp,"auto",Pp,Cp]}],basis:[{basis:[dp,"full","auto",s,...w()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[up,dp,"auto","initial","none",Cp]}],grow:[{grow:["",up,Pp,Cp]}],shrink:[{shrink:["",up,Pp,Cp]}],order:[{order:[hp,"first","last","none",Pp,Cp]}],"grid-cols":[{"grid-cols":C()}],"col-start-end":[{col:I()}],"col-start":[{"col-start":k()}],"col-end":[{"col-end":k()}],"grid-rows":[{"grid-rows":C()}],"row-start-end":[{row:I()}],"row-start":[{"row-start":k()}],"row-end":[{"row-end":k()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":S()}],"auto-rows":[{"auto-rows":S()}],gap:[{gap:w()}],"gap-x":[{"gap-x":w()}],"gap-y":[{"gap-y":w()}],"justify-content":[{justify:["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe","normal"]}],"justify-items":[{"justify-items":["start","end","center","stretch","center-safe","end-safe","normal"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch","center-safe","end-safe"]}],"align-content":[{content:["normal","start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"]}],"align-items":[{items:["start","end","center","stretch","center-safe","end-safe",{baseline:["","last"]}]}],"align-self":[{self:["auto","start","end","center","stretch","center-safe","end-safe",{baseline:["","last"]}]}],"place-content":[{"place-content":["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"]}],"place-items":[{"place-items":["start","end","center","stretch","center-safe","end-safe","baseline"]}],"place-self":[{"place-self":["auto","start","end","center","stretch","center-safe","end-safe"]}],p:[{p:w()}],px:[{px:w()}],py:[{py:w()}],ps:[{ps:w()}],pe:[{pe:w()}],pt:[{pt:w()}],pr:[{pr:w()}],pb:[{pb:w()}],pl:[{pl:w()}],m:[{m:M()}],mx:[{mx:M()}],my:[{my:M()}],ms:[{ms:M()}],me:[{me:M()}],mt:[{mt:M()}],mr:[{mr:M()}],mb:[{mb:M()}],ml:[{ml:M()}],"space-x":[{"space-x":w()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":w()}],"space-y-reverse":["space-y-reverse"],size:[{size:A()}],w:[{w:[s,"screen",...A()]}],"min-w":[{"min-w":[s,"screen","none",...A()]}],"max-w":[{"max-w":[s,"screen","none","prose",{screen:[a]},...A()]}],h:[{h:["screen","lh",...A()]}],"min-h":[{"min-h":["screen","lh","none",...A()]}],"max-h":[{"max-h":["screen","lh",...A()]}],"font-size":[{text:["base",n,Dp,Ip]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[o,Pp,kp]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",mp,Cp]}],"font-family":[{font:[Rp,Cp,t]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[i,Pp,Cp]}],"line-clamp":[{"line-clamp":[up,"none",Pp,kp]}],leading:[{leading:[r,...w()]}],"list-image":[{"list-image":["none",Pp,Cp]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Pp,Cp]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:P()}],"text-color":[{text:P()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:["solid","dashed","dotted","double","wavy"]}],"text-decoration-thickness":[{decoration:[up,"from-font","auto",Pp,Ip]}],"text-decoration-color":[{decoration:P()}],"underline-offset":[{"underline-offset":[up,"auto",Pp,Cp]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:w()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Pp,Cp]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Pp,Cp]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:D()}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","space","round"]}]}],"bg-size":[{bg:R()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},hp,Pp,Cp],radial:["",Pp,Cp],conic:[hp,Pp,Cp]},Ep,Mp]}],"bg-color":[{bg:P()}],"gradient-from-pos":[{from:z()}],"gradient-via-pos":[{via:z()}],"gradient-to-pos":[{to:z()}],"gradient-from":[{from:P()}],"gradient-via":[{via:P()}],"gradient-to":[{to:P()}],rounded:[{rounded:T()}],"rounded-s":[{"rounded-s":T()}],"rounded-e":[{"rounded-e":T()}],"rounded-t":[{"rounded-t":T()}],"rounded-r":[{"rounded-r":T()}],"rounded-b":[{"rounded-b":T()}],"rounded-l":[{"rounded-l":T()}],"rounded-ss":[{"rounded-ss":T()}],"rounded-se":[{"rounded-se":T()}],"rounded-ee":[{"rounded-ee":T()}],"rounded-es":[{"rounded-es":T()}],"rounded-tl":[{"rounded-tl":T()}],"rounded-tr":[{"rounded-tr":T()}],"rounded-br":[{"rounded-br":T()}],"rounded-bl":[{"rounded-bl":T()}],"border-w":[{border:E()}],"border-w-x":[{"border-x":E()}],"border-w-y":[{"border-y":E()}],"border-w-s":[{"border-s":E()}],"border-w-e":[{"border-e":E()}],"border-w-t":[{"border-t":E()}],"border-w-r":[{"border-r":E()}],"border-w-b":[{"border-b":E()}],"border-w-l":[{"border-l":E()}],"divide-x":[{"divide-x":E()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":E()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:["solid","dashed","dotted","double","hidden","none"]}],"divide-style":[{divide:["solid","dashed","dotted","double","hidden","none"]}],"border-color":[{border:P()}],"border-color-x":[{"border-x":P()}],"border-color-y":[{"border-y":P()}],"border-color-s":[{"border-s":P()}],"border-color-e":[{"border-e":P()}],"border-color-t":[{"border-t":P()}],"border-color-r":[{"border-r":P()}],"border-color-b":[{"border-b":P()}],"border-color-l":[{"border-l":P()}],"divide-color":[{divide:P()}],"outline-style":[{outline:["solid","dashed","dotted","double","none","hidden"]}],"outline-offset":[{"outline-offset":[up,Pp,Cp]}],"outline-w":[{outline:["",up,Dp,Ip]}],"outline-color":[{outline:P()}],shadow:[{shadow:["","none",d,_p,Ap]}],"shadow-color":[{shadow:P()}],"inset-shadow":[{"inset-shadow":["none",u,_p,Ap]}],"inset-shadow-color":[{"inset-shadow":P()}],"ring-w":[{ring:E()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:P()}],"ring-offset-w":[{"ring-offset":[up,Ip]}],"ring-offset-color":[{"ring-offset":P()}],"inset-ring-w":[{"inset-ring":E()}],"inset-ring-color":[{"inset-ring":P()}],"text-shadow":[{"text-shadow":["none",h,_p,Ap]}],"text-shadow-color":[{"text-shadow":P()}],opacity:[{opacity:[up,Pp,Cp]}],"mix-blend":[{"mix-blend":["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"]}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[up]}],"mask-image-linear-from-pos":[{"mask-linear-from":_()}],"mask-image-linear-to-pos":[{"mask-linear-to":_()}],"mask-image-linear-from-color":[{"mask-linear-from":P()}],"mask-image-linear-to-color":[{"mask-linear-to":P()}],"mask-image-t-from-pos":[{"mask-t-from":_()}],"mask-image-t-to-pos":[{"mask-t-to":_()}],"mask-image-t-from-color":[{"mask-t-from":P()}],"mask-image-t-to-color":[{"mask-t-to":P()}],"mask-image-r-from-pos":[{"mask-r-from":_()}],"mask-image-r-to-pos":[{"mask-r-to":_()}],"mask-image-r-from-color":[{"mask-r-from":P()}],"mask-image-r-to-color":[{"mask-r-to":P()}],"mask-image-b-from-pos":[{"mask-b-from":_()}],"mask-image-b-to-pos":[{"mask-b-to":_()}],"mask-image-b-from-color":[{"mask-b-from":P()}],"mask-image-b-to-color":[{"mask-b-to":P()}],"mask-image-l-from-pos":[{"mask-l-from":_()}],"mask-image-l-to-pos":[{"mask-l-to":_()}],"mask-image-l-from-color":[{"mask-l-from":P()}],"mask-image-l-to-color":[{"mask-l-to":P()}],"mask-image-x-from-pos":[{"mask-x-from":_()}],"mask-image-x-to-pos":[{"mask-x-to":_()}],"mask-image-x-from-color":[{"mask-x-from":P()}],"mask-image-x-to-color":[{"mask-x-to":P()}],"mask-image-y-from-pos":[{"mask-y-from":_()}],"mask-image-y-to-pos":[{"mask-y-to":_()}],"mask-image-y-from-color":[{"mask-y-from":P()}],"mask-image-y-to-color":[{"mask-y-to":P()}],"mask-image-radial":[{"mask-radial":[Pp,Cp]}],"mask-image-radial-from-pos":[{"mask-radial-from":_()}],"mask-image-radial-to-pos":[{"mask-radial-to":_()}],"mask-image-radial-from-color":[{"mask-radial-from":P()}],"mask-image-radial-to-color":[{"mask-radial-to":P()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"]}],"mask-image-conic-pos":[{"mask-conic":[up]}],"mask-image-conic-from-pos":[{"mask-conic-from":_()}],"mask-image-conic-to-pos":[{"mask-conic-to":_()}],"mask-image-conic-from-color":[{"mask-conic-from":P()}],"mask-image-conic-to-color":[{"mask-conic-to":P()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:D()}],"mask-repeat":[{mask:["no-repeat",{repeat:["","x","y","space","round"]}]}],"mask-size":[{mask:R()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Pp,Cp]}],filter:[{filter:["","none",Pp,Cp]}],blur:[{blur:N()}],brightness:[{brightness:[up,Pp,Cp]}],contrast:[{contrast:[up,Pp,Cp]}],"drop-shadow":[{"drop-shadow":["","none",m,_p,Ap]}],"drop-shadow-color":[{"drop-shadow":P()}],grayscale:[{grayscale:["",up,Pp,Cp]}],"hue-rotate":[{"hue-rotate":[up,Pp,Cp]}],invert:[{invert:["",up,Pp,Cp]}],saturate:[{saturate:[up,Pp,Cp]}],sepia:[{sepia:["",up,Pp,Cp]}],"backdrop-filter":[{"backdrop-filter":["","none",Pp,Cp]}],"backdrop-blur":[{"backdrop-blur":N()}],"backdrop-brightness":[{"backdrop-brightness":[up,Pp,Cp]}],"backdrop-contrast":[{"backdrop-contrast":[up,Pp,Cp]}],"backdrop-grayscale":[{"backdrop-grayscale":["",up,Pp,Cp]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[up,Pp,Cp]}],"backdrop-invert":[{"backdrop-invert":["",up,Pp,Cp]}],"backdrop-opacity":[{"backdrop-opacity":[up,Pp,Cp]}],"backdrop-saturate":[{"backdrop-saturate":[up,Pp,Cp]}],"backdrop-sepia":[{"backdrop-sepia":["",up,Pp,Cp]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":w()}],"border-spacing-x":[{"border-spacing-x":w()}],"border-spacing-y":[{"border-spacing-y":w()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Pp,Cp]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[up,"initial",Pp,Cp]}],ease:[{ease:["linear","initial",v,Pp,Cp]}],delay:[{delay:[up,Pp,Cp]}],animate:[{animate:["none",y,Pp,Cp]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[p,Pp,Cp]}],"perspective-origin":[{"perspective-origin":b()}],rotate:[{rotate:O()}],"rotate-x":[{"rotate-x":O()}],"rotate-y":[{"rotate-y":O()}],"rotate-z":[{"rotate-z":O()}],scale:[{scale:L()}],"scale-x":[{"scale-x":L()}],"scale-y":[{"scale-y":L()}],"scale-z":[{"scale-z":L()}],"scale-3d":["scale-3d"],skew:[{skew:$()}],"skew-x":[{"skew-x":$()}],"skew-y":[{"skew-y":$()}],transform:[{transform:[Pp,Cp,"","none","gpu","cpu"]}],"transform-origin":[{origin:b()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:j()}],"translate-x":[{"translate-x":j()}],"translate-y":[{"translate-y":j()}],"translate-z":[{"translate-z":j()}],"translate-none":["translate-none"],accent:[{accent:P()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:P()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Pp,Cp]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":w()}],"scroll-mx":[{"scroll-mx":w()}],"scroll-my":[{"scroll-my":w()}],"scroll-ms":[{"scroll-ms":w()}],"scroll-me":[{"scroll-me":w()}],"scroll-mt":[{"scroll-mt":w()}],"scroll-mr":[{"scroll-mr":w()}],"scroll-mb":[{"scroll-mb":w()}],"scroll-ml":[{"scroll-ml":w()}],"scroll-p":[{"scroll-p":w()}],"scroll-px":[{"scroll-px":w()}],"scroll-py":[{"scroll-py":w()}],"scroll-ps":[{"scroll-ps":w()}],"scroll-pe":[{"scroll-pe":w()}],"scroll-pt":[{"scroll-pt":w()}],"scroll-pr":[{"scroll-pr":w()}],"scroll-pb":[{"scroll-pb":w()}],"scroll-pl":[{"scroll-pl":w()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Pp,Cp]}],fill:[{fill:["none",...P()]}],"stroke-w":[{stroke:[up,Dp,Ip,kp]}],stroke:[{stroke:["none",...P()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}});var qp=["children","onClick","active","disabled","className","anchorRef"];function Gp(e){var t=e.children,n=e.onClick,o=e.active,i=void 0!==o&&o,r=e.disabled,a=void 0!==r&&r,s=e.className,l=void 0===s?"":s,c=e.anchorRef,d=m(e,qp);return F("button",h({type:"button",ref:c,onClick:n,disabled:a,className:Wp("flex h-[32px] w-auto min-w-[32px] items-center justify-center rounded-md p-[5px] transition-colors hover:bg-interactive-hover hover:ring hover:ring-accent cursor-pointer rounded-none px-2 py-1 text-sm hover:bg-transparent border-b-2 hover:border-b-fg-muted hover:ring-transparent",i?"border-b-accent text-accent hover:border-b-accent":"border-b-transparent",a?"cursor-not-allowed opacity-50":"",l)},d),t)}var Vp=function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M9 6l6 6l-6 6"}))},Kp=function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M15 6l-6 6l6 6"}))},Zp=function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M6 9l6 6l6 -6"}))},Yp=function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M10 10m-7 0a7 7 0 1 0 14 0a7 7 0 1 0 -14 0"}),F("path",{d:"M21 21l-6 -6"}))},Xp=function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M18 6l-12 12"}),F("path",{d:"M6 6l12 12"}))},Qp=function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r,s=e.secondaryColor,l=void 0===s?"currentColor":s;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M7 4h10"}),F("path",{d:"M12 4v8"}),F("defs",null,F("clipPath",{id:"stripeClip"},F("rect",{x:"2",y:"12",width:"20",height:"10",rx:"2"}))),F("rect",{x:"2",y:"12",width:"20",height:"10",rx:"2",fill:"none",stroke:a}),F("g",{"clip-path":"url(#stripeClip)",stroke:l},F("path",{d:"M-7 24l12 -12"}),F("path",{d:"M-3 24l12 -12"}),F("path",{d:"M1 24l12 -12"}),F("path",{d:"M5 24l12 -12"}),F("path",{d:"M9 24l12 -12"}),F("path",{d:"M13 24l12 -12"}),F("path",{d:"M17 24l12 -12"}),F("path",{d:"M21 24l12 -12"}),F("path",{d:"M25 24l12 -12"})))},Jp=function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r,s=e.secondaryColor,l=void 0===s?"currentColor":s;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:a,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M6 20h-1a2 2 0 0 1 -2 -2v-1"}),F("path",{d:"M3 13v-3"}),F("path",{d:"M3 6v-1a2 2 0 0 1 2 -2h1"}),F("path",{d:"M10 3h3"}),F("path",{d:"M17 3h1a2 2 0 0 1 2 2v1"}),F("defs",null,F("clipPath",{id:"redactClip"},F("rect",{x:"10",y:"10",width:"12",height:"12",rx:"2"}))),F("rect",{x:"10",y:"10",width:"12",height:"12",rx:"2",fill:"none"}),F("g",{"clip-path":"url(#redactClip)",stroke:l},F("path",{d:"M-2 24l14 -14"}),F("path",{d:"M2 24l14 -14"}),F("path",{d:"M6 24l14 -14"}),F("path",{d:"M10 24l15 -15"}),F("path",{d:"M14 24l15 -15"}),F("path",{d:"M18 24l15 -15"})))};var ef={download:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2 -2v-2"}),F("path",{d:"M7 11l5 5l5 -5"}),F("path",{d:"M12 4l0 12"}))},menu:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 8l16 0"}),F("path",{d:"M4 16l16 0"}))},fullscreen:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 8v-2a2 2 0 0 1 2 -2h2"}),F("path",{d:"M4 16v2a2 2 0 0 0 2 2h2"}),F("path",{d:"M16 4h2a2 2 0 0 1 2 2v2"}),F("path",{d:"M16 20h2a2 2 0 0 0 2 -2v-2"}))},fullscreenExit:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 8v-2c0 -.551 .223 -1.05 .584 -1.412"}),F("path",{d:"M4 16v2a2 2 0 0 0 2 2h2"}),F("path",{d:"M16 4h2a2 2 0 0 1 2 2v2"}),F("path",{d:"M16 20h2c.545 0 1.04 -.218 1.4 -.572"}),F("path",{d:"M3 3l18 18"}))},save:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M6 4h10l4 4v10a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2"}),F("path",{d:"M12 14m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),F("path",{d:"M14 4l0 4l-6 0l0 -4"}))},print:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M17 17h2a2 2 0 0 0 2 -2v-4a2 2 0 0 0 -2 -2h-14a2 2 0 0 0 -2 2v4a2 2 0 0 0 2 2h2"}),F("path",{d:"M17 9v-4a2 2 0 0 0 -2 -2h-6a2 2 0 0 0 -2 2v4"}),F("path",{d:"M7 13m0 2a2 2 0 0 1 2 -2h6a2 2 0 0 1 2 2v4a2 2 0 0 1 -2 2h-6a2 2 0 0 1 -2 -2z"}))},settings:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M10.325 4.317c.426 -1.756 2.924 -1.756 3.35 0a1.724 1.724 0 0 0 2.573 1.066c1.543 -.94 3.31 .826 2.37 2.37a1.724 1.724 0 0 0 1.065 2.572c1.756 .426 1.756 2.924 0 3.35a1.724 1.724 0 0 0 -1.066 2.573c.94 1.543 -.826 3.31 -2.37 2.37a1.724 1.724 0 0 0 -2.572 1.065c-.426 1.756 -2.924 1.756 -3.35 0a1.724 1.724 0 0 0 -2.573 -1.066c-1.543 .94 -3.31 -.826 -2.37 -2.37a1.724 1.724 0 0 0 -1.065 -2.572c-1.756 -.426 -1.756 -2.924 0 -3.35a1.724 1.724 0 0 0 1.066 -2.573c-.94 -1.543 .826 -3.31 2.37 -2.37c1 .608 2.296 .07 2.572 -1.065z"}),F("path",{d:"M9 12a3 3 0 1 0 6 0a3 3 0 0 0 -6 0"}))},viewSettings:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M12 14m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),F("path",{d:"M12 10.5v1.5"}),F("path",{d:"M12 16v1.5"}),F("path",{d:"M15.031 12.25l-1.299 .75"}),F("path",{d:"M10.268 15l-1.3 .75"}),F("path",{d:"M15 15.803l-1.285 -.773"}),F("path",{d:"M10.285 12.97l-1.285 -.773"}),F("path",{d:"M14 3v4a1 1 0 0 0 1 1h4"}),F("path",{d:"M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z"}))},rotateClockwise:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4.05 11a8 8 0 1 1 .5 4m-.5 5v-5h5"}))},rotateCounterClockwise:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M19.95 11a8 8 0 1 0 -.5 4m.5 5v-5h-5"}))},singlePage:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M5 3m0 1a1 1 0 0 1 1 -1h12a1 1 0 0 1 1 1v16a1 1 0 0 1 -1 1h-12a1 1 0 0 1 -1 -1z"}))},doublePage:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M3 3m0 1a1 1 0 0 1 1 -1h16a1 1 0 0 1 1 1v16a1 1 0 0 1 -1 1h-16a1 1 0 0 1 -1 -1zm9 -1v18"}))},zoomIn:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0"}),F("path",{d:"M9 12h6"}),F("path",{d:"M12 9v6"}))},zoomOut:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"}),F("path",{d:"M9 12l6 0"}))},fitToWidth:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 12v-6a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v6"}),F("path",{d:"M10 18h-7"}),F("path",{d:"M21 18h-7"}),F("path",{d:"M6 15l-3 3l3 3"}),F("path",{d:"M18 15l3 3l-3 3"}))},fitToPage:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M12 20h-6a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2h6"}),F("path",{d:"M18 14v7"}),F("path",{d:"M18 3v7"}),F("path",{d:"M15 18l3 3l3 -3"}),F("path",{d:"M15 6l3 -3l3 3"}))},chevronRight:Vp,chevronLeft:Kp,chevronDown:Zp,search:Yp,comment:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M12 11v.01"}),F("path",{d:"M8 11v.01"}),F("path",{d:"M16 11v.01"}),F("path",{d:"M18 4a3 3 0 0 1 3 3v8a3 3 0 0 1 -3 3h-5l-5 3v-3h-2a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3z"}))},sidebar:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 18v-12a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z"}),F("path",{d:"M10 18v-12a2 2 0 0 1 2 -2h6a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-6a2 2 0 0 1 -2 -2z"}))},dots:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M5 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"}),F("path",{d:"M12 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"}),F("path",{d:"M19 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"}))},vertical:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M8 7l4 -4l4 4"}),F("path",{d:"M8 17l4 4l4 -4"}),F("path",{d:"M12 3l0 18"}))},horizontal:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M7 8l-4 4l4 4"}),F("path",{d:"M17 8l4 4l-4 4"}),F("path",{d:"M3 12l18 0"}))},book:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M3 19a9 9 0 0 1 9 0a9 9 0 0 1 9 0"}),F("path",{d:"M3 6a9 9 0 0 1 9 0a9 9 0 0 1 9 0"}),F("path",{d:"M3 6l0 13"}),F("path",{d:"M12 6l0 13"}),F("path",{d:"M21 6l0 13"}))},book2:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M19 4v16h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2h12z"}),F("path",{d:"M19 16h-12a2 2 0 0 0 -2 2"}),F("path",{d:"M9 8h6"}))},squares:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M8 10a2 2 0 0 1 2 -2h9a2 2 0 0 1 2 2v9a2 2 0 0 1 -2 2h-9a2 2 0 0 1 -2 -2z"}),F("path",{d:"M16 8v-3a2 2 0 0 0 -2 -2h-9a2 2 0 0 0 -2 2v9a2 2 0 0 0 2 2h3"}))},listTree:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M9 6h11"}),F("path",{d:"M12 12h8"}),F("path",{d:"M15 18h5"}),F("path",{d:"M5 6v.01"}),F("path",{d:"M8 12v.01"}),F("path",{d:"M11 18v.01"}))},paperclip:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M15 7l-6.5 6.5a1.5 1.5 0 0 0 3 3l6.5 -6.5a3 3 0 0 0 -6 -6l-6.5 6.5a4.5 4.5 0 0 0 9 9l6.5 -6.5"}))},copy:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M7 7m0 2.667a2.667 2.667 0 0 1 2.667 -2.667h8.666a2.667 2.667 0 0 1 2.667 2.667v8.666a2.667 2.667 0 0 1 -2.667 2.667h-8.666a2.667 2.667 0 0 1 -2.667 -2.667z"}),F("path",{d:"M4.012 16.737a2.005 2.005 0 0 1 -1.012 -1.737v-10c0 -1.1 .9 -2 2 -2h10c.75 0 1.158 .385 1.5 1"}))},underline:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none","stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 20h16",stroke:a}),F("path",{d:"M8 16v-8a4 4 0 1 1 8 0v8",stroke:"currentColor"}),F("path",{d:"M8 10h8",stroke:"currentColor"}))},squiggly:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none","stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M8 16v-8a4 4 0 1 1 8 0v8",stroke:"currentColor"}),F("path",{d:"M8 10h8",stroke:"currentColor"}),F("path",{d:"M4 20c1.5 -1.5 3.5 -1.5 5 0s3.5 1.5 5 0 3.5 -1.5 5 0",stroke:a}))},strikethrough:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none","stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M8 16v-8a4 4 0 1 1 8 0v8",stroke:"currentColor"}),F("path",{d:"M4 10h16",stroke:a}))},highlight:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none","stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("rect",{x:"2",y:"6",width:"20",height:"16",rx:"2",fill:a,stroke:"none"}),F("path",{d:"M8 16v-8a4 4 0 1 1 8 0v8",stroke:"currentColor"}),F("path",{d:"M8 10h8",stroke:"currentColor"}))},palette:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M12 21a9 9 0 0 1 0 -18c4.97 0 9 3.582 9 8c0 1.06 -.474 2.078 -1.318 2.828c-.844 .75 -1.989 1.172 -3.182 1.172h-2.5a2 2 0 0 0 -1 3.75a1.3 1.3 0 0 1 -1 2.25"}),F("path",{d:"M8.5 10.5m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"}),F("path",{d:"M12.5 7.5m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"}),F("path",{d:"M16.5 10.5m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"}))},x:Xp,fileImport:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M14 3v4a1 1 0 0 0 1 1h4"}),F("path",{d:"M5 13v-8a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2h-5.5m-9.5 -2h7m-3 -3l3 3l-3 3"}))},hand:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M8 13v-7.5a1.5 1.5 0 0 1 3 0v6.5"}),F("path",{d:"M11 5.5v-2a1.5 1.5 0 1 1 3 0v8.5"}),F("path",{d:"M14 5.5a1.5 1.5 0 0 1 3 0v6.5"}),F("path",{d:"M17 7.5a1.5 1.5 0 0 1 3 0v8.5a6 6 0 0 1 -6 6h-2h.208a6 6 0 0 1 -5.012 -2.7a69.74 69.74 0 0 1 -.196 -.3c-.312 -.479 -1.407 -2.388 -3.286 -5.728a1.5 1.5 0 0 1 .536 -2.022a1.867 1.867 0 0 1 2.28 .28l1.47 1.47"}))},zoomInArea:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M15 13v4"}),F("path",{d:"M13 15h4"}),F("path",{d:"M15 15m-5 0a5 5 0 1 0 10 0a5 5 0 1 0 -10 0"}),F("path",{d:"M22 22l-3 -3"}),F("path",{d:"M6 18h-1a2 2 0 0 1 -2 -2v-1"}),F("path",{d:"M3 11v-1"}),F("path",{d:"M3 6v-1a2 2 0 0 1 2 -2h1"}),F("path",{d:"M10 3h1"}),F("path",{d:"M15 3h1a2 2 0 0 1 2 2v1"}))},screenshot:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M7 19a2 2 0 0 1 -2 -2"}),F("path",{d:"M5 13v-2"}),F("path",{d:"M5 7a2 2 0 0 1 2 -2"}),F("path",{d:"M11 5h2"}),F("path",{d:"M17 5a2 2 0 0 1 2 2"}),F("path",{d:"M19 11v2"}),F("path",{d:"M19 17v4"}),F("path",{d:"M21 19h-4"}),F("path",{d:"M13 19h-2"}))},arrowBackUp:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M9 14l-4 -4l4 -4"}),F("path",{d:"M5 10h11a4 4 0 1 1 0 8h-1"}))},arrowForwardUp:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M15 14l4 -4l-4 -4"}),F("path",{d:"M19 10h-11a4 4 0 1 0 0 8h1"}))},trash:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 7l16 0"}),F("path",{d:"M10 11l0 6"}),F("path",{d:"M14 11l0 6"}),F("path",{d:"M5 7l1 12a2 2 0 0 0 2 2h8a2 2 0 0 0 2 -2l1 -12"}),F("path",{d:"M9 7v-3a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v3"}))},deviceFloppy:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M6 4h10l4 4v10a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2"}),F("path",{d:"M12 14m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),F("path",{d:"M14 4l0 4l-6 0l0 -4"}))},pencilMarker:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none","stroke-linejoin":"round","stroke-linecap":"round","stroke-width":i,class:e.className,role:"img","aria-label":e.title},F("path",{d:"m9.109 16.275 8.856-8.097c.812-.743.87-2.014.127-2.826s-2.014-.869-2.826-.127L6.41 13.322l-.127 2.826zM13.79 6.575l2.7 2.952",stroke:"currentColor"}),F("path",{stroke:a,d:"M19.375 20.125c.569.063-4.05-.562-6.412-.437s-4.759 1.229-6.857 1.625c-1.764.687-3.404-.938-1.981-2.5"}))},circle:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r,s=e.secondaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:void 0===s?"none":s,stroke:a,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"}))},square:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r,s=e.secondaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:void 0===s?"none":s,stroke:a,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M3 3m0 2a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2z"}))},line:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2.2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M20 4l-16 16"}))},lineArrow:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2.2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M20 4l-16 16"}),F("path",{d:"M16 3h5v5"}))},polygon:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r,s=e.secondaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:void 0===s?"none":s,stroke:a,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M13.163 2.168l8.021 5.828c.694 .504 .984 1.397 .719 2.212l-3.064 9.43a1.978 1.978 0 0 1 -1.881 1.367h-9.916a1.978 1.978 0 0 1 -1.881 -1.367l-3.064 -9.43a1.978 1.978 0 0 1 .719 -2.212l8.021 -5.828a1.978 1.978 0 0 1 2.326 0z"}))},zigzag:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{d:"M12 2.4L21.36 11.76L2.64 12.24L12 21.6"}))},text:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M6.5 15.5m-3.5 0a3.5 3.5 0 1 0 7 0a3.5 3.5 0 1 0 -7 0"}),F("path",{d:"M14 19v-10.5a3.5 3.5 0 0 1 7 0v10.5"}),F("path",{d:"M14 13h7"}),F("path",{d:"M10 12v7"}))},italic:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M11 5l6 0"}),F("path",{d:"M7 19l6 0"}),F("path",{d:"M14 5l-4 14"}))},bold:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M7 5h6a3.5 3.5 0 0 1 0 7h-6z"}),F("path",{d:"M13 12h1a3.5 3.5 0 0 1 0 7h-7v-7"}))},alignLeft:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 6l16 0"}),F("path",{d:"M4 12l10 0"}),F("path",{d:"M4 18l14 0"}))},alignCenter:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 6l16 0"}),F("path",{d:"M8 12l8 0"}),F("path",{d:"M6 18l12 0"}))},alignRight:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 6l16 0"}),F("path",{d:"M10 12l10 0"}),F("path",{d:"M6 18l14 0"}))},alignTop:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M3 19v-14a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2z"}),F("path",{d:"M11 13h2"}),F("path",{d:"M9 10h6"}),F("path",{d:"M10 7h4"}))},alignMiddle:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M3 19v-14a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2z"}),F("path",{d:"M11 15h2"}),F("path",{d:"M9 12h6"}),F("path",{d:"M10 9h4"}))},alignBottom:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M3 19v-14a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2z"}),F("path",{d:"M11 17h2"}),F("path",{d:"M9 14h6"}),F("path",{d:"M10 11h4"}))},photo:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M15 8h.01"}),F("path",{d:"M3 6a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v12a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3v-12z"}),F("path",{d:"M3 16l5 -5c.928 -.893 2.072 -.893 3 0l5 5"}),F("path",{d:"M14 14l1 -1c.928 -.893 2.072 -.893 3 0l3 3"}))},pointer:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M7.904 17.563a1.2 1.2 0 0 0 2.228 .308l2.09 -3.093l4.907 4.907a1.067 1.067 0 0 0 1.509 0l1.047 -1.047a1.067 1.067 0 0 0 0 -1.509l-4.907 -4.907l3.113 -2.09a1.2 1.2 0 0 0 -.309 -2.228l-13.582 -3.904l3.904 13.563z"}))},redact:Qp,redactArea:Jp,redactCombined:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r,s=e.secondaryColor,l=void 0===s?"currentColor":s;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:a,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M6 20h-1a2 2 0 0 1 -2 -2v-1"}),F("path",{d:"M3 13v-3"}),F("path",{d:"M20 13v-3"}),F("path",{d:"M3 6v-1a2 2 0 0 1 2 -2h1"}),F("path",{d:"M10 3h3"}),F("path",{d:"M17 3h1a2 2 0 0 1 2 2v1"}),F("path",{d:"M8 8h8"}),F("path",{d:"M12 8v7"}),F("defs",null,F("clipPath",{id:"redactCombinedClip"},F("rect",{x:"10",y:"18",width:"13",height:"6",rx:"2"}))),F("rect",{x:"10",y:"17",width:"13",height:"6",rx:"2",fill:"none"}),F("g",{"clip-path":"url(#redactCombinedClip)",stroke:l},F("path",{d:"M6 19l12 -12"}),F("path",{d:"M6 23l12 -12"}),F("path",{d:"M10 23l12 -12"}),F("path",{d:"M14 27l12 -12"}),F("path",{d:"M14 23l12 -12"})))},check:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M5 12l5 5l10 -10"}))},file:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r,s=e.className,l=e.title;return F("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:a,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:s,"aria-hidden":!l,role:l?"img":"presentation"},l&&F("title",null,l),F("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),F("polyline",{points:"14 2 14 8 20 8"}))},plus:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r,s=e.className,l=e.title;return F("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:a,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:s,"aria-hidden":!l,role:l?"img":"presentation"},l&&F("title",null,l),F("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),F("line",{x1:"5",y1:"12",x2:"19",y2:"12"}))},lock:function(e){var t=e.size,n=void 0===t?24:t,o=e.className;return F("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:void 0===o?"":o,style:e.style},F("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),F("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}))},unlock:function(e){var t=e.size,n=void 0===t?24:t,o=e.className;return F("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:void 0===o?"":o,style:e.style},F("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),F("path",{d:"M7 11V7a5 5 0 0 1 9.9-1"}))},alertTriangle:function(e){var t=e.size,n=void 0===t?24:t,o=e.className;return F("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:void 0===o?"":o,style:e.style},F("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),F("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),F("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"}))},eye:function(e){var t=e.size,n=void 0===t?24:t,o=e.className;return F("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:void 0===o?"":o,style:e.style},F("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),F("circle",{cx:"12",cy:"12",r:"3"}))},"eye-off":function(e){var t=e.size,n=void 0===t?24:t,o=e.className;return F("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:void 0===o?"":o,style:e.style},F("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"}),F("line",{x1:"1",y1:"1",x2:"23",y2:"23"}))},info:function(e){var t=e.size,n=void 0===t?24:t,o=e.className;return F("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:void 0===o?"":o,style:e.style},F("circle",{cx:"12",cy:"12",r:"10"}),F("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),F("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"}))},link:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M9 15l6 -6"}),F("path",{d:"M11 6l.463 -.536a5 5 0 0 1 7.071 7.072l-.534 .464"}),F("path",{d:"M13 18l-.397 .534a5.068 5.068 0 0 1 -7.127 0a4.972 4.972 0 0 1 0 -7.071l.524 -.463"}))},linkOff:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M9 15l3 -3m2 -2l1 -1"}),F("path",{d:"M11 6l.463 -.536a5 5 0 0 1 7.072 7.071l-.534 .464"}),F("path",{d:"M13 18l-.397 .534a5.068 5.068 0 0 1 -7.127 0a4.972 4.972 0 0 1 0 -7.071l.524 -.463"}),F("path",{d:"M3 3l18 18"}))},externalLink:function(e){return F("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e.className},F("path",{d:"M12 6h-6a2 2 0 0 0 -2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-6"}),F("path",{d:"M11 13l9 -9"}),F("path",{d:"M15 4h5v5"}))},marqueeSelect:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M17 20h6"}),F("path",{d:"M20 17v6"}),F("path",{d:"M4 13v-2"}),F("path",{d:"M4 6v-1a1 1 0 0 1 1 -1h1"}),F("path",{d:"M6 20h-1a1 1 0 0 1 -1 -1v-1"}),F("path",{d:"M11 4h2"}),F("path",{d:"M11 20h2"}),F("path",{d:"M18 4h1a1 1 0 0 1 1 1v1"}),F("path",{d:"M20 11v2"}))},group:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M3 5a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),F("path",{d:"M17 5a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),F("path",{d:"M3 19a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),F("path",{d:"M17 19a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),F("path",{d:"M5 7v10"}),F("path",{d:"M19 7v10"}),F("path",{d:"M7 5h10"}),F("path",{d:"M7 19h10"}),F("path",{d:"M8 8H12.8V11.2H16V16H11.2V12.8H8V8Z"}))},ungroup:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("rect",{x:"4",y:"4",width:"7",height:"7",rx:"1"}),F("rect",{x:"13",y:"13",width:"7",height:"7",rx:"1"}))},redactionSidebar:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 6a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z"}),F("path",{d:"M15 4v16"}),F("path",{d:"M7 8h5"}),F("path",{d:"M7 11h5"}),F("path",{d:"M7 14h4"}))}},tf=new Map,nf=/^[MmZzLlHhVvCcSsQqTtAa0-9\s,.\-eE]+$/;function of(e){return nf.test(e.trim())}function rf(e,t){for(var n=function(e){var t,n;return"path"in e?{viewBox:e.viewBox||"0 0 24 24",paths:[{d:e.path,stroke:null!==(t=e.stroke)&&void 0!==t?t:"primary",fill:null!==(n=e.fill)&&void 0!==n?n:"none",strokeWidth:e.strokeWidth}],strokeLinecap:e.strokeLinecap||"round",strokeLinejoin:e.strokeLinejoin||"round",strokeWidth:e.strokeWidth}:{viewBox:e.viewBox||"0 0 24 24",paths:e.paths,strokeLinecap:e.strokeLinecap||"round",strokeLinejoin:e.strokeLinejoin||"round",strokeWidth:e.strokeWidth}}(t),o=0;o({x:e,y:e}),ff={left:"right",right:"left",bottom:"top",top:"bottom"},vf={start:"end",end:"start"};function yf(e,t,n){return hf(e,uf(t,n))}function bf(e,t){return"function"==typeof e?e(t):e}function wf(e){return e.split("-")[0]}function xf(e){return e.split("-")[1]}function Cf(e){return"x"===e?"y":"x"}function If(e){return"y"===e?"height":"width"}const kf=new Set(["top","bottom"]);function Sf(e){return kf.has(wf(e))?"y":"x"}function Mf(e){return Cf(Sf(e))}function Af(e){return e.replace(/start|end/g,e=>vf[e])}const Pf=["left","right"],Df=["right","left"],Rf=["top","bottom"],zf=["bottom","top"];function Tf(e,t,n,o){const i=xf(e);let r=function(e,t,n){switch(e){case"top":case"bottom":return n?t?Df:Pf:t?Pf:Df;case"left":case"right":return t?Rf:zf;default:return[]}}(wf(e),"start"===n,o);return i&&(r=r.map(e=>e+"-"+i),t&&(r=r.concat(r.map(Af)))),r}function Ef(e){return e.replace(/left|right|bottom|top/g,e=>ff[e])}function _f(e){return"number"!=typeof e?function(e){return{top:0,right:0,bottom:0,left:0,...e}}(e):{top:e,right:e,bottom:e,left:e}}function Nf(e){const{x:t,y:n,width:o,height:i}=e;return{width:o,height:i,top:n,left:t,right:t+o,bottom:n+i,x:t,y:n}}function Of(e,t,n){let{reference:o,floating:i}=e;const r=Sf(t),a=Mf(t),s=If(a),l=wf(t),c="y"===r,d=o.x+o.width/2-i.width/2,u=o.y+o.height/2-i.height/2,h=o[s]/2-i[s]/2;let m;switch(l){case"top":m={x:d,y:o.y-i.height};break;case"bottom":m={x:d,y:o.y+o.height};break;case"right":m={x:o.x+o.width,y:u};break;case"left":m={x:o.x-i.width,y:u};break;default:m={x:o.x,y:o.y}}switch(xf(t)){case"start":m[a]-=h*(n&&c?-1:1);break;case"end":m[a]+=h*(n&&c?-1:1)}return m}async function Lf(e,t){var n;void 0===t&&(t={});const{x:o,y:i,platform:r,rects:a,elements:s,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:u="floating",altBoundary:h=!1,padding:m=0}=bf(t,e),g=_f(m),p=s[h?"floating"===u?"reference":"floating":u],f=Nf(await r.getClippingRect({element:null==(n=await(null==r.isElement?void 0:r.isElement(p)))||n?p:p.contextElement||await(null==r.getDocumentElement?void 0:r.getDocumentElement(s.floating)),boundary:c,rootBoundary:d,strategy:l})),v="floating"===u?{x:o,y:i,width:a.floating.width,height:a.floating.height}:a.reference,y=await(null==r.getOffsetParent?void 0:r.getOffsetParent(s.floating)),b=await(null==r.isElement?void 0:r.isElement(y))&&await(null==r.getScale?void 0:r.getScale(y))||{x:1,y:1},w=Nf(r.convertOffsetParentRelativeRectToViewportRelativeRect?await r.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:v,offsetParent:y,strategy:l}):v);return{top:(f.top-w.top+g.top)/b.y,bottom:(w.bottom-f.bottom+g.bottom)/b.y,left:(f.left-w.left+g.left)/b.x,right:(w.right-f.right+g.right)/b.x}}const $f=new Set(["left","top"]);function jf(){return"undefined"!=typeof window}function Ff(e){return Bf(e)?(e.nodeName||"").toLowerCase():"#document"}function Uf(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Hf(e){var t;return null==(t=(Bf(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function Bf(e){return!!jf()&&(e instanceof Node||e instanceof Uf(e).Node)}function Wf(e){return!!jf()&&(e instanceof Element||e instanceof Uf(e).Element)}function qf(e){return!!jf()&&(e instanceof HTMLElement||e instanceof Uf(e).HTMLElement)}function Gf(e){return!(!jf()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Uf(e).ShadowRoot)}const Vf=new Set(["inline","contents"]);function Kf(e){const{overflow:t,overflowX:n,overflowY:o,display:i}=av(e);return/auto|scroll|overlay|hidden|clip/.test(t+o+n)&&!Vf.has(i)}const Zf=new Set(["table","td","th"]);function Yf(e){return Zf.has(Ff(e))}const Xf=[":popover-open",":modal"];function Qf(e){return Xf.some(t=>{try{return e.matches(t)}catch(e){return!1}})}const Jf=["transform","translate","scale","rotate","perspective"],ev=["transform","translate","scale","rotate","perspective","filter"],tv=["paint","layout","strict","content"];function nv(e){const t=ov(),n=Wf(e)?av(e):e;return Jf.some(e=>!!n[e]&&"none"!==n[e])||!!n.containerType&&"normal"!==n.containerType||!t&&!!n.backdropFilter&&"none"!==n.backdropFilter||!t&&!!n.filter&&"none"!==n.filter||ev.some(e=>(n.willChange||"").includes(e))||tv.some(e=>(n.contain||"").includes(e))}function ov(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("-webkit-backdrop-filter","none")}const iv=new Set(["html","body","#document"]);function rv(e){return iv.has(Ff(e))}function av(e){return Uf(e).getComputedStyle(e)}function sv(e){return Wf(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function lv(e){if("html"===Ff(e))return e;const t=e.assignedSlot||e.parentNode||Gf(e)&&e.host||Hf(e);return Gf(t)?t.host:t}function cv(e){const t=lv(e);return rv(t)?e.ownerDocument?e.ownerDocument.body:e.body:qf(t)&&Kf(t)?t:cv(t)}function dv(e,t,n){var o;void 0===t&&(t=[]),void 0===n&&(n=!0);const i=cv(e),r=i===(null==(o=e.ownerDocument)?void 0:o.body),a=Uf(i);if(r){const e=uv(a);return t.concat(a,a.visualViewport||[],Kf(i)?i:[],e&&n?dv(e):[])}return t.concat(i,dv(i,[],n))}function uv(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function hv(e){const t=av(e);let n=parseFloat(t.width)||0,o=parseFloat(t.height)||0;const i=qf(e),r=i?e.offsetWidth:n,a=i?e.offsetHeight:o,s=mf(n)!==r||mf(o)!==a;return s&&(n=r,o=a),{width:n,height:o,$:s}}function mv(e){return Wf(e)?e:e.contextElement}function gv(e){const t=mv(e);if(!qf(t))return pf(1);const n=t.getBoundingClientRect(),{width:o,height:i,$:r}=hv(t);let a=(r?mf(n.width):n.width)/o,s=(r?mf(n.height):n.height)/i;return a&&Number.isFinite(a)||(a=1),s&&Number.isFinite(s)||(s=1),{x:a,y:s}}const pv=pf(0);function fv(e){const t=Uf(e);return ov()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:pv}function vv(e,t,n,o){void 0===t&&(t=!1),void 0===n&&(n=!1);const i=e.getBoundingClientRect(),r=mv(e);let a=pf(1);t&&(o?Wf(o)&&(a=gv(o)):a=gv(e));const s=function(e,t,n){return void 0===t&&(t=!1),!(!n||t&&n!==Uf(e))&&t}(r,n,o)?fv(r):pf(0);let l=(i.left+s.x)/a.x,c=(i.top+s.y)/a.y,d=i.width/a.x,u=i.height/a.y;if(r){const e=Uf(r),t=o&&Wf(o)?Uf(o):o;let n=e,i=uv(n);for(;i&&o&&t!==n;){const e=gv(i),t=i.getBoundingClientRect(),o=av(i),r=t.left+(i.clientLeft+parseFloat(o.paddingLeft))*e.x,a=t.top+(i.clientTop+parseFloat(o.paddingTop))*e.y;l*=e.x,c*=e.y,d*=e.x,u*=e.y,l+=r,c+=a,n=Uf(i),i=uv(n)}}return Nf({width:d,height:u,x:l,y:c})}function yv(e,t){const n=sv(e).scrollLeft;return t?t.left+n:vv(Hf(e)).left+n}function bv(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-yv(e,n),y:n.top+t.scrollTop}}const wv=new Set(["absolute","fixed"]);function xv(e,t,n){let o;if("viewport"===t)o=function(e,t){const n=Uf(e),o=Hf(e),i=n.visualViewport;let r=o.clientWidth,a=o.clientHeight,s=0,l=0;if(i){r=i.width,a=i.height;const e=ov();(!e||e&&"fixed"===t)&&(s=i.offsetLeft,l=i.offsetTop)}const c=yv(o);if(c<=0){const e=o.ownerDocument,t=e.body,n=getComputedStyle(t),i="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,a=Math.abs(o.clientWidth-t.clientWidth-i);a<=25&&(r-=a)}else c<=25&&(r+=c);return{width:r,height:a,x:s,y:l}}(e,n);else if("document"===t)o=function(e){const t=Hf(e),n=sv(e),o=e.ownerDocument.body,i=hf(t.scrollWidth,t.clientWidth,o.scrollWidth,o.clientWidth),r=hf(t.scrollHeight,t.clientHeight,o.scrollHeight,o.clientHeight);let a=-n.scrollLeft+yv(e);const s=-n.scrollTop;return"rtl"===av(o).direction&&(a+=hf(t.clientWidth,o.clientWidth)-i),{width:i,height:r,x:a,y:s}}(Hf(e));else if(Wf(t))o=function(e,t){const n=vv(e,!0,"fixed"===t),o=n.top+e.clientTop,i=n.left+e.clientLeft,r=qf(e)?gv(e):pf(1);return{width:e.clientWidth*r.x,height:e.clientHeight*r.y,x:i*r.x,y:o*r.y}}(t,n);else{const n=fv(e);o={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return Nf(o)}function Cv(e,t){const n=lv(e);return!(n===t||!Wf(n)||rv(n))&&("fixed"===av(n).position||Cv(n,t))}function Iv(e,t,n){const o=qf(t),i=Hf(t),r="fixed"===n,a=vv(e,!0,r,t);let s={scrollLeft:0,scrollTop:0};const l=pf(0);function c(){l.x=yv(i)}if(o||!o&&!r)if(("body"!==Ff(t)||Kf(i))&&(s=sv(t)),o){const e=vv(t,!0,r,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}else i&&c();r&&!o&&i&&c();const d=!i||o||r?pf(0):bv(i,s);return{x:a.left+s.scrollLeft-l.x-d.x,y:a.top+s.scrollTop-l.y-d.y,width:a.width,height:a.height}}function kv(e){return"static"===av(e).position}function Sv(e,t){if(!qf(e)||"fixed"===av(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Hf(e)===n&&(n=n.ownerDocument.body),n}function Mv(e,t){const n=Uf(e);if(Qf(e))return n;if(!qf(e)){let t=lv(e);for(;t&&!rv(t);){if(Wf(t)&&!kv(t))return t;t=lv(t)}return n}let o=Sv(e,t);for(;o&&Yf(o)&&kv(o);)o=Sv(o,t);return o&&rv(o)&&kv(o)&&!nv(o)?n:o||function(e){let t=lv(e);for(;qf(t)&&!rv(t);){if(nv(t))return t;if(Qf(t))return null;t=lv(t)}return null}(e)||n}const Av={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:n,offsetParent:o,strategy:i}=e;const r="fixed"===i,a=Hf(o),s=!!t&&Qf(t.floating);if(o===a||s&&r)return n;let l={scrollLeft:0,scrollTop:0},c=pf(1);const d=pf(0),u=qf(o);if((u||!u&&!r)&&(("body"!==Ff(o)||Kf(a))&&(l=sv(o)),qf(o))){const e=vv(o);c=gv(o),d.x=e.x+o.clientLeft,d.y=e.y+o.clientTop}const h=!a||u||r?pf(0):bv(a,l);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+d.x+h.x,y:n.y*c.y-l.scrollTop*c.y+d.y+h.y}},getDocumentElement:Hf,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:o,strategy:i}=e;const r=[..."clippingAncestors"===n?Qf(t)?[]:function(e,t){const n=t.get(e);if(n)return n;let o=dv(e,[],!1).filter(e=>Wf(e)&&"body"!==Ff(e)),i=null;const r="fixed"===av(e).position;let a=r?lv(e):e;for(;Wf(a)&&!rv(a);){const t=av(a),n=nv(a);n||"fixed"!==t.position||(i=null),(r?!n&&!i:!n&&"static"===t.position&&i&&wv.has(i.position)||Kf(a)&&!n&&Cv(e,a))?o=o.filter(e=>e!==a):i=t,a=lv(a)}return t.set(e,o),o}(t,this._c):[].concat(n),o],a=r[0],s=r.reduce((e,n)=>{const o=xv(t,n,i);return e.top=hf(o.top,e.top),e.right=uf(o.right,e.right),e.bottom=uf(o.bottom,e.bottom),e.left=hf(o.left,e.left),e},xv(t,a,i));return{width:s.right-s.left,height:s.bottom-s.top,x:s.left,y:s.top}},getOffsetParent:Mv,getElementRects:async function(e){const t=this.getOffsetParent||Mv,n=this.getDimensions,o=await n(e.floating);return{reference:Iv(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:o.width,height:o.height}}},getClientRects:function(e){return Array.from(e.getClientRects())},getDimensions:function(e){const{width:t,height:n}=hv(e);return{width:t,height:n}},getScale:gv,isElement:Wf,isRTL:function(e){return"rtl"===av(e).direction}};function Pv(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Dv(e,t,n,o){void 0===o&&(o={});const{ancestorScroll:i=!0,ancestorResize:r=!0,elementResize:a="function"==typeof ResizeObserver,layoutShift:s="function"==typeof IntersectionObserver,animationFrame:l=!1}=o,c=mv(e),d=i||r?[...c?dv(c):[],...dv(t)]:[];d.forEach(e=>{i&&e.addEventListener("scroll",n,{passive:!0}),r&&e.addEventListener("resize",n)});const u=c&&s?function(e,t){let n,o=null;const i=Hf(e);function r(){var e;clearTimeout(n),null==(e=o)||e.disconnect(),o=null}return function a(s,l){void 0===s&&(s=!1),void 0===l&&(l=1),r();const c=e.getBoundingClientRect(),{left:d,top:u,width:h,height:m}=c;if(s||t(),!h||!m)return;const g={rootMargin:-gf(u)+"px "+-gf(i.clientWidth-(d+h))+"px "+-gf(i.clientHeight-(u+m))+"px "+-gf(d)+"px",threshold:hf(0,uf(1,l))||1};let p=!0;function f(t){const o=t[0].intersectionRatio;if(o!==l){if(!p)return a();o?a(!1,o):n=setTimeout(()=>{a(!1,1e-7)},1e3)}1!==o||Pv(c,e.getBoundingClientRect())||a(),p=!1}try{o=new IntersectionObserver(f,{...g,root:i.ownerDocument})}catch(e){o=new IntersectionObserver(f,g)}o.observe(e)}(!0),r}(c,n):null;let h,m=-1,g=null;a&&(g=new ResizeObserver(e=>{let[o]=e;o&&o.target===c&&g&&(g.unobserve(t),cancelAnimationFrame(m),m=requestAnimationFrame(()=>{var e;null==(e=g)||e.observe(t)})),n()}),c&&!l&&g.observe(c),g.observe(t));let p=l?vv(e):null;return l&&function t(){const o=vv(e);p&&!Pv(p,o)&&n();p=o,h=requestAnimationFrame(t)}(),n(),()=>{var e;d.forEach(e=>{i&&e.removeEventListener("scroll",n),r&&e.removeEventListener("resize",n)}),null==u||u(),null==(e=g)||e.disconnect(),g=null,l&&cancelAnimationFrame(h)}}const Rv=function(e){return void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var n,o;const{x:i,y:r,placement:a,middlewareData:s}=t,l=await async function(e,t){const{placement:n,platform:o,elements:i}=e,r=await(null==o.isRTL?void 0:o.isRTL(i.floating)),a=wf(n),s=xf(n),l="y"===Sf(n),c=$f.has(a)?-1:1,d=r&&l?-1:1,u=bf(t,e);let{mainAxis:h,crossAxis:m,alignmentAxis:g}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return s&&"number"==typeof g&&(m="end"===s?-1*g:g),l?{x:m*d,y:h*c}:{x:h*c,y:m*d}}(t,e);return a===(null==(n=s.offset)?void 0:n.placement)&&null!=(o=s.arrow)&&o.alignmentOffset?{}:{x:i+l.x,y:r+l.y,data:{...l,placement:a}}}}},zv=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:o,placement:i,platform:r}=t,{mainAxis:a=!0,crossAxis:s=!1,limiter:l={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...c}=bf(e,t),d={x:n,y:o},u=await r.detectOverflow(t,c),h=Sf(wf(i)),m=Cf(h);let g=d[m],p=d[h];if(a){const e="y"===m?"bottom":"right";g=yf(g+u["y"===m?"top":"left"],g,g-u[e])}if(s){const e="y"===h?"bottom":"right";p=yf(p+u["y"===h?"top":"left"],p,p-u[e])}const f=l.fn({...t,[m]:g,[h]:p});return{...f,data:{x:f.x-n,y:f.y-o,enabled:{[m]:a,[h]:s}}}}}},Tv=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,o;const{placement:i,middlewareData:r,rects:a,initialPlacement:s,platform:l,elements:c}=t,{mainAxis:d=!0,crossAxis:u=!0,fallbackPlacements:h,fallbackStrategy:m="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:p=!0,...f}=bf(e,t);if(null!=(n=r.arrow)&&n.alignmentOffset)return{};const v=wf(i),y=Sf(s),b=wf(s)===s,w=await(null==l.isRTL?void 0:l.isRTL(c.floating)),x=h||(b||!p?[Ef(s)]:function(e){const t=Ef(e);return[Af(e),t,Af(t)]}(s)),C="none"!==g;!h&&C&&x.push(...Tf(s,p,g,w));const I=[s,...x],k=await l.detectOverflow(t,f),S=[];let M=(null==(o=r.flip)?void 0:o.overflows)||[];if(d&&S.push(k[v]),u){const e=function(e,t,n){void 0===n&&(n=!1);const o=xf(e),i=Mf(e),r=If(i);let a="x"===i?o===(n?"end":"start")?"right":"left":"start"===o?"bottom":"top";return t.reference[r]>t.floating[r]&&(a=Ef(a)),[a,Ef(a)]}(i,a,w);S.push(k[e[0]],k[e[1]])}if(M=[...M,{placement:i,overflows:S}],!S.every(e=>e<=0)){var A,P;const e=((null==(A=r.flip)?void 0:A.index)||0)+1,t=I[e];if(t){if(!("alignment"===u&&y!==Sf(t))||M.every(e=>Sf(e.placement)!==y||e.overflows[0]>0))return{data:{index:e,overflows:M},reset:{placement:t}}}let n=null==(P=M.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:P.placement;if(!n)switch(m){case"bestFit":{var D;const e=null==(D=M.filter(e=>{if(C){const t=Sf(e.placement);return t===y||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:D[0];e&&(n=e);break}case"initialPlacement":n=s}if(i!==n)return{reset:{placement:n}}}return{}}}},Ev=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:o,placement:i,rects:r,platform:a,elements:s,middlewareData:l}=t,{element:c,padding:d=0}=bf(e,t)||{};if(null==c)return{};const u=_f(d),h={x:n,y:o},m=Mf(i),g=If(m),p=await a.getDimensions(c),f="y"===m,v=f?"top":"left",y=f?"bottom":"right",b=f?"clientHeight":"clientWidth",w=r.reference[g]+r.reference[m]-h[m]-r.floating[g],x=h[m]-r.reference[m],C=await(null==a.getOffsetParent?void 0:a.getOffsetParent(c));let I=C?C[b]:0;I&&await(null==a.isElement?void 0:a.isElement(C))||(I=s.floating[b]||r.floating[g]);const k=w/2-x/2,S=I/2-p[g]/2-1,M=uf(u[v],S),A=uf(u[y],S),P=M,D=I-p[g]-A,R=I/2-p[g]/2+k,z=yf(P,R,D),T=!l.arrow&&null!=xf(i)&&R!==z&&r.reference[g]/2-(R{const o=new Map,i={platform:Av,...n},r={...i.platform,_c:o};return(async(e,t,n)=>{const{placement:o="bottom",strategy:i="absolute",middleware:r=[],platform:a}=n,s=r.filter(Boolean),l=await(null==a.isRTL?void 0:a.isRTL(t));let c=await a.getElementRects({reference:e,floating:t,strategy:i}),{x:d,y:u}=Of(c,o,l),h=o,m={},g=0;for(let n=0;n=75?"full":o<=25?"closed":"half",C.current={y:e,height:o,time:Date.now(),state:t},I.current={y:e,time:Date.now()},f(0),t!==c&&d(t),m(!0)}},[s,c]),M=ze(function(e){if(h){var t=s.clientHeight,n=(C.current.y-e)/t*100,o=Math.max(0,Math.min(100,C.current.height+n));I.current={y:e,time:Date.now()};var i=k(C.current.state);f(o-i)}},[h,s]),A=ze(function(){if(h){if(Math.abs(C.current.y-I.current.y)<5)return m(!1),void f(0);var e=k(C.current.state)+p,t=Date.now()-I.current.time,n=I.current.y-C.current.y,o=function(e,t){return Math.abs(t)>.5?t>0?e>50?"half":"closed":e<50?"half":"full":e>=75?"full":e<=25?"closed":"half"}(e,t>0?n/t:0);"closed"===o?(d("closed"),m(!1),f(0),i()):(m(!1),f(0),d(o))}},[h,p,i]),P=ze(function(e){S(e.touches[0].clientY)},[S]),D=ze(function(e){h&&(e.cancelable&&e.preventDefault(),M(e.touches[0].clientY))},[h,M]),R=ze(function(){A()},[A]),z=ze(function(e){e.preventDefault(),S(e.clientY)},[S]);if(Ae(function(){if(h){var e=function(e){M(e.clientY)},t=function(){A()};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",t),function(){document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",t)}}},[h,M,A]),!b)return null;var T=k(h?C.current.state:c),E=h?Math.max(0,Math.min(100,T+p)):T,_=.3*Math.min(E/50,1);return F(H,null,F("div",{className:"bg-bg-overlay absolute inset-0 z-40 transition-opacity duration-300 ".concat(0===E?"pointer-events-none":""),style:{opacity:_},onClick:i}),F("div",{ref:x,className:"bg-bg-surface absolute inset-x-0 bottom-0 z-50 flex flex-col rounded-t-2xl shadow-2xl ".concat(h?"":"transition-[height] duration-300 ease-out"),style:{height:"".concat(E,"%")},"data-sidebar-id":t.id},F("div",{className:"flex flex-shrink-0 cursor-grab touch-none items-center justify-center py-3 active:cursor-grabbing",onTouchStart:P,onTouchMove:D,onTouchEnd:R,onMouseDown:z},F("div",{className:"bg-border-default h-1.5 w-12 rounded-full"})),F("div",{className:"min-h-0 flex-1 overflow-hidden"},"tabs"===a.type&&F(Yv,{content:a,documentId:n,renderCustomComponent:r}),"component"===a.type&&F(H,null,r(a.componentId,n,{})))))}function Yv(e){var t,n=e.content,o=e.documentId,i=e.renderCustomComponent,r=v(Se((null===(t=n.tabs[0])||void 0===t?void 0:t.id)||""),2),a=r[0],s=r[1];return F("div",{className:"flex h-full flex-1 flex-col"},F("div",{role:"tablist",className:"bg-bg-surface mx-4 my-4 flex flex-shrink-0 overflow-hidden"},n.tabs.map(function(e,t,n){var o=a===e.id,i=0===t,r=t===n.length-1;return F("button",{key:e.id,role:"tab","aria-selected":o,tabIndex:o?0:-1,onClick:function(){return s(e.id)},className:"relative flex h-7 flex-1 cursor-pointer items-center justify-center border outline-none transition-colors ".concat(i?"rounded-l-md":""," ").concat(r?"rounded-r-md":""," ").concat(r?"":"border-r-0"," ").concat(o?"border-accent bg-accent text-fg-on-accent":"border-border-default text-fg-secondary hover:bg-interactive-hover")},e.icon&&F(lf,{icon:e.icon,className:"h-5 w-5"}))})),F("div",{className:"min-h-0 flex-1 overflow-auto"},n.tabs.filter(function(e){return e.id===a}).map(function(e){return F(H,{key:e.id},i(e.componentId,o,{}))})))}function Xv(e){var t=e.schema,n=e.documentId,o=e.anchorEl,i=e.onClose,r=Qr().getContainer,a=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:768,n=v(Se(function(){var n=e();return!!n&&n.clientWidth{const{provides:e}=Zr();return(null==e?void 0:e.getSchema())??null})(),c=v(Se([{menuId:t.id,schema:t,title:void 0}]),2),d=c[0],u=c[1];Ae(function(){u([{menuId:t.id,schema:t,title:void 0}])},[t]);var h=d[d.length-1],m=ze(function(e,t){if(l){var n=l.menus[e];n?u(function(o){return[].concat(y(o),[{menuId:e,schema:n,title:t}])}):console.warn("Submenu schema not found: ".concat(e))}},[l]),g=ze(function(){d.length>1&&u(function(e){return e.slice(0,-1)})},[d.length]);return h?a&&s?Pu(F(Qv,{currentMenu:h,menuStack:d,documentId:n,onClose:i,onNavigateBack:g,onNavigateToSubmenu:m,container:s}),s):F(Jv,{currentMenu:h,documentId:n,anchorEl:o,onClose:i,onNavigateToSubmenu:m}):null}function Qv(e){var t=e.currentMenu,n=e.menuStack,o=e.documentId,i=e.onClose,r=e.onNavigateBack,a=e.onNavigateToSubmenu,s=e.container,l=v(Se(!1),2),c=l[0],d=l[1],u=v(Se(!1),2),m=u[0],g=u[1],p=v(Se(0),2),f=p[0],y=p[1],b=De(null),w=De(null),x=De({isDragging:!1,startY:0,currentY:0,startTime:0,sheetHeight:0});Ae(function(){d(!0),requestAnimationFrame(function(){requestAnimationFrame(function(){g(!0)})})},[]);var C=v(Se(null),2),I=C[0],k=C[1];Ae(function(){if(w.current){var e=(n.length>1?60:0)+w.current.scrollHeight+24,t=.8*s.clientHeight;k(Math.min(e,t))}},[t,n.length,s]);var S=ze(function(){g(!1),setTimeout(function(){d(!1),i()},300)},[i]),M=ze(function(e){b.current&&(x.current={isDragging:!0,startY:e,currentY:e,startTime:Date.now(),sheetHeight:b.current.offsetHeight})},[]),A=ze(function(e){if(x.current.isDragging){var t=e-x.current.startY,n=Math.max(0,t);x.current.currentY=e,y(n)}},[]),P=ze(function(){if(x.current.isDragging){var e=x.current,t=e.startY,n=e.currentY,o=e.startTime,i=e.sheetHeight,r=Math.abs(t-n);if(x.current.isDragging=!1,r<5)y(0);else{var a=n-t,s=a/i*100,l=Date.now()-o;s>30||(l>0?a/l:0)>.5?S():y(0)}}},[S]),D=ze(function(e){M(e.touches[0].clientY)},[M]),R=ze(function(e){x.current.isDragging&&e.cancelable&&e.preventDefault(),A(e.touches[0].clientY)},[A]),z=ze(function(){P()},[P]),T=ze(function(e){e.preventDefault(),M(e.clientY)},[M]);if(Ae(function(){if(x.current.isDragging){var e=function(e){return A(e.clientY)},t=function(){return P()};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",t),function(){document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",t)}}},[A,P]),Ae(function(){var e=function(e){"Escape"===e.key&&S()};return document.addEventListener("keydown",e),function(){return document.removeEventListener("keydown",e)}},[S]),!c)return null;var E=m?f:I||400;return F(H,null,F("div",{className:"bg-bg-overlay absolute inset-0 z-40 transition-opacity duration-300 ".concat(m?"opacity-100":"opacity-0"),onClick:S}),F("div",h({ref:b,className:"bg-bg-surface absolute inset-x-0 bottom-0 z-50 flex flex-col rounded-t-2xl shadow-2xl ".concat(x.current.isDragging?"":"transition-transform duration-300 ease-out"),style:{maxHeight:"80%",transform:"translateY(".concat(E,"px)")}},jr(t.schema)),F("div",{className:"flex flex-shrink-0 cursor-grab touch-none items-center justify-center py-3 active:cursor-grabbing",onTouchStart:D,onTouchMove:R,onTouchEnd:z,onMouseDown:T},F("div",{className:"bg-border-default h-1.5 w-12 rounded-full"})),n.length>1&&F("div",{className:"border-border-subtle flex items-center gap-3 border-b px-4 pb-3"},F("button",{onClick:r,className:"hover:bg-interactive-hover rounded-full p-1"},F(Kp,{className:"h-5 w-5"})),F("h3",{className:"text-fg-primary font-semibold"},t.title||"Menu")),F("div",{ref:w,className:"flex-1 overflow-y-auto py-2"},t.schema.items.map(function(e){return F(ey,{key:e.id,item:e,documentId:o,onClose:S,isMobile:!0,onNavigateToSubmenu:a})}))))}function Jv(e){var t=e.currentMenu,n=e.documentId,o=e.anchorEl,i=e.onClose,r=e.onNavigateToSubmenu,a=De(null),s=v(Se(null),2),l=s[0],c=s[1];Ae(function(){if(o){var e=function(){var e,t=o.getBoundingClientRect(),n=(null===(e=a.current)||void 0===e?void 0:e.offsetWidth)||200,i=t.bottom+4,r=t.left;r+n>window.innerWidth&&(r=window.innerWidth-n-8),r<8&&(r=8),c({top:i,left:r})};return e(),window.addEventListener("scroll",e),window.addEventListener("resize",e),function(){window.removeEventListener("scroll",e),window.removeEventListener("resize",e)}}},[o]),Ae(function(){var e=function(e){if(a.current){var t=e.composedPath(),n=t.includes(a.current),r=o&&t.includes(o);n||r||i()}},t=setTimeout(function(){document.addEventListener("mousedown",e)},0);return function(){clearTimeout(t),document.removeEventListener("mousedown",e)}},[i,o]),Ae(function(){var e=function(e){"Escape"===e.key&&i()};return document.addEventListener("keydown",e),function(){return document.removeEventListener("keydown",e)}},[i]);var d=l?{position:"fixed",top:"".concat(l.top,"px"),left:"".concat(l.left,"px"),zIndex:1e3}:{display:"none"};return F("div",h(h({ref:a},jr(t.schema)),{},{className:"border-border-default bg-bg-elevated min-w-[200px] rounded-lg border py-2 shadow-lg",style:d}),t.schema.items.map(function(e){return F(ey,{key:e.id,item:e,documentId:n,onClose:i,isMobile:!1,onNavigateToSubmenu:r})}))}function ey(e){var t=e.item,n=e.documentId,o=e.onClose,i=e.isMobile,r=e.onNavigateToSubmenu;switch(t.type){case"command":return F(ty,{item:t,documentId:n,onClose:o,isMobile:i});case"submenu":return F(ny,{item:t,documentId:n,isMobile:i,onNavigateToSubmenu:r});case"divider":return F("div",h({},jr(t)),F("hr",{className:"border-border-subtle my-2"}));case"section":return F(oy,{item:t,documentId:n,onClose:o,isMobile:i,onNavigateToSubmenu:r});default:return null}}function ty(e){var t,n,o=e.item,i=e.documentId,r=e.onClose,a=e.isMobile,s=Aa(o.commandId,i);if(!s||!s.visible)return null;var l,c,d=function(){s.disabled||(s.execute(),r())};return a?F("button",h(h({},jr(o)),{},{onClick:d,disabled:s.disabled,className:"active:bg-interactive-active flex w-full items-center gap-3 px-4 py-3 text-left text-base transition-colors ".concat(s.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"," ").concat(s.active?"bg-interactive-selected text-accent":"text-fg-secondary"),role:"menuitem"}),s.icon&&F(lf,{icon:s.icon,className:"h-5 w-5",primaryColor:null===(l=s.iconProps)||void 0===l?void 0:l.primaryColor,secondaryColor:null===(c=s.iconProps)||void 0===c?void 0:c.secondaryColor}),F("span",{className:"flex-1"},s.label)):F("button",h(h({},jr(o)),{},{onClick:d,disabled:s.disabled,className:"flex w-full items-center justify-between gap-2 px-4 py-1 text-left ".concat(s.disabled?"pointer-events-none cursor-not-allowed opacity-50":"cursor-pointer"," ").concat(s.active&&!s.disabled?"bg-accent text-fg-on-accent":"text-fg-muted hover:bg-accent hover:text-fg-on-accent"),role:"menuitem"}),F("div",{className:"flex items-center gap-2"},F("div",{className:"flex h-6 w-6 items-center justify-center"},s.icon&&F(lf,{icon:s.icon,className:"h-6 w-6",primaryColor:null===(t=s.iconProps)||void 0===t?void 0:t.primaryColor,secondaryColor:null===(n=s.iconProps)||void 0===n?void 0:n.secondaryColor})),F("span",{className:"text-sm"},s.label)))}function ny(e){var t=e.item,n=e.documentId,o=e.isMobile,i=e.onNavigateToSubmenu,r=ja(n).translate,a=t.labelKey?r(t.labelKey):t.label||"",s=function(){return i(t.menuId,a)};return o?F("button",h(h({},jr(t)),{},{onClick:s,className:"text-fg-secondary active:bg-interactive-active flex w-full cursor-pointer items-center gap-3 px-4 py-3 text-left text-base transition-colors",role:"menuitem"}),F("span",{className:"flex-1"},a),F(Vp,{className:"h-4 w-4"})):F("button",h(h({},jr(t)),{},{onClick:s,className:"text-fg-muted hover:bg-accent hover:text-fg-on-accent flex w-full cursor-pointer items-center justify-between gap-2 px-4 py-1 text-left",role:"menuitem"}),F("span",{className:"text-sm"},a),F(Vp,{className:"h-6 w-6"}))}function oy(e){var t=e.item,n=e.documentId,o=e.onClose,i=e.isMobile,r=e.onNavigateToSubmenu,a=ja(n).translate,s=t.labelKey?a(t.labelKey):t.label||"";return F("div",h({},jr(t)),F("div",{className:"text-fg-secondary px-4 py-3 text-xs font-medium uppercase"},s),t.items.map(function(e){return F(ey,{key:e.id,item:e,documentId:n,onClose:o,isMobile:i,onNavigateToSubmenu:r})}))}function iy(e){var t=e.schema,n=e.documentId,o=e.isOpen,i=e.onClose,r=e.onExited,a=e.modalProps,s=t.content,l=ra().renderCustomComponent;return"component"!==s.type?(console.warn("SchemaModal only supports component content type, got: ".concat(s.type)),null):F(H,null,l(s.componentId,n,h({isOpen:o,onClose:i,onExited:r},a)))}function ry(e){var t=e.documentId;e.onClose;var n=Ai(t),o=n.state,i=n.provides;return F("div",{className:"flex h-full flex-1 flex-col"},F("div",{className:"flex-1 overflow-hidden"},F(yc,{documentId:t,style:{width:"100%",height:"100%"}},function(e){return F("div",{key:e.pageIndex,style:{position:"absolute",width:"100%",height:e.wrapperHeight,top:e.top,display:"flex",flexDirection:"column",alignItems:"center",cursor:"pointer"},onClick:function(){var t;null==i||null===(t=i.scrollToPage)||void 0===t||t.call(i,{pageNumber:e.pageIndex+1})}},F("div",{style:{width:e.width,height:e.height,border:"2px solid ".concat(o.currentPage===e.pageIndex+1?"var(--ep-accent-primary)":"var(--ep-border-default)"),borderRadius:"4px",overflow:"hidden",boxShadow:o.currentPage===e.pageIndex+1?"0 0 0 2px var(--ep-interactive-focus-ring)":"none"}},F(bc,{documentId:t,meta:e,style:{width:"100%",height:"100%"}})),F("div",{style:{height:e.labelHeight,display:"flex",alignItems:"center",justifyContent:"center",marginTop:"4px"}},F("span",{className:"text-fg-secondary text-xs"},e.pageIndex+1)))})))}function ay(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:300,n=v(Se(e),2),o=n[0],i=n[1];return Ae(function(){var n=window.setTimeout(function(){return i(e)},t);return function(){return clearTimeout(n)}},[e,t]),o}var sy=function(e){var t=e.label,n=e.checked,o=e.onChange;return F("label",{className:"text-fg-secondary inline-flex cursor-pointer select-none items-center gap-2 text-xs font-medium"},F("input",{type:"checkbox",checked:n,onChange:function(e){return o(e.target.checked)},className:"border-border-default bg-bg-input checked:border-accent checked:bg-accent peer h-4 w-4 shrink-0 appearance-none rounded-[3px] border transition-all"}),F("svg",{viewBox:"0 0 24 24",className:"/* fine-tune centering */ text-fg-on-accent pointer-events-none absolute h-3.5 w-3.5 translate-x-[1px] translate-y-[1px] opacity-0 peer-checked:opacity-100",fill:"none",stroke:"currentColor",strokeWidth:3,strokeLinecap:"round",strokeLinejoin:"round"},F("polyline",{points:"20 6 9 17 4 12"})),t)},ly=function(e){var t=e.hit,n=e.onClick,o=e.active,i=De(null);return Ae(function(){o&&i.current&&i.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[o]),F("button",{ref:i,onClick:n,className:"w-full rounded border p-2 text-left text-sm transition-colors ".concat(o?"border-accent bg-accent-light text-fg-primary":"border-border-subtle bg-bg-surface text-fg-secondary hover:bg-interactive-hover")},F("span",null,t.context.truncatedLeft&&"… ",t.context.before,F("span",{className:"text-accent font-bold"},t.context.match),t.context.after,t.context.truncatedRight&&" …"))};function cy(e){var t=e.documentId;e.onClose;var n=(e=>{const{provides:t}=js(),[n,o]=Se(Ts),i=Re(()=>null==t?void 0:t.forDocument(e),[t,e]);return Ae(()=>{if(i)return o(i.getState()),i.onStateChange(e=>o(e));o(Ts)},[i]),{state:n,provides:i??null}})(t),o=n.state,i=n.provides,r=Mi().provides,a=ja(t).translate,s=De(null),l=v(Se(""),2),c=l[0],d=l[1];Ae(function(){},[]),Ae(function(){o.query&&!c&&d(o.query)},[o.query]),Ae(function(){void 0!==o.activeResultIndex&&o.activeResultIndex>=0&&m(o.activeResultIndex)},[o.activeResultIndex]);var u=ay(c,300);Ae(function(){u!==o.query&&(null==i||i.searchAllPages(u))},[u,i,o.query]);var h=function(e,t){t?null==i||i.setFlags([].concat(y(o.flags),[e])):null==i||i.setFlags(o.flags.filter(function(t){return t!==e}))},m=function(e){var n,i=o.results[e];if(i){var a=i.rects.reduce(function(e,t){return{x:Math.min(e.x,t.origin.x),y:Math.min(e.y,t.origin.y)}},{x:1/0,y:1/0});null==r||null===(n=r.forDocument(t))||void 0===n||n.scrollToPage({pageNumber:i.pageIndex+1,pageCoordinates:a,alignX:50,alignY:25})}},g=function(e){var t={};return e.forEach(function(e,n){t[e.pageIndex]||(t[e.pageIndex]=[]),t[e.pageIndex].push({hit:e,index:n})}),t}(o.results);return F("div",{className:"bg-bg-surface flex h-full flex-col"},F("div",{className:"p-4"},F("div",{className:"relative"},F("div",{className:"pointer-events-none absolute inset-y-0 left-0 flex items-center pl-2"},F(Yp,{className:"text-fg-muted h-4 w-4"})),F("input",{ref:s,type:"text",placeholder:a("search.placeholder"),value:c,onInput:function(e){var t=e.target;d(t.value)},className:"border-border-default bg-bg-input focus:border-accent focus:ring-accent w-full rounded-md border py-1 pl-8 pr-9 text-base focus:outline-none focus:ring-1"}),c&&F("div",{className:"absolute inset-y-0 right-0 flex cursor-pointer items-center pr-3",onClick:function(){d(""),s.current&&s.current.focus()}},F(Xp,{className:"text-fg-muted hover:text-fg-secondary h-4 w-4"}))),F("div",{className:"mt-3 flex flex-col gap-2"},F(sy,{label:a("search.caseSensitive"),checked:o.flags.includes(Kt.MatchCase),onChange:function(e){return h(Kt.MatchCase,e)}}),F(sy,{label:a("search.wholeWord"),checked:o.flags.includes(Kt.MatchWholeWord),onChange:function(e){return h(Kt.MatchWholeWord,e)}})),F("hr",{className:"border-border-subtle mb-2 mt-5"}),o.active&&F("div",{className:"flex h-[32px] flex-row items-center justify-between"},F("div",{className:"text-fg-muted text-xs"},a("search.resultsFound",{params:{count:o.total}})),o.total>1&&F("div",{className:"flex flex-row"},F(df,{onClick:function(){null==i||i.previousResult()}},F(Kp,{className:"h-4 w-4"})),F(df,{onClick:function(){null==i||i.nextResult()}},F(Vp,{className:"h-4 w-4"}))))),F("div",{className:"flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-4"},Object.entries(g).map(function(e){var t=v(e,2),n=t[0],r=t[1];return F("div",{key:n,className:"mt-2 first:mt-0"},F("div",{className:"bg-bg-surface/80 text-fg-muted py-2 text-xs backdrop-blur"},a("search.page",{params:{page:Number(n)+1}})),F("div",{className:"flex flex-col gap-2"},r.map(function(e){var t=e.hit,n=e.index;return F(ly,{key:n,hit:t,active:n===o.activeResultIndex,onClick:function(){null==i||i.goToResult(n)}})})))}),F("div",null)))}function dy(e){var t=e.documentId,n=_o(cm.id).provides,o=Mi().provides,i=ja(t).translate,r=Oo(t),a=v(Se([]),2),s=a[0],l=a[1],c=v(Se(new Set),2),d=c[0],u=c[1],h=v(Se(!0),2),m=h[0],g=h[1];Ae(function(){if(n&&null!=r&&r.document){g(!0);var e=n.getBookmarks();return e.wait(function(e){var t=e.bookmarks;l(t);var n=t.map(function(e,t){return"bookmark-".concat(t)});u(new Set(n)),g(!1)},function(){g(!1)}),function(){e.abort({code:Qt.Cancelled,message:"Bookmark task cancelled"})}}},[n,null==r?void 0:r.document]);var p=function(e,t){var n,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,a="bookmark-".concat(t),s=e.children&&e.children.length>0,l=d.has(a);return F("div",{key:a,className:"select-none"},F("div",{className:"hover:bg-interactive-hover flex cursor-pointer items-center gap-1 px-2 py-1",style:{paddingLeft:"".concat(16*i+8,"px")},onClick:function(){return function(e){if(o&&e.target){var t;if("action"===e.target.type){var n=e.target.action;if(n.type===Et.Goto||n.type===Et.RemoteGoto)t=n.destination;else if(n.type===Et.URI)return void window.open(n.uri,"_blank")}else"destination"===e.target.type&&(t=e.target.destination);if(t)if(t.zoom.mode===Mt.XYZ){var i,a=null==r||null===(i=r.document)||void 0===i?void 0:i.pages.find(function(e){return e.index===t.pageIndex});if(!a)return;o.scrollToPage({pageNumber:t.pageIndex+1,pageCoordinates:t.zoom.params?{x:t.zoom.params.x,y:a.size.height-t.zoom.params.y}:void 0,behavior:"smooth"})}else o.scrollToPage({pageNumber:t.pageIndex+1,behavior:"smooth"})}}(e)}},s&&F("button",{onClick:function(e){e.stopPropagation(),function(e){u(function(t){var n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}(a)},className:"flex h-4 w-4 items-center justify-center"},F(l?Zp:Vp,{className:"h-3 w-3"})),!s&&F("div",{className:"w-4"}),F("span",{className:"text-fg-secondary text-sm"},e.title)),s&&l&&F("div",null,null===(n=e.children)||void 0===n?void 0:n.map(function(e,t){return p(e,t,i+1)})))};return null==r||!r.document||m?F("div",{className:"text-fg-secondary flex h-full flex-col gap-3 p-4 text-sm"},F("div",{className:"text-fg-primary font-medium"},i("outline.title")),F("p",null,i("outline.loading"))):0===s.length?F("div",{className:"flex h-full items-center justify-center p-6"},F("div",{className:"text-fg-muted text-center"},F("div",{className:"text-sm"},i("outline.noOutline")),F("div",{className:"mt-1 text-xs"},i("outline.noBookmarks")))):F("div",{className:"bg-bg-surface flex h-full flex-col"},F("div",{className:"flex-1 overflow-y-auto"},F("div",{className:"outline-tree"},s.map(function(e,t){return p(e,t)}))))}function uy(e){var t=e.size,n=void 0===t?"md":t,o=e.text,i=e.className,r={sm:"w-6 h-6",md:"w-10 h-10",lg:"w-16 h-16"};return F("div",{className:"flex flex-col items-center justify-center gap-3 ".concat(void 0===i?"":i)},F("div",{className:"relative"},F("div",{className:"".concat(r[n]," border-border-default animate-spin rounded-full border-4")}),F("div",{className:"".concat(r[n]," border-r-accent border-t-accent absolute left-0 top-0 animate-spin rounded-full border-4 border-transparent")})),o&&F("p",{className:"".concat({sm:"text-sm",md:"text-base",lg:"text-lg"}[n]," text-fg-secondary animate-pulse font-medium")},o))}function hy(e){var t=e.size,n=void 0===t?"md":t,o=e.className,i=void 0===o?"":o;return F("div",{className:"".concat({sm:"w-4 h-4 border-2",md:"w-6 h-6 border-2",lg:"w-8 h-8 border-3"}[n]," border-border-default border-t-accent animate-spin rounded-full ").concat(i)})}var my,gy=function(e){var t=e.documentId,n=ch().provides,o=v(Se({show:!1,mode:null,isAnimating:!1}),2),i=o[0],r=o[1],a=ja(t).translate;Ae(function(){if(n)return n.onModeChange(function(e){var t=e.activeMode;if("marqueeZoom"===t||"marqueeCapture"===t){r({show:!0,mode:t,isAnimating:!0});var n=setTimeout(function(){r(function(e){return h(h({},e),{},{show:!1})})},3e3);return function(){return clearTimeout(n)}}r({show:!1,mode:null,isAnimating:!1})})},[n]);if(!i.show&&!i.isAnimating)return null;var s="marqueeZoom"===i.mode?a("zoom.dragTip"):a("capture.dragTip"),l="marqueeZoom"===i.mode?"rgba(33,150,243,0.8)":"rgba(76,175,80,0.8)";return F("div",{className:"hint-overlay ".concat(i.show?"hint-show":"hint-hide"),onAnimationEnd:function(){i.show||r(function(e){return h(h({},e),{},{isAnimating:!1,mode:null})})},style:{position:"absolute",top:0,left:0,right:0,bottom:0,pointerEvents:"none",zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"20px"}},F("div",{className:"hint-text",style:{background:"rgba(0, 0, 0, 0.8)",color:"white",padding:"12px 20px",borderRadius:"8px",fontSize:"14px",fontWeight:"500",textAlign:"center",maxWidth:"250px"}},s),F("div",{className:"drag-demo",style:{position:"relative",width:"150px",height:"100px"}},F("div",{style:{position:"absolute",top:"20px",left:"20px",width:"110px",height:"60px",border:"2px dashed ".concat(l),borderRadius:"4px",opacity:.6}}),F("div",{className:"animated-rect",style:{position:"absolute",top:"20px",left:"20px",border:"2px solid ".concat(l),backgroundColor:"".concat(l.replace("0.8","0.15")),borderRadius:"4px"}}),F("div",{className:"cursor-demo",style:{position:"absolute",width:"20px",height:"20px"}},F("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg"},F("path",{d:"M3.5 2.5L16.5 10L10 11.5L7.5 16.5L3.5 2.5Z",fill:"rgba(0,0,0,0.3)",transform:"translate(1,1)"}),F("path",{d:"M3 2L16 10L10 11.5L7.5 16L3 2Z",fill:"white",stroke:"black",strokeWidth:"1"}),F("path",{d:"M4 3.5L13.5 9.5L9.5 10.5L7.5 14L4 3.5Z",fill:"rgba(255,255,255,0.8)"})))),F("style",{jsx:!0},"\n .hint-overlay {\n animation-duration: 0.3s;\n animation-fill-mode: both;\n }\n\n .hint-show {\n animation-name: hintFadeIn;\n }\n\n .hint-hide {\n animation-name: hintFadeOut;\n }\n\n @keyframes hintFadeIn {\n from {\n opacity: 0;\n transform: translateY(10px);\n }\n to {\n opacity: 1;\n transform: translateY(0);\n }\n }\n\n @keyframes hintFadeOut {\n from {\n opacity: 1;\n transform: translateY(0);\n }\n to {\n opacity: 0;\n transform: translateY(-10px);\n }\n }\n\n .animated-rect {\n animation: rectGrow 2s ease-in-out infinite;\n }\n\n @keyframes rectGrow {\n 0% {\n width: 0;\n height: 0;\n }\n 50% {\n width: 110px;\n height: 60px;\n }\n 100% {\n width: 110px;\n height: 60px;\n opacity: 0.7;\n }\n }\n\n .cursor-demo {\n animation: cursorMove 2s ease-in-out infinite;\n }\n\n @keyframes cursorMove {\n 0% {\n top: 20px;\n left: 20px;\n }\n 50% {\n top: 50px;\n left: 80px;\n }\n 100% {\n top: 80px;\n left: 130px;\n }\n }\n\n .hint-text {\n animation: textPulse 0.6s ease-in-out;\n }\n\n @keyframes textPulse {\n 0% {\n transform: scale(0.9);\n }\n 50% {\n transform: scale(1.05);\n }\n 100% {\n transform: scale(1);\n }\n }\n "))},py=function(e){var t=e.placeholder,n=e.onSubmit,o=e.inputRef,i=e.isFocused,r=v(Se(""),2),a=r[0],s=r[1];return F("form",{className:"border-border-subtle mt-4 flex items-end space-x-2 border-t pt-4",onClick:function(e){return e.stopPropagation()},onSubmit:function(e){null==e||e.preventDefault(),a.trim()&&(n(a),s(""))}},F("input",{ref:o,type:"text",placeholder:t,value:a,onInput:function(e){return s(e.currentTarget.value)},className:"bg-bg-input text-fg-primary placeholder-fg-muted w-full rounded-lg border px-3 py-1 text-base transition-colors focus:border-transparent focus:outline-none focus:ring-2 ".concat(i?"border-accent focus:ring-accent":"border-border-default focus:ring-accent")}),F("button",{type:"submit",disabled:!a.trim(),className:"bg-accent text-fg-on-accent hover:bg-accent-hover disabled:bg-interactive-disabled rounded-lg p-2 transition-colors disabled:cursor-not-allowed"},F("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},F("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 19l9 2-9-18-9 18 9-2zm0 0v-8"}))))},fy=["bg-red-500","bg-blue-500","bg-green-500","bg-yellow-500","bg-purple-500","bg-pink-500","bg-indigo-500","bg-teal-500"],vy=function(e){if(!e)return fy[0];var t=e.length>0?e.charCodeAt(0)%fy.length:0;return fy[t]},yy=function(e){var t=e.name,n=e.className,o=void 0===n?"":n;return F("div",{className:"flex h-8 w-8 items-center justify-center rounded-full text-sm font-medium text-white ".concat(vy(t)," ").concat(o)},function(e){return e?e.split(" ").map(function(e){return e[0]}).join("").toUpperCase().slice(0,2):"G"}(t))},by=function(e){var t,n,o=e.onEdit,i=e.onDelete,r=e.onClose,a=e.documentId,s=De(null),l=ja(a).translate;Ae(function(){var e=function(e){t.current&&!t.current.contains(e.target)&&n()};return document.addEventListener("click",e),function(){document.removeEventListener("click",e)}},[t=s,n=r]);return F("div",{ref:s,className:"bg-bg-elevated ring-border-default absolute right-0 top-6 z-10 w-32 rounded-md shadow-lg ring-1"},F("div",{className:"py-1"},F("button",{onClick:function(e){e.preventDefault(),e.stopPropagation(),o(),r()},className:"text-fg-secondary hover:bg-interactive-hover block w-full px-4 py-2 text-left text-sm"},l("comments.edit")),F("button",{onClick:function(e){e.preventDefault(),e.stopPropagation(),i(),r()},className:"text-state-error hover:bg-interactive-hover block w-full px-4 py-2 text-left text-sm"},l("comments.delete"))))},wy=function(e){var t=e.initialText,n=e.onSave,o=e.onCancel,i=e.autoFocus,r=void 0!==i&&i,a=e.documentId,s=v(Se(t),2),l=s[0],c=s[1],d=De(null),u=ja(a).translate;Ae(function(){r&&d.current&&(d.current.focus(),d.current.setSelectionRange(l.length,l.length))},[r,l.length]);return F("div",{className:"flex-1 space-y-2"},F("textarea",{ref:d,value:l,onInput:function(e){return c(e.currentTarget.value)},className:"border-border-default bg-bg-input text-fg-primary focus:border-accent focus:ring-accent w-full rounded-md border px-3 py-2 text-base focus:outline-none focus:ring-1",rows:3}),F("div",{className:"flex flex-wrap gap-2"},F("button",{onClick:function(e){e.stopPropagation(),n(l)},className:"bg-accent text-fg-on-accent hover:bg-accent-hover whitespace-nowrap rounded-md px-3 py-1 text-sm"},u("comments.save")),F("button",{onClick:function(e){e.stopPropagation(),o()},className:"bg-interactive-hover text-fg-secondary hover:bg-border-default whitespace-nowrap rounded-md px-3 py-1 text-sm"},u("comments.cancel"))))},xy=function(e){if(!e)return"(no date)";try{return(e instanceof Date?e:new Date(e)).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}catch(t){return"string"==typeof e?e:"(no date)"}},Cy=function(e){var t=e.annotation,n=e.onSave,o=e.onDelete,i=e.isReply,r=void 0!==i&&i,a=e.documentId,s=e.isReadOnly,l=void 0!==s&&s,c=v(Se(!1),2),d=c[0],u=c[1],h=v(Se(!1),2),m=h[0],g=h[1],p=t.author||"Guest";return m?F("div",{className:"flex w-full items-start space-x-3",onClick:function(e){return e.stopPropagation()}},r&&F(yy,{name:p,className:"h-8 w-8"}),F(wy,{initialText:t.contents||"",onSave:function(e){n(e),g(!1)},onCancel:function(){g(!1)},autoFocus:!0,documentId:a})):F("div",{className:"flex items-start space-x-3"},r&&F(yy,{name:p,className:"h-8 w-8"}),F("div",{className:"min-w-0 flex-1"},r&&F("div",{className:"flex items-center justify-between"},F("div",{className:"leading-none"},F("h5",{className:"text-fg-primary text-sm font-medium"},p),F("span",{className:"text-fg-muted text-xs"},xy(t.modified||t.created))),!l&&F("div",{className:"relative"},F("button",{onClick:function(e){e.stopPropagation(),u(!0)},className:"text-fg-muted hover:bg-interactive-hover rounded-md p-1"},F("svg",{className:"h-4 w-4",fill:"currentColor",viewBox:"0 0 20 20"},F("path",{d:"M6 10a2 2 0 11-4 0 2 2 0 014 0zM12 10a2 2 0 11-4 0 2 2 0 014 0zM16 12a2 2 0 100-4 2 2 0 000 4z"}))),d&&F(by,{onEdit:function(){return g(!0)},onDelete:o,onClose:function(){return u(!1)},documentId:a}))),F("p",{className:"text-fg-primary mt-2 text-sm"},t.contents)))},Iy=(s(s(s(s(s(s(s(s(s(s(my={},_t.HIGHLIGHT,{label:"Highlight",labelKey:"annotation.highlight",icon:"highlight",iconProps:function(e){return{primaryColor:e.strokeColor||"#ffff00"}}}),_t.CIRCLE,{label:"Circle",labelKey:"annotation.circle",icon:"circle",iconProps:function(e){return{primaryColor:e.strokeColor||"#000000",secondaryColor:e.color}}}),_t.SQUARE,{label:"Square",labelKey:"annotation.square",icon:"square",iconProps:function(e){return{primaryColor:e.strokeColor||"#000000",secondaryColor:e.color}}}),_t.LINE,{label:"Line",labelKey:"annotation.line",icon:"line",iconProps:function(e){return{primaryColor:e.strokeColor||"#000000"}}}),_t.UNDERLINE,{label:"Underline",labelKey:"annotation.underline",icon:"underline",iconProps:function(e){return{primaryColor:e.strokeColor||"#000000"}}}),_t.SQUIGGLY,{label:"Squiggly",labelKey:"annotation.squiggly",icon:"squiggly",iconProps:function(e){return{primaryColor:e.strokeColor||"#000000"}}}),_t.STRIKEOUT,{label:"Strikethrough",labelKey:"annotation.strikeout",icon:"strikethrough",iconProps:function(e){return{primaryColor:e.strokeColor||"#000000"}}}),_t.INK,{label:"Ink",labelKey:"annotation.ink",icon:"pencilMarker",iconProps:function(e){return{primaryColor:e.strokeColor||"#000000"}}}),_t.FREETEXT,{label:"Text",labelKey:"annotation.freeText",icon:"text",iconProps:function(e){return{primaryColor:e.fontColor||"#000000"}}}),_t.POLYGON,{label:"Polygon",labelKey:"annotation.polygon",icon:"polygon",iconProps:function(e){return{primaryColor:e.strokeColor||"#000000",secondaryColor:e.color}}}),s(s(s(my,_t.POLYLINE,{label:"Polyline",labelKey:"annotation.polyline",icon:"zigzag",iconProps:function(e){return{primaryColor:e.strokeColor||"#000000"}}}),_t.STAMP,{label:"Stamp",labelKey:"annotation.stamp",icon:"deviceFloppy",iconProps:function(){return{primaryColor:"#dc2626"}}}),_t.REDACT,{label:"Redact",labelKey:"annotation.redact",icon:"redact",iconProps:function(e){return{primaryColor:e.strokeColor||"#000000",secondaryColor:e.color||"#000000"}}})),ky=function(e){var t=e.text,n=e.maxWords,o=void 0===n?16:n,i=e.className,r=void 0===i?"":i,a=e.documentId,s=v(Se(!1),2),l=s[0],c=s[1],d=ja(a).translate,u=t.split(" ");return u.length>o?F("div",{className:r},l?t:u.slice(0,o).join(" ")+"..."," ",F("button",{onClick:function(e){e.stopPropagation(),c(!l)},className:"text-accent hover:text-accent-hover text-sm font-medium focus:outline-none"},d(l?"comments.showLess":"comments.showMore"))):F("div",{className:r},t)},Sy=function(e){var t=e.annotation,n=e.config,o=e.className,i=void 0===o?"":o,r=e.title,a=n.iconProps(t.object);return F("div",{className:"bg-bg-surface-alt flex items-center justify-center rounded-full ".concat(i),title:r},F(lf,h({icon:n.icon},a)))},My=function(e){var t,n=e.entry,o=e.isSelected,i=e.onSelect,r=e.onUpdate,a=e.onDelete,s=e.onReply,l=e.documentId,c=e.isReadOnly,d=void 0!==c&&c,u=n.annotation,h=n.replies,m=v(Se(!1),2),g=m[0],p=m[1],f=v(Se(!1),2),y=f[0],b=f[1],w=ja(l).translate,x=function(e){return ld(e)?Iy[e.object.type]:null}(u),C=!!u.object.contents,I=h.length>0,k=!C&&!I,S=De(null),M=De(!1),A=u.object.author||"Guest";if(Ae(function(){var e;o&&!M.current&&(null===(e=S.current)||void 0===e||e.focus({preventScroll:!0}));M.current=o},[o]),!x)return null;return F("div",{onClick:i,className:"bg-bg-surface cursor-pointer rounded-lg border shadow-sm transition-all hover:shadow-md ".concat(o?"border-accent ring-interactive-focus-ring ring-2":"border-border-subtle")},F("div",{className:"p-4"},F("div",{className:"flex items-start space-x-3"},F(Sy,{annotation:u,config:x,title:w(x.labelKey,{fallback:x.label}),className:"h-8 w-8"}),F("div",{className:"min-w-0 flex-1"},F("div",{className:"flex items-center justify-between"},F("div",{className:"leading-none"},F("h4",{className:"text-fg-primary text-sm font-medium"},A),F("span",{className:"text-fg-disabled text-xs"},xy(u.object.modified||u.object.created))),!d&&F("div",{className:"relative"},F("button",{onClick:function(e){e.stopPropagation(),p(!0)},className:"text-fg-disabled hover:bg-interactive-hover hover:text-fg-secondary rounded-md p-1"},F("svg",{className:"h-4 w-4",fill:"currentColor",viewBox:"0 0 20 20"},F("path",{d:"M6 10a2 2 0 11-4 0 2 2 0 014 0zM12 10a2 2 0 11-4 0 2 2 0 014 0zM16 12a2 2 0 100-4 2 2 0 000 4z"}))),g&&F(by,{onEdit:function(){return b(!0)},onDelete:function(){return a(u)},onClose:function(){return p(!1)},documentId:l}))),(null===(t=u.object.custom)||void 0===t?void 0:t.text)&&F(ky,{text:u.object.custom.text,maxWords:14,className:"text-fg-muted mt-2 text-sm",documentId:l}),y?F("div",{className:"mt-2"},F(wy,{initialText:u.object.contents||"",onSave:function(e){r(u.object.id,e),b(!1)},onCancel:function(){b(!1)},autoFocus:!0,documentId:l})):C?F("p",{className:"text-fg-primary mt-2 text-sm"},u.object.contents):null)),I&&F("div",{className:"border-border-subtle mt-4 space-y-4 border-t pt-4"},h.map(function(e){return F(Cy,{key:e.object.id,annotation:e.object,onSave:function(t){return r(e.object.id,t)},onDelete:function(){return a(e)},isReply:!0,documentId:l,isReadOnly:d})})),!y&&!d&&F(py,{inputRef:S,isFocused:o,placeholder:w(k?"comments.addComment":"comments.addReply"),onSubmit:function(e){k?r(u.object.id,e):s(u.object.id,e)}})))},Ay=function(e){var t=e.documentId,n=ja(t).translate;return F("div",{class:"text-fg-muted flex flex-col items-center gap-2 p-4"},F(lf,{icon:"comment",className:"h-18 w-18 text-fg-muted"}),F("div",{className:"text-fg-muted max-w-[150px] text-center text-sm"},n("comments.emptyState")))},Py=function(e){var t=e.documentId,n=xh().provides,o=Ch(t).state,i=Mi().provides,r=ja(t).translate,s=Uo(t).canModifyAnnotations,l=De({}),c=De(null),d=!s,u=o.selectedUid?hd(o,o.selectedUid):null,h=(e=>{const t={};for(const n of Object.values(e.pages))for(const o of n){const n=e.byUid[o];if(n&&ad(n)){const e=n.object.inReplyToId;e&&(t[e]||(t[e]=[])).push(n)}}const n={};for(const[o,i]of Object.entries(e.pages)){const r=Number(o),a=[];for(const n of i){const o=e.byUid[n];o&&ld(o)&&a.push({page:r,annotation:o,replies:t[o.object.id]??[]})}a.length>0&&(n[r]=a)}return n})(o);Ae(function(){if(u&&c.current){var e=l.current[u.object.id];if(e&&c.current){var t=c.current,n=t.getBoundingClientRect(),o=e.getBoundingClientRect(),i=o.top-n.top+t.scrollTop-t.clientHeight/2+o.height/2;t.scrollTo({top:i,behavior:"smooth"})}}},[u]);var m=function(e,t){var o=v(e);o&&(null==n||n.updateAnnotation(o.object.pageIndex,e,{contents:t,modified:new Date}))},g=function(e){null==n||n.deleteAnnotation(e.object.pageIndex,e.object.id)},p=function(e,t){var o=v(e);o&&(null==n||n.createAnnotation(o.object.pageIndex,{id:zn(),rect:{origin:{x:o.object.rect.origin.x,y:o.object.rect.origin.y},size:{width:24,height:24}},pageIndex:o.object.pageIndex,created:new Date,modified:new Date,type:_t.TEXT,contents:t,inReplyToId:o.object.id,flags:["noRotate","noZoom","print"],icon:Ot.Comment}))},f=Object.keys(h).map(Number).sort(function(e,t){return e-t}),v=function(e){var t,n=a(f);try{for(n.s();!(t=n.n()).done;){var o,i=t.value,r=a(h[i]);try{for(r.s();!(o=r.n()).done;){var s=o.value;if(s.annotation.object.id===e)return s.annotation;var l=s.replies.find(function(t){return t.object.id===e});if(l)return l}}catch(e){r.e(e)}finally{r.f()}}}catch(e){n.e(e)}finally{n.f()}};return 0===f.length?F(Ay,{documentId:t}):F("div",{ref:c,className:"h-full overflow-y-auto"},F("div",{className:"space-y-6 p-3"},f.map(function(e){return F("div",{key:e,className:"space-y-3"},F("div",{className:"bg-bg-surface sticky top-0 z-10 px-1"},F("div",{className:"border-border-subtle border-b py-2"},F("h3",{className:"text-md text-fg-primary font-semibold"},r("comments.page",{params:{page:e+1}})),F("p",{className:"text-fg-muted text-sm"},1===h[e].length?r("comments.commentCount",{params:{count:1}}):r("comments.commentCountPlural",{params:{count:h[e].length}})))),F("div",{className:"space-y-3 px-1"},h[e].map(function(e){return F("div",{key:e.annotation.object.id,ref:function(t){t&&(l.current[e.annotation.object.id]=t)}},F(My,{entry:e,isSelected:(null==u?void 0:u.object.id)===e.annotation.object.id,onSelect:function(){return t=e.annotation,null==n||n.selectAnnotation(t.object.pageIndex,t.object.id),void(null==i||i.scrollToPage({pageNumber:t.object.pageIndex+1,pageCoordinates:{x:t.object.rect.origin.x,y:t.object.rect.origin.y},alignX:50,alignY:25,behavior:"smooth"}));var t},onUpdate:m,onDelete:g,onReply:p,documentId:t,isReadOnly:d}))})))})))};function Dy(e){var t=e.documentId,n=(e=>{const{provides:t}=Ja(),[n,o]=Se(Ka);return Ae(()=>{if(!t)return;const n=t.forDocument(e);return o(n.getState()),n.onStateChange(e=>{o(e)})},[t,e]),{state:n,provides:(null==t?void 0:t.forDocument(e))??null}})(t),o=n.state,i=n.provides,r=v(Se(""),2),a=r[0],s=r[1];if(!i)return null;var l=Math.round(100*o.currentZoomLevel);Ae(function(){s(l.toString())},[l]);return F("div",{className:"relative"},F("div",{className:"bg-interactive-hover flex items-center rounded"},F("form",{onSubmit:function(e){e.preventDefault();var t=e.target,n=new FormData(t),o=parseFloat(n.get("zoom")||a);!isNaN(o)&&o>0&&i.requestZoom(o/100)},className:"block"},F("input",{name:"zoom",type:"text",inputMode:"numeric",pattern:"\\d*",className:"h-6 w-8 border-0 bg-transparent p-0 text-right text-sm outline-none focus:outline-none","aria-label":"Set zoom",autoFocus:!1,value:a,onInput:function(e){var t=e.target.value.replace(/[^0-9]/g,"");s(t)},onBlur:function(){(!a||parseFloat(a)<=0)&&s(l.toString())}}),F("span",{className:"text-sm"},"%")),F(Lv,{commandId:"zoom:toggle-menu",documentId:t,itemId:"zoom-menu-button"}),F(Lv,{commandId:"zoom:out",documentId:t}),F(Lv,{commandId:"zoom:in",documentId:t})))}var Ry,zy=function(e){var t=e.documentId,n=ja(t).translate;return F("div",{class:"text-fg-muted flex flex-col items-center gap-2 p-4"},F(lf,{icon:"palette",className:"h-18 w-18 text-fg-muted"}),F("div",{className:"text-fg-muted max-w-[150px] text-center text-sm"},n("annotation.selectAnnotation")))},Ty={color:{key:"color",type:"colorWithTransparent",labelKey:"annotation.fillColor"},strokeColor:{key:"strokeColor",type:"colorWithTransparent",labelKey:"annotation.strokeColor"},opacity:{key:"opacity",type:"opacity",labelKey:"annotation.opacity",min:.1,max:1,step:.05,debounce:!0},strokeWidth:{key:"strokeWidth",type:"slider",labelKey:"annotation.strokeWidth",min:1,max:30,step:1,unit:"px",debounce:!0},strokeStyle:{key:"strokeStyle",type:"strokeStyle",labelKey:"annotation.borderStyle"},lineEndings:{key:"lineEndings",type:"lineEndings",labelKey:"annotation.lineEndings"},fontFamily:{key:"fontFamily",type:"fontFamily",labelKey:"annotation.fontFamily"},fontSize:{key:"fontSize",type:"fontSize",labelKey:"annotation.fontSize"},fontColor:{key:"fontColor",type:"fontColor",labelKey:"annotation.fontColor"},textAlign:{key:"textAlign",type:"textAlign",labelKey:"annotation.textAlign"},verticalAlign:{key:"verticalAlign",type:"verticalAlign",labelKey:"annotation.verticalAlign"},blendMode:{key:"blendMode",type:"blendMode",labelKey:"annotation.blendMode"},rotation:{key:"rotation",type:"rotation",labelKey:"annotation.rotation",debounce:!0,editOnly:!0},overlayText:{key:"overlayText",type:"text",labelKey:"annotation.overlayText",placeholderKey:"annotation.overlayTextPlaceholder"}},Ey=(s(s(s(s(s(s(s(s(s(s(Ry={},_t.INK,["strokeColor","opacity","strokeWidth","rotation"]),_t.CIRCLE,["color","opacity","strokeColor","strokeStyle","strokeWidth","rotation"]),_t.SQUARE,["color","opacity","strokeColor","strokeStyle","strokeWidth","rotation"]),_t.POLYGON,["strokeColor","opacity","strokeStyle","strokeWidth","color","rotation"]),_t.LINE,["strokeColor","opacity","strokeStyle","strokeWidth","lineEndings","color","rotation"]),_t.POLYLINE,["strokeColor","opacity","strokeStyle","strokeWidth","lineEndings","color","rotation"]),_t.HIGHLIGHT,["strokeColor","opacity","blendMode"]),_t.UNDERLINE,["strokeColor","opacity","blendMode"]),_t.STRIKEOUT,["strokeColor","opacity","blendMode"]),_t.SQUIGGLY,["strokeColor","opacity","blendMode"]),s(s(s(Ry,_t.STAMP,["rotation"]),_t.FREETEXT,["fontFamily","fontSize","fontColor","textAlign","verticalAlign","opacity","color","rotation"]),_t.REDACT,["strokeColor","color","opacity"]));var _y,Ny=["position"],Oy=function(){var e=v(Se(!1),2),t=e[0],n=e[1],o=De(null),i=De(null);return Ae(function(){if(t){var e=function(e){o.current&&!o.current.contains(e.target)&&n(!1)};return document.addEventListener("click",e),function(){return document.removeEventListener("click",e)}}},[t]),Ae(function(){t&&i.current&&i.current.scrollIntoView({block:"center",inline:"start"})},[t]),{open:t,setOpen:n,rootRef:o,selectedItemRef:i}},Ly=function(e){var t=e.value,n=e.onChange,o=e.options,i=e.getOptionKey,r=e.renderValue,a=e.renderOption,s=e.triggerClass,l=void 0===s?"px-3 py-2":s,c=Oy(),d=c.open,u=c.setOpen,h=c.rootRef,m=c.selectedItemRef;return F("div",{ref:h,class:"relative inline-block w-full"},F("button",{type:"button",class:"border-border-default bg-bg-input flex w-full items-center justify-between gap-2 rounded border ".concat(l),onClick:function(){return u(function(e){return!e})}},r(t),F("svg",{class:"text-fg-secondary h-4 w-4",viewBox:"0 0 20 20",fill:"currentColor"},F("path",{fillRule:"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 10.94l3.71-3.71a.75.75 0 111.06 1.06l-4.24 4.24a.75.75 0 01-1.06 0L5.21 8.29a.75.75 0 01.02-1.08z",clipRule:"evenodd"}))),d&&F("div",{class:"border-border-default bg-bg-elevated absolute z-10 mt-1 max-h-60 w-full overflow-y-auto rounded border p-1 shadow-lg"},o.map(function(e){var o=i(e)===i(t);return F("button",{ref:o?m:null,key:i(e),class:"hover:bg-interactive-hover block w-full rounded text-left ".concat(o?"bg-interactive-hover":""),onClick:function(){n(e),u(!1)}},a(e,o))})))},$y=function(e){var t=e.children,n=e.className;return F("label",{class:"text-fg-primary mb-2 block text-sm font-medium ".concat(void 0===n?"":n)},t)},jy=function(e){var t=e.children,n=e.className;return F("span",{class:"text-fg-muted text-xs ".concat(void 0===n?"":n)},t)},Fy=function(e){var t=e.children,n=e.className;return F("section",{class:"mb-6 ".concat(void 0===n?"":n)},t)},Uy=function(e){var t=e.value,n=e.min,o=void 0===n?0:n,i=e.max,r=void 0===i?1:i,a=e.step,s=void 0===a?.1:a,l=e.onChange;return F("input",{type:"range",class:"range-sm bg-border-subtle mb-2 h-1 w-full cursor-pointer appearance-none rounded-lg",value:t,min:o,max:r,step:s,onInput:function(e){return l(parseFloat(e.target.value))}})},Hy=function(e){var t=e.color,n=e.active,o=e.onSelect,i=function(e){return"transparent"===e||/^rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*0\s*\)$/i.test(e)||/^#([0-9a-f]{8})$/i.test(e)&&"00"===e.slice(-2).toLowerCase()||/^#([0-9a-f]{4})$/i.test(e)&&"0"===e.slice(-1).toLowerCase()}(t)?{backgroundColor:"#fff",backgroundImage:"linear-gradient(45deg, transparent 40%, red 40%, red 60%, transparent 60%)",backgroundSize:"100% 100%"}:{backgroundColor:t};return F("button",{title:t,class:"border-border-strong h-5 w-5 rounded-full border ".concat(n?"outline-accent outline outline-2 outline-offset-2":""),style:i,onClick:function(){return o(t)}})},By=[{id:Ut.SOLID},{id:Ut.DASHED,dash:[6,2]},{id:Ut.DASHED,dash:[8,4]},{id:Ut.DASHED,dash:[3,3]},{id:Ut.DASHED,dash:[1,2]},{id:Ut.DASHED,dash:[4,2,1,2]},{id:Ut.DASHED,dash:[8,4,1,4]}],Wy=function(e){return F("svg",{width:"80",height:"8",viewBox:"0 0 80 8"},F("line",{x1:"0",y1:"4",x2:"80",y2:"4",style:{strokeDasharray:null==e?void 0:e.join(" "),stroke:"currentColor",strokeWidth:"2"}}))},qy=function(e){return F(Ly,h(h({},e),{},{options:By,getOptionKey:function(e){var t;return e.id+((null===(t=e.dash)||void 0===t?void 0:t.join("-"))||"")},renderValue:function(e){return Wy(e.dash)},renderOption:function(e){return F("div",{class:"px-1 py-2"},Wy(e.dash))}}))},Gy=[Lt.None,Lt.Square,Lt.Circle,Lt.Diamond,Lt.OpenArrow,Lt.ClosedArrow,Lt.ROpenArrow,Lt.RClosedArrow,Lt.Butt,Lt.Slash],Vy=function(e){var t,n=e.ending,o=e.position,i=s(s(s(s(s(s(s(s(s({},Lt.Square,F("path",{d:"M68 -4 L76 -4 L76 4 L68 4 Z"})),Lt.Circle,F("circle",{cx:"72",cy:"0",r:"4"})),Lt.Diamond,F("path",{d:"M72 -5 L77 0 L72 5 L67 0 Z"})),Lt.OpenArrow,F("path",{d:"M67 -5 L77 0 L67 5",fill:"none"})),Lt.ClosedArrow,F("path",{d:"M67 -5 L77 0 L67 5 Z"})),Lt.ROpenArrow,F("path",{d:"M77 -5 L67 0 L77 5",fill:"none"})),Lt.RClosedArrow,F("path",{d:"M77 -5 L67 0 L77 5 Z"})),Lt.Butt,F("path",{d:"M72 -5 L72 5",fill:"none"})),Lt.Slash,F("path",{d:"M67 -5 L77 5",fill:"none"})),r=s(s(s(s(s(s(s(s(s({},Lt.Square,68),Lt.Circle,68),Lt.Diamond,67),Lt.OpenArrow,76),Lt.ClosedArrow,67),Lt.ROpenArrow,67),Lt.RClosedArrow,67),Lt.Butt,72),Lt.Slash,72),a=i[n];return F("svg",{width:"80",height:"20",viewBox:"0 0 80 20",class:"text-fg-primary"},F("g",{transform:"start"===o?"rotate(180 40 10)":""},F("line",{x1:"4",y1:"10",x2:null!==(t=r[n])&&void 0!==t?t:77,y2:"10",stroke:"currentColor","stroke-width":"1.5"}),a&&F("g",{transform:"translate(0, 10)",fill:"currentColor",stroke:"currentColor","stroke-width":"1.5"},a)))},Ky=function(e){var t=e.position,n=m(e,Ny);return F(Ly,h(h({},n),{},{options:Gy,getOptionKey:function(e){return e},triggerClass:"px-3 py-1",renderValue:function(e){return F(Vy,{ending:e,position:t})},renderOption:function(e){return F("div",{class:"px-1 py-1"},F(Vy,{ending:e,position:t}))}}))},Zy=function(e){return F(Ly,h(h({},e),{},{options:Cn,getOptionKey:function(e){return e},triggerClass:"px-2 py-1 text-sm",renderValue:function(e){return F("span",null,In(e))},renderOption:function(e){return F("div",{class:"px-2 py-1"},In(e))}}))},Yy=function(e){var t=e.value,n=e.onChange,o=(t%360+360)%360,i=function(e){n(((o+e)%360+360)%360)};return F("div",{class:"flex items-center gap-1"},F("button",{type:"button",title:"-90°",class:"border-border-default bg-bg-input text-fg-primary hover:bg-interactive-hover flex h-8 w-8 shrink-0 items-center justify-center rounded border",onClick:function(){return i(-90)}},F("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"},F("path",{d:"M1 4v6h6"}),F("path",{d:"M3.51 15a9 9 0 1 0 2.13-9.36L1 10"}))),F("div",{class:"relative flex-1"},F("input",{type:"number",min:"0",max:"359",class:"border-border-default bg-bg-input text-fg-primary h-8 w-full rounded border px-2 pr-6 text-center text-sm",value:o,onInput:function(e){var t=parseInt(e.target.value,10);Number.isFinite(t)&&n((t%360+360)%360)}}),F("span",{class:"text-fg-muted pointer-events-none absolute inset-y-0 right-2 flex items-center text-xs"},"°")),F("button",{type:"button",title:"+90°",class:"border-border-default bg-bg-input text-fg-primary hover:bg-interactive-hover flex h-8 w-8 shrink-0 items-center justify-center rounded border",onClick:function(){return i(90)}},F("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"},F("path",{d:"M23 4v6h-6"}),F("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"}))))},Xy=function(e){var t=e.value,n=e.onChange,o=e.options,i=void 0===o?[8,9,10,11,12,14,16,18,24,36,48,72]:o,r=Oy(),a=r.open,s=r.setOpen,l=r.rootRef,c=r.selectedItemRef;return F("div",{ref:l,class:"relative w-full"},F("input",{type:"number",min:"1",class:"border-border-default bg-bg-input w-full rounded border px-2 py-1 pr-7 text-sm",value:t,onInput:function(e){var t=parseInt(e.target.value,10);Number.isFinite(t)&&t>0&&n(t)},onClick:function(){return s(!0)}}),F("button",{type:"button",class:"absolute inset-y-0 right-1 flex items-center",onClick:function(){return s(function(e){return!e})},tabIndex:-1},F("svg",{class:"text-fg-secondary h-4 w-4",viewBox:"0 0 20 20",fill:"currentColor"},F("path",{"fill-rule":"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 10.94l3.71-3.71a.75.75 0 111.06 1.06l-4.24 4.24a.75.75 0 01-1.06 0L5.21 8.29a.75.75 0 01.02-1.08z","clip-rule":"evenodd"}))),a&&F("div",{class:"border-border-default bg-bg-elevated absolute z-10 mt-1 max-h-48 w-full overflow-y-auto rounded border shadow-lg"},i.map(function(e){var o=e===t;return F("button",{ref:o?c:null,key:e,class:"hover:bg-interactive-hover block w-full px-2 py-1 text-left text-sm ".concat(o?"bg-interactive-hover":""),onClick:function(){n(e),s(!1)}},e)})))};function Qy(e){var t=e.active,n=void 0!==t&&t,o=e.disabled,i=void 0!==o&&o,r=e.onClick,a=e.title,s=e.children,l=e.className,c=void 0===l?"":l;return F("button",{type:"button",title:a,disabled:i,onClick:r,className:"h-9 w-9 rounded border px-2 py-1 text-sm transition-colors ".concat(n?"border-accent bg-accent text-fg-on-accent":"border-border-default bg-bg-input text-fg-primary hover:bg-interactive-hover"," disabled:cursor-not-allowed disabled:opacity-40 ").concat(c)},s)}function Jy(e){switch(e.config.type){case"color":return He(eb,h(h({},e),{},{allowTransparent:!1}));case"colorWithTransparent":return He(eb,h(h({},e),{},{allowTransparent:!0}));case"opacity":return He(tb,h({},e));case"slider":return He(nb,h({},e));case"strokeStyle":return He(ob,h({},e));case"lineEndings":return He(ib,h({},e));case"fontFamily":return He(rb,h({},e));case"fontSize":return He(ab,h({},e));case"fontColor":return He(sb,h({},e));case"textAlign":return He(lb,h({},e));case"verticalAlign":return He(cb,h({},e));case"blendMode":return He(ub,h({},e));case"text":return He(hb,h({},e));case"rotation":return He(mb,h({},e));default:return null}}function eb(e){var t=e.config,n=e.value,o=e.onChange,i=e.colorPresets,r=e.translate,a=e.allowTransparent,s=v(Se(null!=n?n:"#000000"),2),l=s[0],c=s[1];Ae(function(){return c(null!=n?n:"#000000")},[n]);var d=function(e){c(e),o(e)};return He(Fy,{children:[He($y,{className:"mb-3",children:r(t.labelKey)}),He("div",{class:"grid grid-cols-6 gap-x-1 gap-y-4",children:[i.map(function(e){return He(Hy,{color:e,active:e===l,onSelect:d},e)}),a&&He(Hy,{color:"transparent",active:"transparent"===l,onSelect:d})]})]})}function tb(e){var t,n,o,i=e.config,r=e.value,a=e.onChange,s=e.translate,l=v(Se(null!=r?r:1),2),c=l[0],d=l[1];Ae(function(){return d(null!=r?r:1)},[r]);var u=ay(c,300);return Ae(function(){u!==r&&a(u)},[u]),He(Fy,{children:[He($y,{children:s(i.labelKey)}),He(Uy,{value:c,min:null!==(t=i.min)&&void 0!==t?t:.1,max:null!==(n=i.max)&&void 0!==n?n:1,step:null!==(o=i.step)&&void 0!==o?o:.05,onChange:d}),He(jy,{children:[Math.round(100*c),"%"]})]})}function nb(e){var t,n,o,i,r,a=e.config,s=e.value,l=e.onChange,c=e.translate,d=v(Se(null!==(t=null!=s?s:a.min)&&void 0!==t?t:1),2),u=d[0],h=d[1];Ae(function(){var e;return h(null!==(e=null!=s?s:a.min)&&void 0!==e?e:1)},[s]);var m=ay(u,300);return Ae(function(){m!==s&&l(m)},[m]),He(Fy,{children:[He($y,{children:c(a.labelKey)}),He(Uy,{value:u,min:null!==(n=a.min)&&void 0!==n?n:1,max:null!==(o=a.max)&&void 0!==o?o:30,step:null!==(i=a.step)&&void 0!==i?i:1,onChange:h}),He(jy,{children:[u,null!==(r=a.unit)&&void 0!==r?r:""]})]})}function ob(e){var t=e.config,n=e.value,o=e.onChange,i=e.translate,r=v(Se("object"===w(n)&&null!==n?n:{id:null!=n?n:Ut.SOLID}),2),a=r[0],s=r[1];Ae(function(){var e="object"===w(n)&&null!==n?n:{id:null!=n?n:Ut.SOLID};s(e)},[n]);return He(Fy,{children:[He($y,{className:"mb-3",children:i(t.labelKey)}),He(qy,{value:a,onChange:function(e){s(e),o({strokeStyle:e.id,strokeDashArray:e.dash})}})]})}function ib(e){e.config;var t=e.value,n=e.onChange,o=e.translate,i=null!=t?t:{start:Lt.None,end:Lt.None},r=v(Se(i.start),2),a=r[0],s=r[1],l=v(Se(i.end),2),c=l[0],d=l[1];Ae(function(){s(i.start),d(i.end)},[t]);return He(Fy,{children:He("div",{class:"grid grid-cols-2 gap-4",children:[He("div",{children:[He($y,{className:"mb-3",children:o("annotation.lineStart")}),He(Ky,{value:a,onChange:function(e){s(e),n({start:e,end:c})},position:"start"})]}),He("div",{children:[He($y,{className:"mb-3",children:o("annotation.lineEnd")}),He(Ky,{value:c,onChange:function(e){d(e),n({start:a,end:e})},position:"end"})]})]})})}function rb(e){var t=e.config,n=e.value,o=e.onChange,i=e.translate,r=null!=n?n:Pt.Helvetica,a=vn(r),s=yn(r),l=bn(r),c=v(Se(a),2),d=c[0],u=c[1],h=v(Se(s),2),m=h[0],g=h[1],p=v(Se(l),2),f=p[0],y=p[1];Ae(function(){var e=null!=n?n:Pt.Helvetica;u(vn(e)),g(yn(e)),y(bn(e))},[n]);var b=function(e,t,n){var i=wn(e,{bold:t,italic:n});o(i)};return He(Fy,{children:[He($y,{children:i(t.labelKey)}),He("div",{class:"mb-3",children:He(Zy,{value:d,onChange:function(e){var t=yn(wn(e,{bold:!0,italic:!1})),n=bn(wn(e,{bold:!1,italic:!0})),o=!!t&&m,i=!!n&&f;u(e),g(o),y(i),b(e,o,i)}})}),He("div",{class:"flex gap-2",children:[He(Qy,{title:"Bold",active:m,disabled:!yn(wn(d,{bold:!0,italic:!1})),onClick:function(){if(yn(wn(d,{bold:!0,italic:!1}))){var e=!m;g(e),b(d,e,f)}},className:"font-bold",children:He(lf,{icon:"bold",size:18})}),He(Qy,{title:"Italic",active:f,disabled:!bn(wn(d,{bold:!1,italic:!0})),onClick:function(){if(bn(wn(d,{bold:!1,italic:!0}))){var e=!f;y(e),b(d,m,e)}},className:"italic",children:He(lf,{icon:"italic",size:18})})]})]})}function ab(e){var t=e.config,n=e.value,o=e.onChange,i=e.translate,r=v(Se(null!=n?n:12),2),a=r[0],s=r[1];Ae(function(){return s(null!=n?n:12)},[n]);return He(Fy,{children:[He($y,{children:i(t.labelKey)}),He(Xy,{value:a,onChange:function(e){!Number.isFinite(e)||e<=0||(s(e),o(e))}})]})}function sb(e){var t=e.config,n=e.value,o=e.onChange,i=e.colorPresets,r=e.translate,a=v(Se(null!=n?n:"#000000"),2),s=a[0],l=a[1];Ae(function(){return l(null!=n?n:"#000000")},[n]);var c=function(e){l(e),o(e)};return He(Fy,{children:[He($y,{className:"mb-3",children:r(t.labelKey)}),He("div",{class:"grid grid-cols-6 gap-x-1 gap-y-4",children:i.map(function(e){return He(Hy,{color:e,active:e===s,onSelect:c},e)})})]})}function lb(e){var t=e.config,n=e.value,o=e.onChange,i=e.translate,r=v(Se(null!=n?n:Dt.Left),2),a=r[0],s=r[1];Ae(function(){return s(null!=n?n:Dt.Left)},[n]);var l=function(e){s(e),o(e)};return He(Fy,{children:[He($y,{children:i(t.labelKey)}),He("div",{class:"flex gap-2",children:[He(Qy,{title:"Align left",active:a===Dt.Left,onClick:function(){return l(Dt.Left)},children:He(lf,{icon:"alignLeft",size:18})}),He(Qy,{title:"Align center",active:a===Dt.Center,onClick:function(){return l(Dt.Center)},children:He(lf,{icon:"alignCenter",size:18})}),He(Qy,{title:"Align right",active:a===Dt.Right,onClick:function(){return l(Dt.Right)},children:He(lf,{icon:"alignRight",size:18})})]})]})}function cb(e){var t=e.config,n=e.value,o=e.onChange,i=e.translate,r=v(Se(null!=n?n:Rt.Top),2),a=r[0],s=r[1];Ae(function(){return s(null!=n?n:Rt.Top)},[n]);var l=function(e){s(e),o(e)};return He(Fy,{children:[He($y,{children:i(t.labelKey)}),He("div",{class:"flex gap-2",children:[He(Qy,{title:"Align top",active:a===Rt.Top,onClick:function(){return l(Rt.Top)},children:He(lf,{icon:"alignTop",size:18})}),He(Qy,{title:"Align middle",active:a===Rt.Middle,onClick:function(){return l(Rt.Middle)},children:He(lf,{icon:"alignMiddle",size:18})}),He(Qy,{title:"Align bottom",active:a===Rt.Bottom,onClick:function(){return l(Rt.Bottom)},children:He(lf,{icon:"alignBottom",size:18})})]})]})}var db=(s(s(s(s(s(s(s(s(s(s(_y={},zt.Normal,"blendMode.normal"),zt.Multiply,"blendMode.multiply"),zt.Screen,"blendMode.screen"),zt.Overlay,"blendMode.overlay"),zt.Darken,"blendMode.darken"),zt.Lighten,"blendMode.lighten"),zt.ColorDodge,"blendMode.colorDodge"),zt.ColorBurn,"blendMode.colorBurn"),zt.HardLight,"blendMode.hardLight"),zt.SoftLight,"blendMode.softLight"),s(s(s(s(s(s(_y,zt.Difference,"blendMode.difference"),zt.Exclusion,"blendMode.exclusion"),zt.Hue,"blendMode.hue"),zt.Saturation,"blendMode.saturation"),zt.Color,"blendMode.color"),zt.Luminosity,"blendMode.luminosity"));function ub(e){var t=e.config,n=e.value,o=e.onChange,i=e.translate,r=v(Se(null!=n?n:zt.Normal),2),a=r[0],s=r[1];Ae(function(){return s(null!=n?n:zt.Normal)},[n]);return He(Fy,{children:[He($y,{children:i(t.labelKey)}),He("select",{class:"border-border-default bg-bg-input text-fg-primary w-full rounded border px-2 py-1 text-sm",value:a,onChange:function(e){var t=parseInt(e.target.value,10);s(t),o(t)},children:An.map(function(e){return He("option",{value:e,children:i(db[e])},e)})})]})}function hb(e){var t=e.config,n=e.value,o=e.onChange,i=e.translate,r=v(Se(null!=n?n:""),2),a=r[0],s=r[1];Ae(function(){return s(null!=n?n:"")},[n]);var l=ay(a,300);Ae(function(){l!==n&&o(l)},[l]);return He(Fy,{children:[He($y,{children:i(t.labelKey)}),He("input",{type:"text",class:"border-border-default bg-bg-input text-fg-primary w-full rounded border px-2 py-1 text-sm",value:a,onInput:function(e){var t=e.target.value;s(t)},placeholder:t.placeholderKey?i(t.placeholderKey):void 0})]})}function mb(e){var t=e.config,n=e.value,o=e.onChange,i=e.translate,r=v(Se(null!=n?n:0),2),a=r[0],s=r[1];Ae(function(){return s(null!=n?n:0)},[n]);var l=ay(a,300);return Ae(function(){l!==n&&o(l)},[l]),He(Fy,{children:[He($y,{children:i(t.labelKey)}),He(Yy,{value:a,onChange:s})]})}function gb(e){var t=e.documentId,n=e.annotations,o=e.activeTool,i=e.colorPresets,r=xh().provides,l=ja(t).translate;if(!r)return null;var c=n.length>0,d=c?y(new Set(n.map(function(e){return e.object.type}).filter(function(e){return void 0!==e}))):void 0!==(null==o?void 0:o.defaults.type)?[o.defaults.type]:[];if(0===d.length)return null;var u=function(e){var t;if(0===e.length)return[];for(var n=e.map(function(e){var t;return new Set(null!==(t=Ey[e])&&void 0!==t?t:[])}),o=n[0],i=1;i0,h="";if(c.length>1)h=s("annotation.multiSelect",{params:{count:String(c.length)}});else if(u){var m=c[0].object.type,g=pb[m],p=g?s(g):"";h=p?s("annotation.styles",{params:{type:p}}):""}else if(d){var f=d.defaults.type;if(void 0!==f){var v=pb[f],b=v?s(v):"";h=b?s("annotation.defaults",{params:{type:b}}):""}}var w=u?y(new Set(c.map(function(e){return e.object.type}))):void 0!==(null==d?void 0:d.defaults.type)?[d.defaults.type]:[],x=w.length>0&&w.some(function(e){var t,n;return(null!==(t=null===(n=Ey[e])||void 0===n?void 0:n.length)&&void 0!==t?t:0)>0});return x||u||d?He("div",{class:"h-full overflow-y-auto p-4",children:[h&&He("h2",{class:"text-md mb-4 font-medium",children:h}),He(gb,{documentId:n,annotations:c,activeTool:d,colorPresets:l})]}):He(zy,{documentId:n})}var vb=function(e){var t=e.item,n=e.pageNumber,o=e.isSelected,i=e.onSelect,r="text"===t.kind?Qp:Jp;return F("div",{onClick:i,class:"border-border-subtle hover:bg-interactive-hover flex cursor-pointer items-start gap-3 rounded-lg border p-3 transition-colors ".concat(o?"bg-interactive-selected ring-accent ring-1":"")},F("div",{class:"flex-shrink-0"},F(r,{size:20,primaryColor:t.markColor,secondaryColor:t.redactionColor})),F("div",{class:"min-w-0 flex-1"},F("div",{class:"text-fg-muted text-xs"},"Page ",n),F("div",{class:"text-fg-primary text-sm font-medium"},"text"===t.kind?"Text Redaction":"Area Redaction"),"text"===t.kind&&t.text&&F("div",{class:"text-fg-muted mt-1 truncate text-xs italic"},'"',t.text,'"')))},yb=function(e){var t=e.documentId,n=ja(t).translate;return F("div",{class:"text-fg-muted flex flex-col items-center gap-2 p-4"},F(lf,{icon:"redact",className:"h-18 w-18 text-fg-muted"}),F("div",{className:"text-fg-muted max-w-[150px] text-center text-sm"},n("redaction.emptyState",{fallback:"No pending redactions"})))};function bb(e){var t=e.documentId,n=(e=>{const{provides:t}=wg(),[n,o]=Se(lg),i=Re(()=>t?t.forDocument(e):null,[t,e]);return Ae(()=>{if(i){try{o(i.getState())}catch(e){o(lg)}return i.onStateChange(e=>{o(e)})}o(lg)},[i]),{state:n,provides:i}})(t),o=n.state,i=n.provides,r=Uo(t),a=r.canModifyAnnotations,s=r.canModifyContents,l=Mi().provides,c=ja(t).translate,d=Object.entries(o.pending).flatMap(function(e){var t=v(e,2),n=t[0];return t[1].map(function(e){return{item:e,pageNumber:Number(n)+1}})}).sort(function(e,t){return e.pageNumber-t.pageNumber});return F("div",{class:"flex h-full flex-col"},F("div",{class:"border-border-subtle border-b p-3"},F("h2",{class:"text-fg-primary text-md font-semibold"},c("redaction.panel.title",{fallback:"Redactions"})),d.length>0&&F("p",{class:"text-fg-muted text-sm"},1===d.length?c("redaction.panel.itemCount",{fallback:"1 pending redaction",params:{count:1}}):c("redaction.panel.itemCountPlural",{fallback:"".concat(d.length," pending redactions"),params:{count:d.length}}))),F("div",{class:"flex-1 overflow-y-auto p-3"},0===d.length?F(yb,{documentId:t}):F("div",{class:"space-y-2"},d.map(function(e){var t,n=e.item,r=e.pageNumber;return F(vb,{key:n.id,item:n,pageNumber:r,onSelect:function(){return function(e){null==i||i.selectPending(e.page,e.id),null==l||l.scrollToPage({pageNumber:e.page+1,pageCoordinates:{x:e.rect.origin.x,y:e.rect.origin.y},alignX:50,alignY:25,behavior:"smooth"})}(n)},isSelected:(null===(t=o.selected)||void 0===t?void 0:t.id)===n.id})}))),d.length>0&&F("div",{class:"border-border-subtle flex gap-2 border-t p-3"},F(df,{onClick:function(){null==i||i.clearPending()},disabled:!a,className:"border-border-default bg-bg-surface text-fg-secondary hover:bg-interactive-hover flex-1 rounded-md border px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},c("redaction.panel.clearAll",{fallback:"Clear All"})),F(df,{onClick:function(){null==i||i.commitAllPending()},disabled:!s,className:"bg-accent text-fg-on-accent hover:!bg-accent-hover flex-1 rounded-md border border-transparent px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},c("redaction.panel.redactAll",{fallback:"Redact All"}))))}function wb(e){var t=e.schema,n=e.documentId,o=e.props,i=o.menuWrapperProps,r=o.rect,a=o.placement,s={position:"absolute",pointerEvents:"auto",cursor:"default",left:"50%",transform:"translateX(-50%)"};return null!=a&&a.suggestTop?s.top=-50:s.top=r.size.height+8,F("div",h(h({},i),jr(t)),F("div",{style:s,className:"border-border-subtle bg-bg-elevated rounded-lg border shadow-lg"},F("div",{className:"flex items-center gap-1 p-1"},t.items.map(function(e){return F(Cb,{key:e.id,item:e,documentId:n,props:o})}))))}function xb(e){var t=e.item,n=e.documentId,o=Aa(t.commandId,n);return null!=o&&o.visible?F("div",h({},jr(t)),F(Lv,{commandId:t.commandId,documentId:n,variant:t.variant})):null}function Cb(e){var t,n=e.item,o=e.documentId,i=e.props;switch(n.type){case"command-button":return F(xb,{item:n,documentId:o});case"divider":return F("div",h({},jr(n)),F("div",{className:"bg-border-default h-6 w-px","aria-hidden":"true"}));case"group":return F("div",h({className:"flex items-center gap-".concat(null!==(t=n.gap)&&void 0!==t?t:1)},jr(n)),n.items.map(function(e){return F(Cb,{key:e.id,item:e,documentId:o,props:i})}));default:return null}}function Ib(e){var t,n,o=e.schema,i=e.documentId,r=e.className,a=o.content,s=o.position,l=ra().renderCustomComponent,c=(t=s.anchor,(n={"top-left":"top-0 left-0","top-center":"top-0 left-1/2 -translate-x-1/2","top-right":"top-0 right-0","center-left":"top-1/2 left-0 -translate-y-1/2",center:"top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2","center-right":"top-1/2 right-0 -translate-y-1/2","bottom-left":"bottom-0 left-0","bottom-center":"bottom-0 left-1/2 -translate-x-1/2","bottom-right":"bottom-0 right-0"})[t]||n["bottom-center"]),d=function(e){if(e){var t={};return e.top&&(t.top=e.top),e.right&&(t.right=e.right),e.bottom&&(t.bottom=e.bottom),e.left&&(t.left=e.left),Object.keys(t).length>0?t:void 0}}(s.offset);return F("div",{className:"z-3 absolute ".concat(c," ").concat(r||""),style:d,"data-overlay-id":o.id},l(a.componentId,i))}function kb(e){var t=e.open,n=e.title,o=e.children,i=e.onClose,r=e.onExited,a=e.className,s=e.showCloseButton,l=void 0===s||s,c=De(null),d=v(Se(t),2),u=d[0],h=d[1],m=v(Se(!1),2),g=m[0],p=m[1];Ae(function(){if(t)h(!0),requestAnimationFrame(function(){p(!0)});else if(u){p(!1);var e=setTimeout(function(){h(!1),null==r||r()},200);return function(){return clearTimeout(e)}}},[t,u,r]),Ae(function(){if(t){var e=function(e){"Escape"===e.key&&(null==i||i())};return document.addEventListener("keydown",e),function(){return document.removeEventListener("keydown",e)}}},[t,i]);return Ae(function(){return document.body.style.overflow=u?"hidden":"",function(){document.body.style.overflow=""}},[u]),u?He("div",{ref:c,className:"fixed inset-0 z-50 transition-opacity duration-200 md:flex md:items-center md:justify-center ".concat(g&&t?"bg-bg-overlay":"bg-transparent"),onClick:function(e){e.target===c.current&&(null==i||i())},children:He("div",{className:Wp("bg-bg-surface md:border-border-subtle relative flex h-full w-full flex-col transition-all duration-200 md:h-auto md:w-[28rem] md:max-w-[90vw] md:rounded-lg md:border md:shadow-lg",g&&t?"scale-100 opacity-100":"scale-95 opacity-0",a),onClick:function(e){return e.stopPropagation()},children:[(n||l)&&He("div",{className:"border-border-subtle flex flex-shrink-0 items-center justify-between border-b px-6 py-4",children:[n&&He("h2",{className:"text-fg-primary text-lg font-semibold",children:n}),l&&He(df,{onClick:i,className:"hover:bg-interactive-hover p-1",children:He(lf,{icon:"x",className:"h-5 w-5"})})]}),He("div",{className:"flex-1 overflow-y-auto px-6 py-4 md:max-h-[80vh] md:flex-none",children:o})]})}):null}function Sb(e){var t=e.documentId,n=e.isOpen,o=e.onClose,i=e.onExited,r=Mi().provides,a=Yh().provides,s=ja(t).translate,l=v(Se("all"),2),c=l[0],d=l[1],u=v(Se(""),2),h=u[0],m=u[1],g=v(Se(!0),2),p=g[0],f=g[1],y=v(Se(!1),2),b=y[0],w=y[1],x=v(Se(""),2),C=x[0],I=x[1],k=null==r?void 0:r.forDocument(t).getMetrics(),S=(null==k?void 0:k.currentPage)||1,M=(null==r?void 0:r.forDocument(t).getTotalPages())||0;Ae(function(){n&&(d("all"),m(""),f(!0),w(!1),I(""))},[n]);var A=("custom"!==c||h.trim().length>0)&&!b;return F(kb,{open:null!=n&&n,title:s("print.title"),onClose:o,onExited:i,className:"md:w-[32rem]"},F("div",{className:"space-y-6"},F("div",null,F("label",{className:"text-fg-secondary mb-3 block text-sm font-medium"},s("print.pages")),F("div",{className:"space-y-2"},F("label",{className:"flex items-center"},F("input",{type:"radio",name:"pageRange",value:"all",checked:"all"===c,onChange:function(){return d("all")},disabled:b,className:"accent-accent mr-2"}),F("span",{className:"text-fg-primary text-sm"},s("print.all"))),F("label",{className:"flex items-center"},F("input",{type:"radio",name:"pageRange",value:"current",checked:"current"===c,onChange:function(){return d("current")},disabled:b,className:"accent-accent mr-2"}),F("span",{className:"text-fg-primary text-sm"},s("print.current",{params:{currentPage:S}}))),F("label",{className:"flex items-start"},F("input",{type:"radio",name:"pageRange",value:"custom",checked:"custom"===c,onChange:function(){return d("custom")},disabled:b,className:"accent-accent mr-2 mt-0.5"}),F("div",{className:"flex-1"},F("span",{className:"text-fg-primary mb-1 block text-sm"},s("print.specify")),F("input",{type:"text",placeholder:s("print.specifyEG"),value:h,onInput:function(e){return m(e.target.value)},disabled:"custom"!==c||b,className:"w-full rounded-md border px-3 py-1 text-base ".concat("custom"!==c||b?"bg-interactive-disabled text-fg-muted":"border-border-default bg-bg-input text-fg-primary focus:border-accent focus:ring-accent"," focus:outline-none focus:ring-1")}),"custom"===c&&h.trim()&&M>0&&F("p",{className:"text-fg-muted mt-1 text-xs"},s("print.current",{params:{totalPages:M}})))))),F("div",null,F("label",{className:"flex items-center"},F("input",{type:"checkbox",checked:p,onChange:function(e){return f(e.target.checked)},disabled:b,className:"accent-accent mr-2"}),F("span",{className:"text-fg-secondary text-sm font-medium"},s("print.annotation")))),b&&F("div",{className:"bg-state-info-light flex items-center space-x-3 rounded-md p-3"},F(hy,{className:"text-accent"}),F("span",{className:"text-accent text-sm"},C)),F("div",{className:"border-border-subtle flex justify-end space-x-3 border-t pt-4"},F(df,{onClick:o,disabled:b,className:"border-border-default bg-bg-surface text-fg-secondary hover:bg-interactive-hover rounded-md border px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},s("print.cancel")),F(df,{onClick:function(){var e;"current"===c?e=String(S):"custom"===c&&(e=h.trim()||void 0);var n={includeAnnotations:p,pageRange:e};try{w(!0),I(s("print.loading"));var i=null==a?void 0:a.forDocument(t).print(n);i&&(i.onProgress(function(e){I(e.message)}),i.wait(function(){w(!1),I(""),null==o||o()},function(e){console.error("Print failed:",e),w(!1),I("")}))}catch(e){console.error("Print failed:",e),w(!1),I("")}},disabled:!A,className:"bg-accent text-fg-on-accent hover:!bg-accent-hover flex items-center space-x-2 rounded-md border border-transparent px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},b&&F(hy,{size:"sm"}),F("span",null,s(b?"print.printing":"print.print"))))))}function Mb(e){var t,n=e.documentId,o=e.isOpen,i=e.onClose,r=e.onExited,s=e.source,l=Mi().provides,c=xh().provides,d=Ll().provides,u=ja(n).translate,h=v(Se("url"),2),m=h[0],g=h[1],p=v(Se(""),2),f=p[0],y=p[1],b=v(Se(1),2),w=b[0],x=b[1],C=(null==l?void 0:l.forDocument(n).getTotalPages())||1,I=null==c?void 0:c.forDocument(n),k=null==d?void 0:d.forDocument(n),S=null==I?void 0:I.getSelectedAnnotation(),M=null!==(t=null==k?void 0:k.getFormattedSelection())&&void 0!==t?t:[];Ae(function(){o&&(g("url"),y(""),x(1))},[o]);var A="page"===m||f.trim().length>0;return F(kb,{open:null!=o&&o,title:u("link.title")||"Insert Link or Page",onClose:i,onExited:r,className:"md:w-[28rem]"},F("form",{onSubmit:function(e){e.preventDefault(),function(){var e;if("url"===m){if(!f.trim())return;e={type:"action",action:{type:Et.URI,uri:f.trim()}}}else e={type:"destination",destination:{pageIndex:w-1,zoom:{mode:Mt.FitPage},view:[]}};var t=function(){if(!S)return!1;var t,n="segmentRects"in S.object?S.object.segmentRects:[S.object.rect],o=a(null!=n?n:[]);try{for(o.s();!(t=o.n()).done;){var i=t.value;null==I||I.createAnnotation(S.object.pageIndex,{id:zn(),type:_t.LINK,pageIndex:S.object.pageIndex,rect:i,inReplyToId:S.object.id,replyType:$t.Group,target:e,strokeStyle:Ut.UNDERLINE,strokeColor:"#0000FF",strokeWidth:2})}}catch(e){o.e(e)}finally{o.f()}return!0},n=function(){if(0===M.length)return!1;var t,n=null==k?void 0:k.getSelectedText(),o=a(M);try{var i=function(){var o=t.value;null==n||n.wait(function(t){var n,i=zn();null==I||I.createAnnotation(o.pageIndex,{id:i,created:new Date,flags:["print"],type:_t.HIGHLIGHT,blendMode:zt.Multiply,pageIndex:o.pageIndex,rect:o.rect,segmentRects:o.segmentRects,strokeColor:"#FFFFFF",opacity:0,custom:{text:t.join("\n")}});var r,s=a(null!==(n=o.segmentRects)&&void 0!==n?n:[o.rect]);try{for(s.s();!(r=s.n()).done;){var l=r.value;null==I||I.createAnnotation(o.pageIndex,{id:zn(),type:_t.LINK,pageIndex:o.pageIndex,rect:l,inReplyToId:i,replyType:$t.Group,target:e,strokeStyle:Ut.UNDERLINE,strokeColor:"#0000FF",strokeWidth:2})}}catch(e){s.e(e)}finally{s.f()}null==I||I.selectAnnotation(o.pageIndex,i)},En)};for(o.s();!(t=o.n()).done;)i()}catch(e){o.e(e)}finally{o.f()}return null==k||k.clear(),!0};"annotation"===s?t():"selection"===s?n():t()||n(),null==i||i()}()},className:"space-y-6"},F("div",{className:"border-border-subtle flex border-b"},F(Gp,{active:"url"===m,onClick:function(){return g("url")}},u("link.url")||"URL"),F(Gp,{active:"page"===m,onClick:function(){return g("page")}},u("link.page")||"Page")),F("div",{className:"bg-bg-muted rounded-lg"},"url"===m?F("div",null,F("label",{className:"text-fg-secondary mb-2 block text-sm font-medium"},u("link.enterUrl")||"Enter URL"),F("input",{type:"url",value:f,onInput:function(e){return y(e.target.value)},placeholder:"https://example.com",className:"border-border-default bg-bg-input text-fg-primary focus:border-accent focus:ring-accent w-full rounded-md border px-3 py-2 text-base focus:outline-none focus:ring-1",autoFocus:!0})):F("div",null,F("label",{className:"text-fg-secondary mb-2 block text-sm font-medium"},u("link.enterPage")||"Enter Page Number"),F("input",{type:"number",min:1,max:C,value:w,onInput:function(e){var t=parseInt(e.target.value,10);isNaN(t)||x(Math.max(1,Math.min(C,t)))},className:"border-border-default bg-bg-input text-fg-primary focus:border-accent focus:ring-accent w-full rounded-md border px-3 py-2 text-base focus:outline-none focus:ring-1",autoFocus:!0}),F("p",{className:"text-fg-muted mt-1 text-xs"},u("link.pageRange",{params:{totalPages:C}})||"Page 1 to ".concat(C)))),F("div",{className:"border-border-subtle flex justify-end space-x-3 border-t pt-4"},F(df,{type:"button",onClick:i,className:"border-border-default bg-bg-surface text-fg-secondary hover:bg-interactive-hover rounded-md border px-4 py-2 text-sm"},u("common.cancel")||"Cancel"),F(df,{type:"submit",disabled:!A,className:"bg-accent text-fg-on-accent hover:!bg-accent-hover rounded-md border border-transparent px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},u("link.link")||"Link"))))}function Ab(e){var t=e.documentId,n=ci().provides,o=Ai(t),i=o.provides,r=o.state,a=r.currentPage,s=r.totalPages,l=v(Se(!1),2),c=l[0],d=l[1],u=v(Se(!1),2),h=u[0],m=u[1],g=De(null),p=v(Se(a.toString()),2),f=p[0],y=p[1],b=De(null);Ae(function(){y(a.toString())},[a]);var w=ze(function(){g.current&&clearTimeout(g.current),g.current=setTimeout(function(){h||d(!1)},4e3)},[h]);Ae(function(){if(n)return n.onScrollActivity(function(e){e.documentId===t&&(d(!0),w())})},[n,t,w]),Ae(function(){return function(){g.current&&clearTimeout(g.current)}},[]);return s<=1?null:F("div",{onMouseEnter:function(){m(!0),d(!0),g.current&&clearTimeout(g.current)},onMouseLeave:function(){m(!1),w()},className:"pointer-events-auto"},F("div",{className:"border-border-default bg-bg-surface flex items-center gap-1 rounded-lg border p-1 shadow-lg transition-opacity duration-300 ".concat(c?"opacity-100":"opacity-0")},F(Lv,{commandId:"scroll:previous-page",documentId:t,variant:"icon"}),F("div",{className:"flex items-center gap-1 px-1"},F("input",{ref:b,type:"text",inputMode:"numeric",pattern:"[0-9]*",value:f,onChange:function(e){var t=e.target.value.replace(/[^0-9]/g,"");y(t)},onFocus:function(){setTimeout(function(){var e;return null===(e=b.current)||void 0===e?void 0:e.select()},0)},onBlur:function(){var e,t=parseInt(f,10);!isNaN(t)&&t>=1&&t<=s?null==i||null===(e=i.scrollToPage)||void 0===e||e.call(i,{pageNumber:t}):y(a.toString())},onKeyDown:function(e){"Enter"===e.key?e.target.blur():"Escape"===e.key&&(y(a.toString()),e.target.blur())},className:"border-border-default bg-bg-input text-fg-primary focus:border-accent focus:ring-accent h-7 w-10 rounded border px-1 text-center text-base focus:outline-none focus:ring-1"}),F("span",{className:"text-fg-secondary text-sm"},"  ",s)),F(Lv,{commandId:"scroll:next-page",documentId:t,variant:"icon"})))}var Pb=function(e,t,n){return!function(e,t,n){return lo(e.core,t,n)}(e,t,n)},Db={"zoom:in":{id:"zoom:in",labelKey:"zoom.in",icon:"zoomIn",shortcuts:["Ctrl+=","Meta+=","Ctrl+NumpadAdd","Meta+NumpadAdd"],categories:["zoom","zoom-in"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).zoomIn()}},"zoom:out":{id:"zoom:out",labelKey:"zoom.out",icon:"zoomOut",shortcuts:["Ctrl+-","Meta+-","Ctrl+NumpadSubtract","Meta+NumpadSubtract"],categories:["zoom","zoom-out"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).zoomOut()}},"zoom:fit-page":{id:"zoom:fit-page",labelKey:"zoom.fitPage",icon:"fitToPage",shortcuts:["Ctrl+0","Meta+0"],categories:["zoom","zoom-fit-page"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).requestZoom(Fa.FitPage)},active:function(e){var t,n=e.state,o=e.documentId;return(null===(t=n.plugins.zoom)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.zoomLevel)===Fa.FitPage}},"zoom:fit-width":{id:"zoom:fit-width",labelKey:"zoom.fitWidth",icon:"fitToWidth",shortcuts:["Ctrl+1","Meta+1"],categories:["zoom","zoom-fit-width"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).requestZoom(Fa.FitWidth)},active:function(e){var t,n=e.state,o=e.documentId;return(null===(t=n.plugins.zoom)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.zoomLevel)===Fa.FitWidth}},"zoom:marquee":{id:"zoom:marquee",labelKey:"zoom.marquee",icon:"zoomInArea",shortcuts:["Ctrl+M","Meta+M"],categories:["zoom","zoom-marquee"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).toggleMarqueeZoom()},active:function(e){var t,n,o=e.state,i=e.documentId;return null!==(t=null===(n=o.plugins.zoom)||void 0===n||null===(n=n.documents[i])||void 0===n?void 0:n.isMarqueeZoomActive)&&void 0!==t&&t}},"zoom:25":{id:"zoom:25",label:"25%",categories:["zoom","zoom-level","zoom-level-25"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).requestZoom(.25)},active:function(e){var t,n=e.state,o=e.documentId;return.25===(null===(t=n.plugins.zoom)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.zoomLevel)}},"zoom:50":{id:"zoom:50",label:"50%",categories:["zoom","zoom-level","zoom-level-50"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).requestZoom(.5)},active:function(e){var t,n=e.state,o=e.documentId;return.5===(null===(t=n.plugins.zoom)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.zoomLevel)}},"zoom:100":{id:"zoom:100",label:"100%",categories:["zoom","zoom-level","zoom-level-100"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).requestZoom(1)},active:function(e){var t,n=e.state,o=e.documentId;return 1===(null===(t=n.plugins.zoom)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.zoomLevel)}},"zoom:125":{id:"zoom:125",label:"125%",categories:["zoom","zoom-level","zoom-level-125"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).requestZoom(1.25)},active:function(e){var t,n=e.state,o=e.documentId;return 1.25===(null===(t=n.plugins.zoom)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.zoomLevel)}},"zoom:150":{id:"zoom:150",label:"150%",categories:["zoom","zoom-level","zoom-level-150"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).requestZoom(1.5)},active:function(e){var t,n=e.state,o=e.documentId;return 1.5===(null===(t=n.plugins.zoom)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.zoomLevel)}},"zoom:200":{id:"zoom:200",label:"200%",categories:["zoom","zoom-level","zoom-level-200"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).requestZoom(2)},active:function(e){var t,n=e.state,o=e.documentId;return 2===(null===(t=n.plugins.zoom)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.zoomLevel)}},"zoom:400":{id:"zoom:400",label:"400%",categories:["zoom","zoom-level","zoom-level-400"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).requestZoom(4)},active:function(e){var t,n=e.state,o=e.documentId;return 4===(null===(t=n.plugins.zoom)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.zoomLevel)}},"zoom:800":{id:"zoom:800",label:"800%",categories:["zoom","zoom-level","zoom-level-800"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).requestZoom(8)},active:function(e){var t,n=e.state,o=e.documentId;return 8===(null===(t=n.plugins.zoom)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.zoomLevel)}},"zoom:1600":{id:"zoom:1600",label:"1600%",categories:["zoom","zoom-level","zoom-level-1600"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).requestZoom(16)},active:function(e){var t,n=e.state,o=e.documentId;return 16===(null===(t=n.plugins.zoom)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.zoomLevel)}},"zoom:toggle-menu":{id:"zoom:toggle-menu",labelKey:"zoom.menu",icon:"chevronDown",iconProps:{className:"h-3.5 w-3.5"},categories:["zoom","zoom-menu"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("ui"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).toggleMenu("zoom-menu","zoom:toggle-menu","zoom-menu-button")},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins.ui)||void 0===t?void 0:t.documents[o];return void 0!==(null==i?void 0:i.openMenus["zoom-menu"])}},"zoom:toggle-menu-mobile":{id:"zoom:toggle-menu-mobile",labelKey:"zoom.menu",icon:"zoomIn",categories:["zoom","zoom-menu"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("ui"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).toggleMenu("zoom-menu","zoom:toggle-menu-mobile","zoom-menu-button")},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins.ui)||void 0===t?void 0:t.documents[o];return void 0!==(null==i?void 0:i.openMenus["zoom-menu"])}},"pan:toggle":{id:"pan:toggle",labelKey:"pan.toggle",icon:"hand",shortcuts:["h"],categories:["tools","pan"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("pan"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).togglePan()},active:function(e){var t,n,o=e.state,i=e.documentId;return null!==(t=null===(n=o.plugins.pan)||void 0===n||null===(n=n.documents[i])||void 0===n?void 0:n.isPanMode)&&void 0!==t&&t}},"pointer:toggle":{id:"pointer:toggle",labelKey:"pointer.toggle",icon:"pointer",shortcuts:["p"],categories:["tools","pointer"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("interaction-manager"))||void 0===t?void 0:t.provides();if(i){var r=i.forDocument(o);"pointerMode"===r.getActiveMode()?r.activateDefaultMode():r.activate("pointerMode")}},active:function(e){var t,n=e.state,o=e.documentId;return"pointerMode"===(null===(t=n.plugins["interaction-manager"])||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.activeMode)}},"left-action-menu:overflow-menu":{id:"left-action-menu:overflow-menu",labelKey:"menu.moreOptions",icon:"dots",categories:["ui","ui-menu"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("ui"))||void 0===t?void 0:t.provides();i&&i.toggleMenu("left-action-menu","left-action-menu:overflow-menu","overflow-left-action-menu-button",o)},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins.ui)||void 0===t?void 0:t.documents[o];return void 0!==(null==i?void 0:i.openMenus["left-action-menu"])}},"capture:screenshot":{id:"capture:screenshot",labelKey:"capture.screenshot",icon:"screenshot",shortcuts:["Ctrl+Shift+S","Meta+Shift+S"],categories:["tools","capture","capture-screenshot"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("capture"))||void 0===t?void 0:t.provides();if(i){var r=i.forDocument(o);r.isMarqueeCaptureActive()?r.disableMarqueeCapture():r.enableMarqueeCapture()}},active:function(e){var t,n=e.state,o=e.documentId;return"marqueeCapture"===(null===(t=n.plugins["interaction-manager"].documents[o])||void 0===t?void 0:t.activeMode)}},"document:menu":{id:"document:menu",labelKey:"document.menu",icon:"menu",categories:["document","document-menu"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin(Ui);if(o&&o.provides){var i=o.provides();if(i)i.forDocument(n).toggleMenu("document-menu","document:menu","document-menu-button")}},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins.ui)||void 0===t?void 0:t.documents[o];return void 0!==(null==i?void 0:i.openMenus["document-menu"])}},"document:open":{id:"document:open",labelKey:"document.open",icon:"fileImport",shortcuts:["Ctrl+O","Meta+O"],categories:["document","document-open"],action:function(e){var t,n=null===(t=e.registry.getPlugin("document-manager"))||void 0===t?void 0:t.provides();null==n||n.openFileDialog()}},"document:close":{id:"document:close",labelKey:"document.close",icon:"x",shortcuts:["Ctrl+W","Meta+W"],categories:["document","document-close"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("document-manager"))||void 0===t?void 0:t.provides();null==i||i.closeDocument(o)}},"document:print":{id:"document:print",labelKey:"document.print",icon:"print",shortcuts:["Ctrl+P","Meta+P"],categories:["document","document-print"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin(Ui);if(o&&o.provides){var i=o.provides();if(i)i.forDocument(n).openModal("print-modal")}},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.Print)}},"document:protect":{id:"document:protect",labelKey:"document.protect",icon:"lock",categories:["document","document-protect"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("ui"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).openModal("protect-modal")}},"document:export":{id:"document:export",labelKey:"document.export",icon:"download",categories:["document","document-export"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("export"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).download()}},"document:capture":{id:"document:capture",labelKey:"capture.screenshot",icon:"screenshot",categories:["document","document-capture"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("capture"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).toggleMarqueeCapture()},active:function(e){var t,n=e.state,o=e.documentId;return"marqueeCapture"===(null===(t=n.plugins["interaction-manager"])||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.activeMode)}},"document:fullscreen":{id:"document:fullscreen",labelKey:"document.fullscreen",icon:function(e){var t;return null!==(t=e.state.plugins.fullscreen)&&void 0!==t&&t.isFullscreen?"fullscreenExit":"fullscreen"},shortcuts:["F11"],categories:["document","document-fullscreen"],action:function(e){var t,n=null===(t=e.registry.getPlugin("fullscreen"))||void 0===t?void 0:t.provides();n&&(n.isFullscreen()?n.exitFullscreen():n.enableFullscreen())},active:function(e){var t,n;return null!==(t=null===(n=e.state.plugins.fullscreen)||void 0===n?void 0:n.isFullscreen)&&void 0!==t&&t}},"panel:toggle-sidebar":{id:"panel:toggle-sidebar",labelKey:"panel.sidebar",icon:"sidebar",categories:["panel","panel-sidebar"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin(Ui);if(o&&o.provides){var i=o.provides();if(i)i.forDocument(n).toggleSidebar("left","main","sidebar-panel")}},active:function(e){var t=e.state,n=e.documentId;return Vr(t.plugins,n,"left","main","sidebar-panel")}},"panel:toggle-search":{id:"panel:toggle-search",labelKey:"panel.search",icon:"search",shortcuts:["Ctrl+F","Meta+F"],categories:["panel","panel-search"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin(Ui);if(o&&o.provides){var i=o.provides();if(i)i.forDocument(n).toggleSidebar("right","main","search-panel")}},active:function(e){var t=e.state,n=e.documentId;return Vr(t.plugins,n,"right","main","search-panel")}},"panel:toggle-comment":{id:"panel:toggle-comment",labelKey:"panel.comment",icon:"comment",categories:["panel","panel-comment"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin(Ui);if(o&&o.provides){var i=o.provides();if(i)i.forDocument(n).toggleSidebar("right","main","comment-panel")}},active:function(e){var t=e.state,n=e.documentId;return Vr(t.plugins,n,"right","main","comment-panel")}},"panel:toggle-redaction":{id:"panel:toggle-redaction",labelKey:"panel.redaction",icon:"redactionSidebar",categories:["panel","panel-redaction","redaction"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin(Ui);if(o&&o.provides){var i=o.provides();if(i)i.forDocument(n).toggleSidebar("right","main","redaction-panel")}},active:function(e){var t=e.state,n=e.documentId;return Vr(t.plugins,n,"right","main","redaction-panel")}},"panel:toggle-annotation-style":{id:"panel:toggle-annotation-style",labelKey:"panel.annotationStyle",icon:"palette",categories:["panel","panel-annotation-style"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin(Ui);if(o&&o.provides){var i=o.provides();if(i)i.forDocument(n).toggleSidebar("left","main","annotation-panel")}},active:function(e){var t=e.state,n=e.documentId;return Vr(t.plugins,n,"left","main","annotation-panel")},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyAnnotations)}},"page:settings":{id:"page:settings",labelKey:"page.settings",icon:"viewSettings",categories:["page","page-settings"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin(Ui);if(o&&o.provides){var i=o.provides();if(i)i.forDocument(n).toggleMenu("page-settings-menu","page:settings","page-settings-button")}},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins.ui)||void 0===t?void 0:t.documents[o];return void 0!==(null==i?void 0:i.openMenus["page-settings-menu"])}},"spread:none":{id:"spread:none",labelKey:"page.single",icon:"singlePage",categories:["page","spread","spread-none"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("spread"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).setSpreadMode(Di.None)},active:function(e){var t,n=e.state,o=e.documentId;return(null===(t=n.plugins.spread)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.spreadMode)===Di.None}},"spread:odd":{id:"spread:odd",labelKey:"page.twoOdd",icon:"doublePage",categories:["page","spread","spread-odd"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("spread"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).setSpreadMode(Di.Odd)},active:function(e){var t,n=e.state,o=e.documentId;return(null===(t=n.plugins.spread)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.spreadMode)===Di.Odd}},"spread:even":{id:"spread:even",labelKey:"page.twoEven",icon:"book2",categories:["page","spread","spread-even"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("spread"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).setSpreadMode(Di.Even)},active:function(e){var t,n=e.state,o=e.documentId;return(null===(t=n.plugins.spread)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.spreadMode)===Di.Even}},"rotate:clockwise":{id:"rotate:clockwise",labelKey:"rotate.clockwise",icon:"rotateClockwise",shortcuts:["Ctrl+]","Meta+]"],categories:["page","rotate","rotate-clockwise"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("rotate"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).rotateForward()}},"rotate:counter-clockwise":{id:"rotate:counter-clockwise",labelKey:"rotate.counterClockwise",icon:"rotateCounterClockwise",shortcuts:["Ctrl+[","Meta+["],categories:["page","rotate","rotate-counter-clockwise"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("rotate"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).rotateBackward()}},"scroll:vertical":{id:"scroll:vertical",labelKey:"page.vertical",icon:"vertical",categories:["page","scroll","scroll-vertical"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("scroll"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).setScrollStrategy(hi.Vertical)},active:function(e){var t,n=e.state,o=e.documentId;return(null===(t=n.plugins.scroll)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.strategy)===hi.Vertical}},"scroll:horizontal":{id:"scroll:horizontal",labelKey:"page.horizontal",icon:"horizontal",categories:["page","scroll","scroll-horizontal"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("scroll"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).setScrollStrategy(hi.Horizontal)},active:function(e){var t,n=e.state,o=e.documentId;return(null===(t=n.plugins.scroll)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.strategy)===hi.Horizontal}},"scroll:next-page":{id:"scroll:next-page",labelKey:"page.next",icon:"chevronRight",categories:["page","navigation","navigation-next"],shortcuts:["Ctrl+]","Meta+]","ArrowRight"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("scroll"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).scrollToNextPage()},disabled:function(e){var t,n,o=e.state,i=e.documentId;return(null===(t=o.plugins.scroll)||void 0===t||null===(t=t.documents[i])||void 0===t?void 0:t.currentPage)>=(null===(n=o.plugins.scroll)||void 0===n||null===(n=n.documents[i])||void 0===n?void 0:n.totalPages)}},"scroll:previous-page":{id:"scroll:previous-page",labelKey:"page.previous",icon:"chevronLeft",categories:["page","navigation","navigation-previous"],shortcuts:["Ctrl+[","Meta+[","ArrowLeft"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("scroll"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).scrollToPreviousPage()},disabled:function(e){var t,n=e.state,o=e.documentId;return(null===(t=n.plugins.scroll)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.currentPage)<=1}},"mode:view":{id:"mode:view",labelKey:"mode.view",categories:["mode","mode-view"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin("ui"))||void 0===t?void 0:t.provides(),a=null===(n=o.getPlugin("interaction-manager"))||void 0===n?void 0:n.provides();if(r&&a){var s=a.forDocument(i);s&&(s.activateDefaultMode(),r.forDocument(i).closeToolbarSlot("top","secondary"))}},active:function(e){var t=e.state,n=e.documentId;return!Gr(t.plugins,n,"top","secondary")}},"mode:annotate":{id:"mode:annotate",labelKey:"mode.annotate",categories:["mode","mode-annotate","annotation"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("ui"))||void 0===t?void 0:t.provides();i&&i.setActiveToolbar("top","secondary","annotation-toolbar",o)},active:function(e){var t=e.state,n=e.documentId;return Gr(t.plugins,n,"top","secondary","annotation-toolbar")}},"mode:shapes":{id:"mode:shapes",labelKey:"mode.shapes",categories:["mode","mode-shapes","annotation"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("ui"))||void 0===t?void 0:t.provides();i&&i.setActiveToolbar("top","secondary","shapes-toolbar",o)},active:function(e){var t=e.state,n=e.documentId;return Gr(t.plugins,n,"top","secondary","shapes-toolbar")}},"mode:redact":{id:"mode:redact",labelKey:"mode.redact",categories:["mode","mode-redact","redaction"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("ui"))||void 0===t?void 0:t.provides();i&&i.setActiveToolbar("top","secondary","redaction-toolbar",o)},active:function(e){var t=e.state,n=e.documentId;return Gr(t.plugins,n,"top","secondary","redaction-toolbar")}},"tabs:overflow-menu":{id:"tabs:overflow-menu",labelKey:"tabs.overflowMenu",icon:"dots",categories:["ui","ui-menu"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("ui"))||void 0===t?void 0:t.provides();i&&i.toggleMenu("mode-tabs-overflow-menu","tabs:overflow-menu","overflow-tabs-button",o)},active:function(e){var t,n=e.state,o=e.documentId;return void 0!==(null===(t=n.plugins.ui)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.openMenus["mode-tabs-overflow-menu"])}},"annotation:add-highlight":{id:"annotation:add-highlight",labelKey:"annotation.highlight",icon:"highlight",iconProps:function(e){var t;return{primaryColor:null===(t=md(e.state.plugins.annotation,"highlight"))||void 0===t?void 0:t.strokeColor}},categories:["annotation","annotation-markup","annotation-highlight"],action:function(e){var t,n,o,i=e.registry,r=e.documentId,s=null===(t=i.getPlugin(wc))||void 0===t?void 0:t.provides(),l=null===(n=i.getPlugin(Us))||void 0===n?void 0:n.provides(),c=null===(o=i.getPlugin("ui"))||void 0===o?void 0:o.provides();if(l&&s&&c){var d=null==s?void 0:s.forDocument(r),u=null==l?void 0:l.forDocument(r);if(d&&u){var h=s.getTool("highlight");if(h&&du(h)){var m=h.defaults,g=u.getFormattedSelection(),p=u.getSelectedText();if(g.length>0){var f,v=a(g);try{var y=function(){var e=f.value;p.wait(function(t){var n=zn();d.createAnnotation(e.pageIndex,{id:n,created:new Date,flags:["print"],type:_t.HIGHLIGHT,blendMode:zt.Multiply,strokeColor:m.strokeColor,opacity:m.opacity,pageIndex:e.pageIndex,rect:e.rect,segmentRects:e.segmentRects,custom:{text:t.join("\n")}}),d.selectAnnotation(e.pageIndex,n)},En)};for(v.s();!(f=v.n()).done;)y()}catch(e){v.e(e)}finally{v.f()}u.clear(),d.setActiveTool("highlight"),c.setActiveToolbar("top","secondary","annotation-toolbar",r)}else{var b;"highlight"===(null===(b=d.getActiveTool())||void 0===b?void 0:b.id)?d.setActiveTool(null):d.setActiveTool("highlight")}}}}},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[wc])||void 0===t?void 0:t.documents[o];return"highlight"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyAnnotations)}},"annotation:add-underline":{id:"annotation:add-underline",labelKey:"annotation.underline",icon:"underline",iconProps:function(e){var t;return{primaryColor:null===(t=md(e.state.plugins.annotation,"underline"))||void 0===t?void 0:t.strokeColor}},categories:["annotation","annotation-markup","annotation-underline"],action:function(e){var t,n,o,i=e.registry,r=e.documentId,s=null===(t=i.getPlugin(wc))||void 0===t?void 0:t.provides(),l=null===(n=i.getPlugin(Us))||void 0===n?void 0:n.provides(),c=null===(o=i.getPlugin("ui"))||void 0===o?void 0:o.provides();if(l&&s&&c){var d=null==s?void 0:s.forDocument(r),u=null==l?void 0:l.forDocument(r);if(d&&u){var h=s.getTool("underline");if(h&&hu(h)){var m=h.defaults,g=u.getFormattedSelection(),p=u.getSelectedText();if(g.length>0){var f,v=a(g);try{var y=function(){var e=f.value;p.wait(function(t){var n=zn();d.createAnnotation(e.pageIndex,{id:n,created:new Date,flags:["print"],type:_t.UNDERLINE,strokeColor:m.strokeColor,opacity:m.opacity,pageIndex:e.pageIndex,rect:e.rect,segmentRects:e.segmentRects,custom:{text:t.join("\n")}}),d.selectAnnotation(e.pageIndex,n)},En)};for(v.s();!(f=v.n()).done;)y()}catch(e){v.e(e)}finally{v.f()}u.clear(),d.setActiveTool("underline"),c.setActiveToolbar("top","secondary","annotation-toolbar",r)}else{var b;"underline"===(null===(b=d.getActiveTool())||void 0===b?void 0:b.id)?d.setActiveTool(null):d.setActiveTool("underline")}}}}},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[wc])||void 0===t?void 0:t.documents[o];return"underline"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyAnnotations)}},"annotation:add-strikeout":{id:"annotation:add-strikeout",labelKey:"annotation.strikeout",icon:"strikethrough",iconProps:function(e){var t;return{primaryColor:null===(t=md(e.state.plugins.annotation,"strikeout"))||void 0===t?void 0:t.strokeColor}},categories:["annotation","annotation-markup","annotation-strikeout"],action:function(e){var t,n,o,i=e.registry,r=e.documentId,s=null===(t=i.getPlugin(wc))||void 0===t?void 0:t.provides(),l=null===(n=i.getPlugin(Us))||void 0===n?void 0:n.provides(),c=null===(o=i.getPlugin("ui"))||void 0===o?void 0:o.provides();if(l&&s&&c){var d=null==s?void 0:s.forDocument(r),u=null==l?void 0:l.forDocument(r);if(d&&u){var h=s.getTool("strikeout");if(h&&mu(h)){var m=h.defaults,g=u.getFormattedSelection(),p=u.getSelectedText();if(g.length>0){var f,v=a(g);try{var y=function(){var e=f.value;p.wait(function(t){var n=zn();d.createAnnotation(e.pageIndex,{id:n,created:new Date,flags:["print"],type:_t.STRIKEOUT,strokeColor:m.strokeColor,opacity:m.opacity,pageIndex:e.pageIndex,rect:e.rect,segmentRects:e.segmentRects,custom:{text:t.join("\n")}}),d.selectAnnotation(e.pageIndex,n)},En)};for(v.s();!(f=v.n()).done;)y()}catch(e){v.e(e)}finally{v.f()}u.clear(),d.setActiveTool("strikeout"),c.setActiveToolbar("top","secondary","annotation-toolbar",r)}else{var b;"strikeout"===(null===(b=d.getActiveTool())||void 0===b?void 0:b.id)?d.setActiveTool(null):d.setActiveTool("strikeout")}}}}},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[wc])||void 0===t?void 0:t.documents[o];return"strikeout"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyAnnotations)}},"annotation:add-squiggly":{id:"annotation:add-squiggly",labelKey:"annotation.squiggly",icon:"squiggly",iconProps:function(e){var t;return{primaryColor:null===(t=md(e.state.plugins.annotation,"squiggly"))||void 0===t?void 0:t.strokeColor}},categories:["annotation","annotation-markup","annotation-squiggly"],action:function(e){var t,n,o,i=e.registry,r=e.documentId,s=null===(t=i.getPlugin(wc))||void 0===t?void 0:t.provides(),l=null===(n=i.getPlugin(Us))||void 0===n?void 0:n.provides(),c=null===(o=i.getPlugin("ui"))||void 0===o?void 0:o.provides();if(l&&s&&c){var d=null==s?void 0:s.forDocument(r),u=null==l?void 0:l.forDocument(r);if(d&&u){var h=s.getTool("squiggly");if(h&&uu(h)){var m=h.defaults,g=u.getFormattedSelection(),p=u.getSelectedText();if(g.length>0){var f,v=a(g);try{var y=function(){var e=f.value;p.wait(function(t){var n=zn();d.createAnnotation(e.pageIndex,{id:n,created:new Date,flags:["print"],type:_t.SQUIGGLY,strokeColor:m.strokeColor,opacity:m.opacity,pageIndex:e.pageIndex,rect:e.rect,segmentRects:e.segmentRects,custom:{text:t.join("\n")}}),d.selectAnnotation(e.pageIndex,n)},En)};for(v.s();!(f=v.n()).done;)y()}catch(e){v.e(e)}finally{v.f()}u.clear(),d.setActiveTool("squiggly"),c.setActiveToolbar("top","secondary","annotation-toolbar",r)}else{var b;"squiggly"===(null===(b=d.getActiveTool())||void 0===b?void 0:b.id)?d.setActiveTool(null):d.setActiveTool("squiggly")}}}}},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[wc])||void 0===t?void 0:t.documents[o];return"squiggly"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyAnnotations)}},"annotation:add-ink":{id:"annotation:add-ink",labelKey:"annotation.ink",icon:"pencilMarker",iconProps:function(e){var t;return{primaryColor:null===(t=md(e.state.plugins.annotation,"ink"))||void 0===t?void 0:t.color}},categories:["annotation","annotation-ink"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(wc))||void 0===t?void 0:t.provides(),a=null==r?void 0:r.forDocument(i);a&&("ink"===(null===(n=a.getActiveTool())||void 0===n?void 0:n.id)?a.setActiveTool(null):a.setActiveTool("ink"))},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[wc])||void 0===t?void 0:t.documents[o];return"ink"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyAnnotations)}},"annotation:add-text":{id:"annotation:add-text",labelKey:"annotation.text",icon:"text",iconProps:function(e){var t;return{primaryColor:null===(t=md(e.state.plugins.annotation,"freeText"))||void 0===t?void 0:t.fontColor}},categories:["annotation","annotation-text"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(wc))||void 0===t?void 0:t.provides(),a=null==r?void 0:r.forDocument(i);a&&("freeText"===(null===(n=a.getActiveTool())||void 0===n?void 0:n.id)?a.setActiveTool(null):a.setActiveTool("freeText"))},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[wc])||void 0===t?void 0:t.documents[o];return"freeText"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyAnnotations)}},"annotation:add-stamp":{id:"annotation:add-stamp",labelKey:"annotation.stamp",icon:"photo",categories:["annotation","annotation-stamp"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(wc))||void 0===t?void 0:t.provides(),a=null==r?void 0:r.forDocument(i);a&&("stamp"===(null===(n=a.getActiveTool())||void 0===n?void 0:n.id)?a.setActiveTool(null):a.setActiveTool("stamp"))},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[wc])||void 0===t?void 0:t.documents[o];return"stamp"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyAnnotations)}},"annotation:add-rectangle":{id:"annotation:add-rectangle",labelKey:"annotation.rectangle",icon:"square",iconProps:function(e){var t,n,o=e.state;return{primaryColor:null===(t=md(o.plugins.annotation,"square"))||void 0===t?void 0:t.strokeColor,secondaryColor:null===(n=md(o.plugins.annotation,"square"))||void 0===n?void 0:n.color}},categories:["annotation","annotation-shape","annotation-rectangle"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(wc))||void 0===t?void 0:t.provides(),a=null==r?void 0:r.forDocument(i);a&&("square"===(null===(n=a.getActiveTool())||void 0===n?void 0:n.id)?a.setActiveTool(null):a.setActiveTool("square"))},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[wc])||void 0===t?void 0:t.documents[o];return"square"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyAnnotations)}},"annotation:add-circle":{id:"annotation:add-circle",labelKey:"annotation.circle",icon:"circle",iconProps:function(e){var t,n,o=e.state;return{primaryColor:null===(t=md(o.plugins.annotation,"circle"))||void 0===t?void 0:t.strokeColor,secondaryColor:null===(n=md(o.plugins.annotation,"circle"))||void 0===n?void 0:n.color}},categories:["annotation","annotation-shape","annotation-circle"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(wc))||void 0===t?void 0:t.provides(),a=null==r?void 0:r.forDocument(i);a&&("circle"===(null===(n=a.getActiveTool())||void 0===n?void 0:n.id)?a.setActiveTool(null):a.setActiveTool("circle"))},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[wc])||void 0===t?void 0:t.documents[o];return"circle"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyAnnotations)}},"annotation:add-line":{id:"annotation:add-line",labelKey:"annotation.line",icon:"line",iconProps:function(e){var t;return{primaryColor:null===(t=md(e.state.plugins.annotation,"line"))||void 0===t?void 0:t.strokeColor}},categories:["annotation","annotation-shape","annotation-line"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(wc))||void 0===t?void 0:t.provides(),a=null==r?void 0:r.forDocument(i);a&&("line"===(null===(n=a.getActiveTool())||void 0===n?void 0:n.id)?a.setActiveTool(null):a.setActiveTool("line"))},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[wc])||void 0===t?void 0:t.documents[o];return"line"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyAnnotations)}},"annotation:add-arrow":{id:"annotation:add-arrow",labelKey:"annotation.arrow",icon:"lineArrow",iconProps:function(e){var t;return{primaryColor:null===(t=md(e.state.plugins.annotation,"line"))||void 0===t?void 0:t.strokeColor}},categories:["annotation","annotation-shape","annotation-arrow"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(wc))||void 0===t?void 0:t.provides(),a=null==r?void 0:r.forDocument(i);a&&("lineArrow"===(null===(n=a.getActiveTool())||void 0===n?void 0:n.id)?a.setActiveTool(null):a.setActiveTool("lineArrow"))},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[wc])||void 0===t?void 0:t.documents[o];return"lineArrow"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyAnnotations)}},"annotation:add-polygon":{id:"annotation:add-polygon",labelKey:"annotation.polygon",icon:"polygon",iconProps:function(e){var t,n,o=e.state;return{primaryColor:null===(t=md(o.plugins.annotation,"polygon"))||void 0===t?void 0:t.strokeColor,secondaryColor:null===(n=md(o.plugins.annotation,"polygon"))||void 0===n?void 0:n.color}},categories:["annotation","annotation-shape","annotation-polygon"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(wc))||void 0===t?void 0:t.provides(),a=null==r?void 0:r.forDocument(i);a&&("polygon"===(null===(n=a.getActiveTool())||void 0===n?void 0:n.id)?a.setActiveTool(null):a.setActiveTool("polygon"))},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[wc])||void 0===t?void 0:t.documents[o];return"polygon"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyAnnotations)}},"annotation:add-polyline":{id:"annotation:add-polyline",labelKey:"annotation.polyline",icon:"zigzag",iconProps:function(e){var t;return{primaryColor:null===(t=md(e.state.plugins.annotation,"polyline"))||void 0===t?void 0:t.strokeColor}},categories:["annotation","annotation-shape","annotation-polyline"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(wc))||void 0===t?void 0:t.provides(),a=null==r?void 0:r.forDocument(i);a&&("polyline"===(null===(n=a.getActiveTool())||void 0===n?void 0:n.id)?a.setActiveTool(null):a.setActiveTool("polyline"))},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[wc])||void 0===t?void 0:t.documents[o];return"polyline"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyAnnotations)}},"annotation:delete-selected":{id:"annotation:delete-selected",labelKey:"annotation.deleteSelected",icon:"trash",categories:["annotation","annotation-delete"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(wc))||void 0===t?void 0:t.provides(),r=null==i?void 0:i.forDocument(o);if(r){var a=r.getSelectedAnnotation();a&&r.deleteAnnotation(a.object.pageIndex,a.object.id)}},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyAnnotations)}},"annotation:delete-all-selected":{id:"annotation:delete-all-selected",labelKey:"annotation.deleteAllSelected",icon:"trash",categories:["annotation","annotation-delete","annotation-group"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(wc))||void 0===t?void 0:t.provides(),r=null==i?void 0:i.forDocument(o);if(r){var a=r.getSelectedAnnotations();0!==a.length&&(r.deleteAnnotations(a.map(function(e){return{pageIndex:e.object.pageIndex,id:e.object.id}})),r.deselectAnnotation())}},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyAnnotations)}},"annotation:toggle-group":{id:"annotation:toggle-group",labelKey:function(e){var t,n=e.registry,o=e.documentId;return"ungroup"===(null===(t=n.getPlugin(wc))||void 0===t?void 0:t.provides().forDocument(o).getGroupingAction())?"annotation.ungroup":"annotation.group"},icon:function(e){var t,n=e.registry,o=e.documentId;return"ungroup"===(null===(t=n.getPlugin(wc))||void 0===t?void 0:t.provides().forDocument(o).getGroupingAction())?"ungroup":"group"},categories:["annotation","annotation-group"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(wc))||void 0===t?void 0:t.provides().forDocument(o);if(i){var r=i.getGroupingAction();if("ungroup"===r){var a=i.getSelectedAnnotations();a.length>0&&i.ungroupAnnotations(a[0].object.id)}else"group"===r&&i.groupAnnotations()}},disabled:function(e){var t,n=e.registry,o=e.state,i=e.documentId;return!!Pb(o,i,Zt.ModifyAnnotations)||"disabled"===(null===(t=n.getPlugin(wc))||void 0===t?void 0:t.provides().forDocument(i).getGroupingAction())}},"annotation:overflow-tools":{id:"annotation:overflow-tools",labelKey:"annotation.moreTools",icon:"dots",categories:["annotation","annotation-overflow"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("ui"))||void 0===t?void 0:t.provides();if(i){var r=i.forDocument(o);r&&r.toggleMenu("annotation-tools-menu","annotation:overflow-tools","overflow-annotation-tools")}},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins.ui)||void 0===t?void 0:t.documents[o];return void 0!==(null==i?void 0:i.openMenus["annotation-tools-menu"])},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyAnnotations)}},"annotation:overflow-shapes":{id:"annotation:overflow-shapes",labelKey:"annotation.moreTools",icon:"dots",categories:["annotation","annotation-shape","annotation-overflow"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("ui"))||void 0===t?void 0:t.provides();if(i){var r=i.forDocument(o);r&&r.toggleMenu("shapes-tools-menu","annotation:overflow-shapes","overflow-shapes-tools")}},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins.ui)||void 0===t?void 0:t.documents[o];return void 0!==(null==i?void 0:i.openMenus["shapes-tools-menu"])},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyAnnotations)}},"annotation:add-link":{id:"annotation:add-link",labelKey:"annotation.addLink",icon:"link",categories:["annotation","annotation-link"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("ui"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).openModal("link-modal",{source:"selection"})},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyAnnotations)}},"annotation:toggle-annotation-style":{id:"annotation:toggle-annotation-style",labelKey:"annotation.style",icon:"palette",categories:["annotation","annotation-style"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin(Ui);if(o&&o.provides){var i=o.provides();if(i)i.forDocument(n).toggleSidebar("left","main","annotation-panel")}},active:function(e){var t=e.state,n=e.documentId;return Vr(t.plugins,n,"left","main","annotation-panel")},visible:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(wc))||void 0===t?void 0:t.provides().forDocument(o),r=null==i?void 0:i.getSelectedAnnotation();return!r||r.object.type!==_t.LINK},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyAnnotations)}},"annotation:toggle-link":{id:"annotation:toggle-link",labelKey:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(wc))||void 0===t?void 0:t.provides().forDocument(o);if(!i)return"annotation.addLink";var r=i.getSelectedAnnotation();return r&&i.hasAttachedLinks(r.object.id)?"annotation.removeLink":"annotation.addLink"},icon:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(wc))||void 0===t?void 0:t.provides().forDocument(o);if(!i)return"link";var r=i.getSelectedAnnotation();return r&&i.hasAttachedLinks(r.object.id)?"linkOff":"link"},categories:["annotation","annotation-link"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(wc))||void 0===t?void 0:t.provides(),a=null===(n=o.getPlugin("ui"))||void 0===n?void 0:n.provides();if(r&&a){var s=r.forDocument(i),l=s.getSelectedAnnotation();l&&(s.hasAttachedLinks(l.object.id)?s.deleteAttachedLinks(l.object.id):a.forDocument(i).openModal("link-modal",{source:"annotation"}))}},visible:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(wc))||void 0===t?void 0:t.provides().forDocument(o),r=null==i?void 0:i.getSelectedAnnotation();return!r||r.object.type!==_t.LINK&&r.object.type!==_t.REDACT},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyAnnotations)}},"annotation:toggle-comment":{id:"annotation:toggle-comment",labelKey:"annotation.comment",icon:"comment",categories:["annotation","annotation-comment"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin(Ui);if(o&&o.provides){var i=o.provides();if(i)i.forDocument(n).toggleSidebar("right","main","comment-panel")}},active:function(e){var t=e.state,n=e.documentId;return Vr(t.plugins,n,"right","main","comment-panel")},visible:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(wc))||void 0===t?void 0:t.provides().forDocument(o),r=null==i?void 0:i.getSelectedAnnotation();return!r||r.object.type!==_t.LINK}},"annotation:goto-link":{id:"annotation:goto-link",labelKey:"annotation.gotoLink",icon:"externalLink",categories:["annotation","annotation-link"],action:function(e){var t,n,o,i=e.registry,r=e.documentId,a=null===(t=i.getPlugin(wc))||void 0===t?void 0:t.provides(),s=null===(n=i.getPlugin("scroll"))||void 0===n?void 0:n.provides();if(a){var l=a.forDocument(r),c=l.getSelectedAnnotation();if(c){var d=null;if(sd(c))d=c.object;else{var u=l.getAttachedLinks(c.object.id);u.length>0&&(d=u[0].object)}if(null!==(o=d)&&void 0!==o&&o.target){var h=d.target;if("action"===h.type){var m=h.action;if(m.type===Et.URI)window.open(m.uri,"_blank","noopener,noreferrer");else if(m.type===Et.Goto&&s){var g=m.destination;s.forDocument(r).scrollToPage({pageNumber:g.pageIndex+1,behavior:"smooth"})}}else if("destination"===h.type&&s){var p=h.destination;s.forDocument(r).scrollToPage({pageNumber:p.pageIndex+1,behavior:"smooth"})}}}}},visible:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(wc))||void 0===t?void 0:t.provides();if(!i)return!1;var r=i.forDocument(o),a=null==r?void 0:r.getSelectedAnnotation();return!!a&&(a.object.type===_t.LINK||r.hasAttachedLinks(a.object.id))}},"redaction:redact":{id:"redaction:redact",labelKey:"redaction.redact",icon:"redactArea",categories:["redaction","redaction-combined"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("redaction"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).toggleRedact()},active:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin("redaction"))||void 0===t?void 0:t.provides();return null!==(n=null==r?void 0:r.forDocument(i).isRedactActive())&&void 0!==n&&n},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyContents)}},"redaction:redact-area":{id:"redaction:redact-area",labelKey:"redaction.area",icon:"redactArea",categories:["redaction","redaction-area"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("redaction"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).toggleMarqueeRedact()},active:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin("redaction"))||void 0===t?void 0:t.provides();return null!==(n=null==r?void 0:r.forDocument(i).isMarqueeRedactActive())&&void 0!==n&&n},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyContents)}},"redaction:redact-text":{id:"redaction:redact-text",labelKey:"redaction.text",icon:"redact",categories:["redaction","redaction-text"],action:function(e){var t,n,o,i,r=e.registry,a=e.documentId,s=null===(t=r.getPlugin("redaction"))||void 0===t?void 0:t.provides(),l=null===(n=r.getPlugin(Us))||void 0===n?void 0:n.provides(),c=null===(o=r.getPlugin("ui"))||void 0===o?void 0:o.provides();if(s&&l&&c){var d=s.forDocument(a),u=null==l?void 0:l.forDocument(a);(null!==(i=null==u?void 0:u.getFormattedSelection())&&void 0!==i?i:[]).length>0?(d.queueCurrentSelectionAsPending(),c.setActiveToolbar("top","secondary","redaction-toolbar",a)):d.toggleRedactSelection()}},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[gg])||void 0===t?void 0:t.documents[o];return(null==i?void 0:i.activeType)===Wm.RedactSelection},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyContents)}},"redaction:apply-all":{id:"redaction:apply-all",labelKey:"redaction.applyAll",icon:"check",categories:["redaction","redaction-apply"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("redaction"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).commitAllPending()},disabled:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[gg])||void 0===t?void 0:t.documents[o];return 0===(null==i?void 0:i.pendingCount)||Pb(n,o,Zt.ModifyContents)}},"redaction:clear-all":{id:"redaction:clear-all",labelKey:"redaction.clearAll",icon:"x",categories:["redaction","redaction-clear"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("redaction"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).clearPending()},disabled:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[gg])||void 0===t?void 0:t.documents[o];return 0===(null==i?void 0:i.pendingCount)||Pb(n,o,Zt.ModifyContents)}},"redaction:delete-selected":{id:"redaction:delete-selected",labelKey:"redaction.deleteSelected",icon:"trash",categories:["redaction","redaction-delete"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("redaction"))||void 0===t?void 0:t.provides(),r=null==i?void 0:i.forDocument(o).getSelectedPending();r&&(null==i||i.forDocument(o).removePending(r.page,r.id))}},"redaction:commit-selected":{id:"redaction:commit-selected",labelKey:"redaction.commitSelected",icon:"check",categories:["redaction","redaction-commit"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("redaction"))||void 0===t?void 0:t.provides(),r=null==i?void 0:i.forDocument(o).getSelectedPending();r&&(null==i||i.forDocument(o).commitPending(r.page,r.id))}},"annotation:apply-redaction":{id:"annotation:apply-redaction",labelKey:"redaction.apply",icon:"check",categories:["annotation","annotation-redaction","redaction"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=e.logger;r.debug("Command","ApplyRedaction","Starting for document: ".concat(i));var a=null===(t=o.getPlugin(wc))||void 0===t?void 0:t.provides(),s=null===(n=o.getPlugin(gg))||void 0===n?void 0:n.provides();if(a&&s){var l=a.forDocument(i).getSelectedAnnotation();r.debug("Command","ApplyRedaction","Selected annotation: ".concat(l?JSON.stringify({id:l.object.id,type:l.object.type,pageIndex:l.object.pageIndex}):"none")),l&&l.object.type===_t.REDACT?(r.debug("Command","ApplyRedaction","Calling commitPending for page ".concat(l.object.pageIndex,", id ").concat(l.object.id)),s.forDocument(i).commitPending(l.object.pageIndex,l.object.id),r.debug("Command","ApplyRedaction","commitPending called successfully")):r.warn("Command","ApplyRedaction","No valid redaction selected - selected: ".concat(!!l,", type: ").concat(null==l?void 0:l.object.type))}else r.warn("Command","ApplyRedaction","Missing plugins - annotation: ".concat(!!a,", redaction: ").concat(!!s))},visible:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(wc))||void 0===t?void 0:t.provides().forDocument(o),r=null==i?void 0:i.getSelectedAnnotation();return(null==r?void 0:r.object.type)===_t.REDACT},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.ModifyContents)}},"selection:copy-to-clipboard":{id:"selection:copy-to-clipboard",labelKey:"selection.copyToClipboard",icon:"copy",shortcuts:["Ctrl+C","Meta+C"],categories:["selection","selection-copy-to-clipboard"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin("selection"),i=null==o?void 0:o.provides().forDocument(n);null==i||i.copyToClipboard()},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.CopyContents)}},"selection:copy":{id:"selection:copy",labelKey:"selection.copy",icon:"copy",categories:["selection","selection-copy"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin("selection"),i=null==o?void 0:o.provides().forDocument(n);null==i||i.copyToClipboard(),null==i||i.clear()},disabled:function(e){var t=e.state,n=e.documentId;return Pb(t,n,Zt.CopyContents)}},"history:undo":{id:"history:undo",labelKey:"history.undo",icon:"arrowBackUp",shortcuts:["Ctrl+Z","Meta+Z"],categories:["history","history-undo"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(_m))||void 0===t?void 0:t.provides();i&&i.forDocument(o).undo()},disabled:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[_m])||void 0===t?void 0:t.documents[o];return!(null!=i&&i.global.canUndo)}},"history:redo":{id:"history:redo",labelKey:"history.redo",icon:"arrowForwardUp",shortcuts:["Ctrl+Y","Meta+Shift+Z"],categories:["history","history-redo"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(_m))||void 0===t?void 0:t.provides();i&&i.forDocument(o).redo()},disabled:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[_m])||void 0===t?void 0:t.documents[o];return!(null!=i&&i.global.canRedo)}}},Rb={"zoom.level":function(e){var t,n,o=e.state,i=e.documentId,r=i&&null!==(t=null===(n=o.plugins[Ha])||void 0===n||null===(n=n.documents[i])||void 0===n?void 0:n.currentZoomLevel)&&void 0!==t?t:1;return{level:Math.round(100*r)}}},zb={colors:{background:{app:"#f3f4f6",surface:"#ffffff",surfaceAlt:"#f1f3f5",elevated:"#ffffff",overlay:"rgba(0, 0, 0, 0.5)",input:"#ffffff"},foreground:{primary:"#111827",secondary:"#374151",muted:"#6b7280",disabled:"#9ca3af",onAccent:"#ffffff"},border:{default:"#d1d5db",subtle:"#e5e7eb",strong:"#9ca3af"},accent:{primary:"#3b82f6",primaryHover:"#2563eb",primaryActive:"#1d4ed8",primaryLight:"#eff6ff",primaryForeground:"#ffffff"},interactive:{hover:"#f3f4f6",active:"#e5e7eb",selected:"#eff6ff",focus:"#3b82f6",focusRing:"#bfdbfe"},state:{error:"#ef4444",errorLight:"#fef2f2",warning:"#f59e0b",warningLight:"#fffbeb",success:"#22c55e",successLight:"#f0fdf4",info:"#3b82f6",infoLight:"#eff6ff"},tooltip:{background:"#111827",foreground:"#ffffff"},scrollbar:{track:"#f3f4f6",thumb:"#d1d5db",thumbHover:"#9ca3af"}}},Tb={colors:{background:{app:"#111827",surface:"#1f2937",surfaceAlt:"#374151",elevated:"#1f2937",overlay:"rgba(0, 0, 0, 0.7)",input:"#374151"},foreground:{primary:"#f9fafb",secondary:"#e5e7eb",muted:"#9ca3af",disabled:"#6b7280",onAccent:"#111827"},border:{default:"#4b5563",subtle:"#374151",strong:"#6b7280"},accent:{primary:"#60a5fa",primaryHover:"#3b82f6",primaryActive:"#2563eb",primaryLight:"#1e3a5f",primaryForeground:"#111827"},interactive:{hover:"#374151",active:"#4b5563",selected:"#1e3a5f",focus:"#60a5fa",focusRing:"#1e40af"},state:{error:"#f87171",errorLight:"#7f1d1d",warning:"#fbbf24",warningLight:"#78350f",success:"#4ade80",successLight:"#14532d",info:"#60a5fa",infoLight:"#1e3a5f"},tooltip:{background:"#f9fafb",foreground:"#111827"},scrollbar:{track:"#1f2937",thumb:"#4b5563",thumbHover:"#6b7280"}}};function Eb(e,t){var n=h({},e);for(var o in t){var i=t[o];i&&"object"===w(i)&&!Array.isArray(i)?n[o]=Eb(e[o]||{},i):void 0!==i&&(n[o]=i)}return n}function _b(e,t){return{colors:Eb(e.colors,t)}}function Nb(e){return"system"===e?"undefined"==typeof window?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":e}function Ob(e){return e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Lb(e){return":host {\n".concat(function(e){var t=[];return function e(n,o){for(var i=0,r=Object.entries(n);i1?F("div",{className:"bg-bg-surface-alt flex items-end pr-2 pt-2"},F("div",{className:"flex flex-1 items-end overflow-x-auto pl-4"},t.map(function(e){var t,o,i=n===e.id;return F("div",{key:e.id,onClick:function(){return l(e.id)},role:"tab",tabIndex:0,"aria-selected":i,onKeyDown:function(t){"Enter"!==t.key&&" "!==t.key||(t.preventDefault(),l(e.id))},className:"group relative flex min-w-[120px] max-w-[240px] cursor-pointer items-center gap-2 rounded-t-lg px-4 py-2 text-sm font-medium transition-all ".concat(i?"bg-bg-surface text-fg-primary z-10":"bg-bg-surface-alt text-fg-secondary hover:bg-interactive-hover hover:text-fg-primary")},F("span",{className:"min-w-0 flex-1 truncate"},null!==(t=e.name)&&void 0!==t?t:"Document ".concat(e.id.slice(0,8))),i&&F("button",{onClick:function(t){t.stopPropagation(),c(e.id)},"aria-label":"Close ".concat(null!==(o=e.name)&&void 0!==o?o:"document"),className:"hover:bg-interactive-hover flex-shrink-0 cursor-pointer rounded-full p-1 transition-all ".concat(i?"opacity-100":"opacity-0 group-hover:opacity-100")},F(lf,{icon:"x",size:14})))}),a&&F("button",{onClick:d,className:"text-fg-secondary hover:bg-interactive-hover hover:text-fg-primary mb-1.5 ml-1 flex-shrink-0 cursor-pointer rounded p-1.5 transition-colors","aria-label":"Open File",title:"Open File"},F(lf,{icon:"plus",size:14})))):null}function jb(){var e=va().provides,t=ja().translate;return F("div",{className:"bg-bg-app flex h-full w-full items-center justify-center"},F("div",{className:"flex max-w-sm flex-col items-center text-center"},F("div",{className:"bg-accent-light mb-6 rounded-full p-5"},F(lf,{icon:"file",size:48,className:"text-accent"})),F("h2",{className:"text-fg-primary mb-2 text-xl font-semibold"},t("emptyState.title")),F("p",{className:"text-fg-secondary mb-6 text-sm leading-relaxed"},t("emptyState.description"),F("br",null),t("emptyState.descriptionMulti")),F("button",{onClick:function(){null==e||e.openFileDialog()},className:"bg-accent hover:bg-accent-hover text-accent-fg inline-flex cursor-pointer items-center gap-2 rounded-md px-5 py-2.5 text-sm font-medium shadow-sm transition-all"},F(lf,{icon:"plus",size:16}),t("emptyState.openButton")),F("p",{className:"text-fg-muted mt-4 text-xs"},t("emptyState.supportedFormats"))))}function Fb(e){var t=e.documentState,o=va().provides,i=ja().translate,r=v(Se(""),2),a=r[0],s=r[1],l=v(Se(!1),2),c=l[0],d=l[1];if(!t)return null;var u=t.name,h=t.errorCode,m=t.passwordProvided,p=h===Qt.Password,f=p&&!m,y=p&&m;if(!p)return F("div",{className:"bg-bg-app flex h-full items-center justify-center p-8"},F("div",{className:"bg-bg-surface border-border-default flex max-w-sm flex-col items-center rounded-xl border p-6 text-center shadow-lg"},F("div",{className:"bg-state-error-light mb-4 rounded-full p-4"},F(lf,{icon:"alertTriangle",size:28,className:"text-state-error"})),F("h3",{className:"text-fg-primary text-lg font-semibold"},i("documentError.title")),F("p",{className:"text-fg-secondary mt-2 text-sm"},t.error||i("documentError.unknown")),h&&F("p",{className:"text-fg-muted mt-1 text-xs"},i("documentError.errorCode",{params:{code:String(h)}})),F("button",{onClick:function(){return null==o?void 0:o.closeDocument(t.id)},className:"bg-accent hover:bg-accent-hover text-accent-fg mt-5 w-full cursor-pointer rounded-md px-4 py-2.5 text-sm font-medium transition-colors"},i("documentError.close"))));var b=function(){var e=n(g().m(function e(){return g().w(function(e){for(;;)switch(e.n){case 0:if(o&&a.trim()){e.n=1;break}return e.a(2);case 1:d(!0),o.retryDocument(t.id,{password:a}).wait(function(){s(""),d(!1)},function(e){console.error("Retry failed:",e),d(!1)});case 2:return e.a(2)}},e)}));return function(){return e.apply(this,arguments)}}();return F("div",{className:"bg-bg-app flex h-full items-center justify-center p-8"},F("div",{className:"bg-bg-surface border-border-default w-full max-w-sm rounded-xl border p-6 shadow-lg"},F("div",{className:"flex flex-col items-center text-center"},F("div",{className:"bg-accent-light mb-4 rounded-full p-4"},F(lf,{icon:"lock",size:28,className:"text-accent"})),F("h3",{className:"text-fg-primary text-lg font-semibold"},i("passwordPrompt.title")),u&&F("p",{className:"text-fg-muted mt-1 text-sm"},u)),F("p",{className:"text-fg-secondary mt-4 text-center text-sm"},f&&i("passwordPrompt.required"),y&&i("passwordPrompt.incorrect")),F("div",{className:"mt-5"},F("label",{className:"text-fg-primary mb-1.5 block text-sm font-medium"},i("passwordPrompt.label")),F("input",{type:"password",value:a,onInput:function(e){return s(e.target.value)},onKeyDown:function(e){return"Enter"===e.key&&!c&&a.trim()&&b()},disabled:c,placeholder:i("passwordPrompt.placeholder"),className:"bg-bg-input border-border-default focus:border-accent focus:ring-accent text-fg-primary placeholder:text-fg-muted block w-full rounded-md border px-3 py-2.5 text-sm focus:outline-none focus:ring-1 disabled:opacity-50",autoFocus:!0})),y&&F("div",{className:"bg-state-error-light border-state-error mt-3 flex items-center gap-2 rounded-md border p-3"},F(lf,{icon:"alertTriangle",size:16,className:"text-state-error flex-shrink-0"}),F("p",{className:"text-state-error text-sm"},i("passwordPrompt.incorrectWarning"))),F("div",{className:"mt-6 flex gap-3"},F("button",{onClick:function(){return null==o?void 0:o.closeDocument(t.id)},disabled:c,className:"border-border-default text-fg-secondary hover:bg-interactive-hover flex-1 cursor-pointer rounded-md border px-4 py-2.5 text-sm font-medium transition-colors disabled:opacity-50"},i("passwordPrompt.cancel")),F("button",{onClick:b,disabled:c||!a.trim(),className:"bg-accent hover:bg-accent-hover text-accent-fg flex-1 cursor-pointer rounded-md px-4 py-2.5 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50"},i(c?"passwordPrompt.opening":"passwordPrompt.open")))))}function Ub(e){var t=e.documentId,n=e.className,o=Aa("mode:view",t),i=Aa("mode:annotate",t),r=Aa("mode:shapes",t),a=Aa("mode:redact",t),s=Aa("tabs:overflow-menu",t),l=Re(function(){return[o,i,r,a].find(function(e){return null==e?void 0:e.active})||o},[o,i,r,a]),c=ze(function(e){e.preventDefault(),e.stopPropagation(),s&&!s.disabled&&s.execute()},[s]);if(!s||!s.visible)return null;var d=s.active;return F("div",{style:{maxWidth:"100px",width:"100px"},className:n},F(df,{className:"bg-bg-surface col-start-1 row-start-1 !w-full appearance-none rounded-md py-1.5 pl-3 pr-2 text-[13px] ".concat(d?"bg-interactive-selected ring-accent border-none shadow ring":"border-border-default outline-border-default hover:bg-interactive-hover hover:ring-accent outline outline-1 -outline-offset-1 hover:ring"," flex flex-row items-center justify-between gap-2"),onClick:c,disabled:s.disabled,style:{height:34}},F("span",{className:"min-w-0 flex-1 truncate text-left ".concat(d?"text-accent":"text-fg-primary")},null==l?void 0:l.label),F(lf,{icon:"chevronDown",className:"h-4 w-4 ".concat(d?"text-accent":"text-fg-secondary")})))}function Hb(e){var t=e.documentId,n=Tm().provides,o=v(Se(!1),2),i=o[0],r=o[1],a=v(Se(null),2),s=a[0],l=a[1],c=v(Se(null),2),d=c[0],u=c[1],h=v(Se(null),2),m=h[0],g=h[1],p=De(null),f=De(null),y=ja(t).translate,b=function(){p.current&&(URL.revokeObjectURL(p.current),p.current=null),m&&(URL.revokeObjectURL(m),g(null)),r(!1),l(null),u(null)};Ae(function(){if(n)return n.onCaptureArea(function(e){var t=e.pageIndex,n=e.rect,o=e.blob;l({pageIndex:t,rect:n,blob:o});var i=URL.createObjectURL(o);p.current=i,u(i),r(!0)})},[n]);return F(H,null,F(kb,{open:i,onClose:b,title:y("capture.title"),className:"md:w-[48rem]"},F("div",{className:"space-y-6"},F("div",{className:"flex justify-center"},d&&F("img",{src:d,onLoad:function(){p.current&&(URL.revokeObjectURL(p.current),p.current=null)},alt:"Captured PDF area",style:{maxWidth:"100%",maxHeight:"400px",border:"1px solid #e5e7eb",borderRadius:"4px",display:"block"}})),F("div",{className:"border-border-subtle flex justify-end space-x-3 border-t pt-4"},F(df,{onClick:b,className:"border-border-default bg-bg-surface text-fg-secondary hover:bg-interactive-hover rounded-md border px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},y("capture.cancel")),F(df,{onClick:function(){if(s&&f.current){var e=URL.createObjectURL(s.blob);g(e),f.current.href=e,f.current.download="pdf-capture-page-".concat(s.pageIndex+1,".png"),f.current.click(),b()}},disabled:!s,className:"bg-accent text-fg-on-accent hover:!bg-accent-hover flex items-center space-x-2 rounded-md border border-transparent px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},y("capture.download"))))),F("a",{ref:f,style:{display:"none"},href:"",download:""}))}var Bb=[{flag:Zt.Print,labelKey:"protect.permissions.print"},{flag:Zt.PrintHighQuality,labelKey:"protect.permissions.printHighQuality"},{flag:Zt.CopyContents,labelKey:"protect.permissions.copy"},{flag:Zt.ExtractForAccessibility,labelKey:"protect.permissions.accessibility"},{flag:Zt.ModifyContents,labelKey:"protect.permissions.modify"},{flag:Zt.ModifyAnnotations,labelKey:"protect.permissions.annotations"},{flag:Zt.FillForms,labelKey:"protect.permissions.fillForms"},{flag:Zt.AssembleDocument,labelKey:"protect.permissions.assemble"}];function Wb(e){var t=e.permissions,n=e.translate,o=e.label;return F("div",null,F("label",{className:"text-fg-secondary mb-2 block text-sm font-medium"},null!=o?o:n("security.viewPermissions.restrictedActions")),F("div",{className:"grid grid-cols-1 gap-1 sm:grid-cols-2"},Bb.map(function(e){var o,i=(o=e.flag,0!==(t&o));return F("div",{key:e.flag,className:"flex items-center rounded-md p-2 ".concat(i?"text-fg-primary":"text-fg-muted")},F(lf,{icon:i?"check":"x",className:"mr-2 h-4 w-4 flex-shrink-0 ".concat(i?"text-state-success":"text-state-error")}),F("span",{className:"text-sm"},n(e.labelKey)))})))}function qb(e){var t,n,o,i=e.documentId,r=e.isOpen,s=e.onClose,l=e.onExited,c=ja(i).translate,d=va().provides,u=Oo(i),h=null==u?void 0:u.document,m=null!==(t=null==h?void 0:h.isEncrypted)&&void 0!==t&&t,g=null!==(n=null==h?void 0:h.isOwnerUnlocked)&&void 0!==n&&n,p=null!==(o=null==h?void 0:h.permissions)&&void 0!==o?o:0,f=v(Se("edit-protection"),2),y=f[0],b=f[1],w=v(Se(""),2),x=w[0],C=w[1],I=v(Se(!1),2),k=I[0],S=I[1],M=v(Se(!1),2),A=M[0],P=M[1],D=v(Se(null),2),R=D[0],z=D[1],T=v(Se(!1),2),E=T[0],_=T[1],N=v(Se(""),2),O=N[0],L=N[1],$=v(Se(""),2),j=$[0],U=$[1],H=v(Se(!1),2),B=H[0],W=H[1],q=v(Se(!1),2),G=q[0],V=q[1],K=v(Se(""),2),Z=K[0],Y=K[1],X=v(Se(""),2),Q=X[0],J=X[1],ee=v(Se(!1),2),te=ee[0],ne=ee[1],oe=Se(new Set(Bb.map(function(e){return e.flag}))),ie=v(oe,2),re=ie[0],ae=ie[1],se=v(Se(!1),2),le=se[0],ce=se[1],de=v(Se(null),2),ue=de[0],he=de[1];Ae(function(){r&&(C(""),S(!1),P(!1),z(null),_(!1),L(""),U(""),W(!1),V(!1),Y(""),J(""),ne(!1),ae(new Set(Bb.map(function(e){return e.flag}))),ce(!1),he(null),b(m&&!g?"unlock":m&&g?"choose-action":"edit-protection"))},[r,m,g]);var me=O===j,ge=Z===Q,pe=!E||O.length>0&&me,fe=!G||Z.length>0&&ge,ve=(E||G)&&pe&&fe&&!le,ye=function(){d&&x&&(P(!0),z(null),d.unlockOwnerPermissions(i,x).wait(function(e){P(!1),e?b("choose-action"):z(c("security.unlock.invalidPassword"))},function(e){var t,n;P(!1),z(null!==(t=null===(n=e.reason)||void 0===n?void 0:n.message)&&void 0!==t?t:c("security.unlock.failed"))}))},be=function(){if(ve&&d){var e=0;if(G){var t,n=a(re);try{for(n.s();!(t=n.n()).done;){e|=t.value}}catch(e){n.e(e)}finally{n.f()}}else e=Zt.AllowAll;var o=E?O:"",r=G?Z:E?O:"";ce(!0),he(null),d.setDocumentEncryption(i,{userPassword:o,ownerPassword:r,allowedFlags:e}).wait(function(e){ce(!1),e?null==s||s():he(c("protect.applyFailed"))},function(e){var t,n;ce(!1),he(null!==(t=null===(n=e.reason)||void 0===n?void 0:n.message)&&void 0!==t?t:c("protect.applyFailed"))})}},we=function(){d&&(ce(!0),he(null),d.removeEncryption(i).wait(function(e){ce(!1),e?null==s||s():he(c("protect.removeFailed"))},function(e){var t,n;ce(!1),he(null!==(t=null===(n=e.reason)||void 0===n?void 0:n.message)&&void 0!==t?t:c("protect.removeFailed"))}))},xe=function(){return F("div",{className:"space-y-6"},F("div",{className:"bg-bg-subtle rounded-lg"},F("label",{className:"flex cursor-pointer items-start"},F("input",{type:"checkbox",checked:E,onChange:function(e){return _(e.target.checked)},className:"accent-accent mr-3 mt-0.5"}),F("div",{className:"flex-1"},F("span",{className:"text-fg-primary block font-medium"},c("protect.openPassword.title")),F("span",{className:"text-fg-muted text-sm"},c("protect.openPassword.description")))),E&&F("div",{className:"mt-4 space-y-3 pl-6"},F("div",null,F("label",{className:"text-fg-secondary mb-1 block text-sm"},c("protect.openPassword.label")),F("div",{className:"relative"},F("input",{type:B?"text":"password",value:O,onInput:function(e){return L(e.target.value)},placeholder:c("protect.openPassword.placeholder"),className:"border-border-default bg-bg-input text-fg-primary focus:border-accent focus:ring-accent w-full rounded-md border px-3 py-2 pr-10 text-sm focus:outline-none focus:ring-1"}),F("button",{type:"button",onClick:function(){return W(!B)},className:"text-fg-muted hover:text-fg-secondary absolute right-2 top-1/2 -translate-y-1/2"},F(lf,{icon:B?"eye-off":"eye",className:"h-4 w-4"})))),F("div",null,F("label",{className:"text-fg-secondary mb-1 block text-sm"},c("protect.openPassword.confirm")),F("input",{type:B?"text":"password",value:j,onInput:function(e){return U(e.target.value)},placeholder:c("protect.openPassword.confirmPlaceholder"),className:"border-border-default bg-bg-input text-fg-primary focus:ring-accent w-full rounded-md border px-3 py-2 text-sm focus:outline-none focus:ring-1 ".concat(j&&!me?"border-state-error focus:border-state-error":"focus:border-accent")}),j&&!me&&F("p",{className:"text-state-error mt-1 text-xs"},c("protect.passwordMismatch"))))),F("div",{className:"bg-bg-subtle rounded-lg"},F("label",{className:"flex cursor-pointer items-start"},F("input",{type:"checkbox",checked:G,onChange:function(e){return V(e.target.checked)},className:"accent-accent mr-3 mt-0.5"}),F("div",{className:"flex-1"},F("span",{className:"text-fg-primary block font-medium"},c("protect.permissions.title")),F("span",{className:"text-fg-muted text-sm"},c("protect.permissions.description")))),G&&F("div",{className:"mt-4 space-y-4 pl-6"},F("div",{className:"border-border-subtle border-b pb-4"},F("div",null,F("label",{className:"text-fg-secondary mb-1 block text-sm"},c("protect.ownerPassword.label")),F("div",{className:"relative"},F("input",{type:te?"text":"password",value:Z,onInput:function(e){return Y(e.target.value)},placeholder:c("protect.ownerPassword.placeholder"),className:"border-border-default bg-bg-input text-fg-primary focus:border-accent focus:ring-accent w-full rounded-md border px-3 py-2 pr-10 text-sm focus:outline-none focus:ring-1"}),F("button",{type:"button",onClick:function(){return ne(!te)},className:"text-fg-muted hover:text-fg-secondary absolute right-2 top-1/2 -translate-y-1/2"},F(lf,{icon:te?"eye-off":"eye",className:"h-4 w-4"})))),F("div",{className:"mt-3"},F("label",{className:"text-fg-secondary mb-1 block text-sm"},c("protect.ownerPassword.confirm")),F("input",{type:te?"text":"password",value:Q,onInput:function(e){return J(e.target.value)},placeholder:c("protect.ownerPassword.confirmPlaceholder"),className:"border-border-default bg-bg-input text-fg-primary focus:ring-accent w-full rounded-md border px-3 py-2 text-sm focus:outline-none focus:ring-1 ".concat(Q&&!ge?"border-state-error focus:border-state-error":"focus:border-accent")}),Q&&!ge&&F("p",{className:"text-state-error mt-1 text-xs"},c("protect.passwordMismatch")))),F("div",null,F("label",{className:"text-fg-secondary mb-2 block text-sm font-medium"},c("protect.permissions.allowedActions")),F("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-2"},Bb.map(function(e){return F("label",{key:e.flag,className:"hover:bg-bg-surface flex cursor-pointer items-center rounded-md p-2 transition-colors"},F("input",{type:"checkbox",checked:re.has(e.flag),onChange:function(){return t=e.flag,void ae(function(e){var n=new Set(e);return n.has(t)?n.delete(t):(n.add(t),t===Zt.PrintHighQuality&&n.add(Zt.Print)),n});var t},className:"accent-accent mr-2"}),F("span",{className:"text-fg-primary text-sm"},c(e.labelKey)))}))))),E&&G&&F("div",{className:"bg-state-info-light flex items-start space-x-2 rounded-md p-3"},F(lf,{icon:"info",className:"text-accent mt-0.5 h-4 w-4 flex-shrink-0"}),F("p",{className:"text-fg-secondary text-sm"},c("protect.bothPasswordsNote"))),!E&&!G&&!ue&&F("div",{className:"bg-state-warning-light flex items-start space-x-2 rounded-md p-3"},F(lf,{icon:"alertTriangle",className:"text-state-warning mt-0.5 h-4 w-4 flex-shrink-0"}),F("p",{className:"text-fg-secondary text-sm"},c("protect.noProtectionSelected"))),ue&&F("div",{className:"bg-state-error-light flex items-start space-x-2 rounded-md p-3"},F(lf,{icon:"alertTriangle",className:"text-state-error mt-0.5 h-4 w-4 flex-shrink-0"}),F("p",{className:"text-state-error text-sm"},ue)),F("div",{className:"border-border-subtle flex justify-end space-x-3 border-t pt-4"},m&&g&&F(df,{onClick:function(){return b("choose-action")},disabled:le,className:"border-border-default bg-bg-surface text-fg-secondary hover:bg-interactive-hover rounded-md border px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},c("common.back")),F(df,{onClick:be,disabled:!ve,className:"bg-accent text-fg-on-accent hover:!bg-accent-hover flex items-center space-x-2 rounded-md border border-transparent px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},le&&F(hy,{size:"sm"}),F("span",null,c(le?"protect.applying":"protect.apply")))))};return F(kb,{open:null!=r&&r,title:function(){switch(y){case"unlock":return c("protect.encrypted.title");case"choose-action":return c("protect.modifyProtection.title");case"remove-protection":return c("protect.removeProtection.title");default:return c("protect.title")}}(),onClose:s,onExited:l,className:"md:w-[36rem]"},function(){switch(y){case"unlock":return F("div",{className:"space-y-5"},F("p",{className:"text-fg-secondary text-sm"},c("protect.encrypted.description")),F("div",null,F("label",{className:"text-fg-primary mb-2 block text-sm font-medium"},c("protect.encrypted.enterOwnerPassword")),F("div",{className:"relative"},F("input",{type:k?"text":"password",value:x,onInput:function(e){return C(e.target.value)},placeholder:c("protect.ownerPassword.placeholder"),className:"border-border-default bg-bg-input text-fg-primary focus:border-accent focus:ring-accent w-full rounded-md border px-3 py-2 pr-10 text-sm focus:outline-none focus:ring-1",onKeyDown:function(e){"Enter"===e.key&&x&&ye()}}),F("button",{type:"button",onClick:function(){return S(!k)},className:"text-fg-muted hover:text-fg-secondary absolute right-2 top-1/2 -translate-y-1/2"},F(lf,{icon:k?"eye-off":"eye",className:"h-4 w-4"}))),R&&F("p",{className:"text-state-error mt-2 text-xs"},R)),F(Wb,{permissions:p,translate:c}),F("div",{className:"border-border-subtle flex justify-end space-x-3 border-t pt-4"},F(df,{onClick:ye,disabled:!x||A,className:"bg-accent text-fg-on-accent hover:!bg-accent-hover flex items-center space-x-2 rounded-md border border-transparent px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},A&&F(hy,{size:"sm"}),F("span",null,c("protect.encrypted.unlockAndEdit")))));case"choose-action":return F("div",{className:"space-y-5"},F("p",{className:"text-fg-secondary text-sm"},c("protect.modifyProtection.description")),F("div",{className:"space-y-3"},F("button",{type:"button",onClick:function(){return b("edit-protection")},className:"border-border-default hover:border-accent hover:bg-bg-subtle flex w-full items-center rounded-lg border p-4 text-left transition-colors"},F("div",{className:"bg-accent/10 mr-4 rounded-full p-2"},F(lf,{icon:"lock",size:20,className:"text-accent"})),F("div",null,F("span",{className:"text-fg-primary block font-medium"},c("protect.modifyProtection.changeOption")),F("span",{className:"text-fg-muted text-sm"},c("protect.modifyProtection.changeDescription")))),F("button",{type:"button",onClick:function(){return b("remove-protection")},className:"border-border-default hover:border-state-error hover:bg-state-error-light flex w-full items-center rounded-lg border p-4 text-left transition-colors"},F("div",{className:"bg-state-error-light mr-4 rounded-full p-2"},F(lf,{icon:"unlock",size:20,className:"text-state-error"})),F("div",null,F("span",{className:"text-fg-primary block font-medium"},c("protect.modifyProtection.removeOption")),F("span",{className:"text-fg-muted text-sm"},c("protect.modifyProtection.removeDescription"))))),F("div",{className:"border-border-subtle flex justify-end border-t pt-4"},F(df,{onClick:s,className:"border-border-default bg-bg-surface text-fg-secondary hover:bg-interactive-hover rounded-md border px-4 py-2 text-sm"},c("protect.cancel"))));case"remove-protection":return F("div",{className:"space-y-5"},F("div",{className:"bg-state-warning-light flex items-start space-x-3 rounded-lg p-4"},F(lf,{icon:"alertTriangle",className:"text-state-warning mt-0.5 h-5 w-5 flex-shrink-0"}),F("div",null,F("p",{className:"text-fg-primary font-medium"},c("protect.removeProtection.warning")),F("p",{className:"text-fg-secondary mt-1 text-sm"},c("protect.removeProtection.description")))),ue&&F("div",{className:"bg-state-error-light flex items-start space-x-2 rounded-md p-3"},F(lf,{icon:"alertTriangle",className:"text-state-error mt-0.5 h-4 w-4 flex-shrink-0"}),F("p",{className:"text-state-error text-sm"},ue)),F("div",{className:"border-border-subtle flex justify-end space-x-3 border-t pt-4"},F(df,{onClick:function(){return b("choose-action")},disabled:le,className:"border-border-default bg-bg-surface text-fg-secondary hover:bg-interactive-hover rounded-md border px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},c("common.back")),F(df,{onClick:we,disabled:le,className:"bg-state-error text-fg-on-accent hover:bg-state-error/90 flex items-center space-x-2 rounded-md border border-transparent px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},le&&F(hy,{size:"sm"}),F("span",null,c("protect.removeProtection.confirm")))));default:return xe()}}())}function Gb(e){var t,n,o,i=e.documentId,r=ja(i).translate,a=Zr().provides,s=Oo(i),l=null==s?void 0:s.document,c=null!==(t=null==l?void 0:l.isEncrypted)&&void 0!==t&&t,d=null!==(n=null==l?void 0:l.isOwnerUnlocked)&&void 0!==n&&n,u=((null!==(o=null==l?void 0:l.permissions)&&void 0!==o?o:Zt.AllowAll)&Zt.AllowAll)!==Zt.AllowAll,h=c&&!d&&u,m=ze(function(){null==a||a.forDocument(i).disableOverlay("unlock-owner-overlay")},[i,a]),g=ze(function(){null==a||a.forDocument(i).disableOverlay("unlock-owner-overlay"),null==a||a.forDocument(i).openModal("view-permissions-modal")},[i,a]);return h?F("div",{className:""},F("div",{className:"bg-bg-surface border-border-default flex max-w-sm items-start gap-3 rounded-lg border p-4 shadow-lg"},F("div",{className:"bg-accent/10 flex-shrink-0 rounded-full p-2"},F(lf,{icon:"lock",size:20,className:"text-accent"})),F("div",{className:"min-w-0 flex-1"},F("h3",{className:"text-fg-primary text-sm font-semibold"},r("security.protected.title")),F("p",{className:"text-fg-secondary mt-1 text-xs leading-relaxed"},r("security.protected.description")),F("button",{type:"button",onClick:g,className:"text-accent hover:text-accent-hover mt-2 text-xs font-medium"},r("security.protected.viewPermissions"))),F("button",{type:"button",onClick:m,className:"text-fg-muted hover:text-fg-secondary -mr-1 -mt-1 flex-shrink-0 p-1","aria-label":r("common.close")},F(lf,{icon:"x",size:16})))):null}function Vb(e){var t,n,o=e.documentId,i=e.isOpen,r=e.onClose,a=e.onExited,s=ja(o).translate,l=Oo(o),c=va().provides,d=v(Se(""),2),u=d[0],h=d[1],m=v(Se(!1),2),g=m[0],p=m[1],f=v(Se(!1),2),y=f[0],b=f[1],w=v(Se(null),2),x=w[0],C=w[1],I=null==l?void 0:l.document,k=null!==(t=null==I?void 0:I.permissions)&&void 0!==t?t:0,S=null!==(n=null==I?void 0:I.isOwnerUnlocked)&&void 0!==n&&n;Ae(function(){i&&(h(""),p(!1),b(!1),C(null))},[i]);var M=function(){c&&u&&(b(!0),C(null),c.unlockOwnerPermissions(o,u).wait(function(e){b(!1),e?h(""):C(s("security.unlock.invalidPassword"))},function(e){var t,n;b(!1),C(null!==(t=null===(n=e.reason)||void 0===n?void 0:n.message)&&void 0!==t?t:s("security.unlock.failed"))}))};return F(kb,{open:null!=i&&i,title:s("security.viewPermissions.title"),onClose:r,onExited:a,className:"md:w-[32rem]"},F("div",{className:"space-y-5"},F("p",{className:"text-fg-secondary text-sm"},s("security.viewPermissions.description")),!S&&F("div",null,F("label",{className:"text-fg-primary mb-2 block text-sm font-medium"},s("security.unlock.label")),F("div",{className:"relative"},F("input",{type:g?"text":"password",value:u,onInput:function(e){return h(e.target.value)},placeholder:s("security.unlock.placeholder"),className:"border-border-default bg-bg-input text-fg-primary focus:border-accent focus:ring-accent w-full rounded-md border px-3 py-2 pr-10 text-sm focus:outline-none focus:ring-1",onKeyDown:function(e){"Enter"===e.key&&u&&M()}}),F("button",{type:"button",onClick:function(){return p(!g)},className:"text-fg-muted hover:text-fg-secondary absolute right-2 top-1/2 -translate-y-1/2"},F(lf,{icon:g?"eye-off":"eye",className:"h-4 w-4"}))),x&&F("p",{className:"text-state-error mt-2 text-xs"},x),F(df,{onClick:M,disabled:!u||y,className:"bg-accent text-fg-on-accent hover:!bg-accent-hover mt-3 flex items-center space-x-2 rounded-md px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},y&&F(hy,{size:"sm"}),F("span",null,s("security.unlock.button")))),S&&F("div",{className:"bg-state-success-light flex items-center space-x-2 rounded-md p-3"},F(lf,{icon:"check",className:"text-state-success h-4 w-4 flex-shrink-0"}),F("p",{className:"text-fg-secondary text-sm"},s("security.unlock.success"))),F(Wb,{permissions:k,translate:s}),F("div",{className:"border-border-subtle flex justify-end border-t pt-4"},F(df,{onClick:r,className:"border-border-default bg-bg-surface text-fg-secondary hover:bg-interactive-hover rounded-md border px-4 py-2 text-sm"},s("common.close")))))}var Kb={documentManager:{},commands:{commands:Db},i18n:{defaultLocale:"en",locales:[{code:"en",name:"English",translations:{search:{placeholder:"Search",caseSensitive:"Case sensitive",wholeWord:"Whole word",resultsFound:"{count} results found",page:"Page {page}"},zoom:{in:"Zoom In",out:"Zoom Out",fitWidth:"Fit to Width",fitPage:"Fit to Page",marquee:"Marquee Zoom",menu:"Zoom Menu",level:"Zoom Level ({level}%)",dragTip:"Drag to select area to zoom"},pan:{toggle:"Toggle Pan Mode"},pointer:{toggle:"Toggle Pointer Mode"},capture:{screenshot:"Screenshot",dragTip:"Drag to select area to capture",title:"Screenshot Preview",download:"Download",cancel:"Cancel"},document:{menu:"Document Menu",open:"Open",close:"Close",print:"Print",protect:"Security",export:"Export",fullscreen:"Fullscreen",loading:"Loading document..."},emptyState:{title:"No Documents Open",description:"Open a PDF document to get started.",descriptionMulti:"You can view multiple documents using tabs.",openButton:"Open Document",supportedFormats:"Supported format: PDF"},passwordPrompt:{title:"Password Required",required:"This document is password protected. Please enter the password to open it.",incorrect:"The password you entered was incorrect. Please try again.",incorrectWarning:"Incorrect password. Please check and try again.",label:"Password",placeholder:"Enter document password",open:"Open",opening:"Opening...",cancel:"Cancel",close:"Close"},documentError:{title:"Error loading document",unknown:"An unknown error occurred",errorCode:"Error Code: {code}",close:"Close Document"},panel:{sidebar:"Sidebar",search:"Search",comment:"Comment",thumbnails:"Thumbnails",outline:"Outline",annotationStyle:"Annotation Style",redaction:"Redaction Sidebar"},menu:{viewControls:"View Controls",zoomControls:"Zoom Controls",moreOptions:"More Options"},outline:{title:"Outline",loading:"Loading outline...",noOutline:"No outline available",noBookmarks:"This document doesn't contain bookmarks"},page:{settings:"Page Settings",single:"Single Page",twoOdd:"Two Page (Odd)",twoEven:"Two Page (Even)",vertical:"Vertical",horizontal:"Horizontal",spreadMode:"Spread Mode",scrollLayout:"Scroll Layout",rotation:"Page Rotation",next:"Next Page",previous:"Previous Page"},rotate:{clockwise:"Rotate Clockwise",counterClockwise:"Rotate Counter-Clockwise"},selection:{copy:"Copy Selection"},mode:{view:"View",annotate:"Annotate",shapes:"Shapes",redact:"Redact"},annotation:{text:"Text",highlight:"Highlight",strikeout:"Strikethrough",underline:"Underline",squiggly:"Squiggly",rectangle:"Rectangle",circle:"Circle",line:"Line",arrow:"Arrow",polygon:"Polygon",polyline:"Polyline",ink:"Ink",stamp:"Stamp",freeText:"Free Text",square:"Square",style:"Annotation Style",styles:"{type} Styles",defaults:"{type} Defaults",color:"Color",opacity:"Opacity",blendMode:"Blend mode",strokeWidth:"Stroke width",strokeColor:"Stroke color",borderStyle:"Border style",fillColor:"Fill color",fontSize:"Font size",fontFamily:"Font",textAlign:"Text alignment",verticalAlign:"Vertical alignment",lineEnding:"Line ending",lineStart:"Line start",lineEnd:"Line end",font:"Font",fontColor:"Font color",backgroundColor:"Background color",noStyles:"There are no styles for this annotation.",noStylesStamp:"There are no styles for stamps.",selectAnnotation:"Select an annotation to see styles",deleteSelected:"Delete selected annotation",deleteAllSelected:"Delete Selected",multiSelect:"{count} annotations selected",group:"Group",ungroup:"Ungroup",moreTools:"More Tools",addLink:"Add Link",removeLink:"Remove Link",gotoLink:"Go to Link",comment:"Comment",redact:"Redact",overlayText:"Overlay Text",overlayTextPlaceholder:"e.g., REDACTED",rotation:"Rotation"},redaction:{redact:"Redact",area:"Redact Area",text:"Redact Text",apply:"Apply Redaction",applyAll:"Apply All",clearAll:"Clear All",deleteSelected:"Delete selected redaction",commitSelected:"Apply selected redaction",emptyState:"No pending redactions",panel:{title:"Redactions",itemCount:"{count} pending redaction",itemCountPlural:"{count} pending redactions",clearAll:"Clear All",redactAll:"Redact All"}},history:{undo:"Undo",redo:"Redo"},comments:{page:"Page {page}",commentCount:"{count} comment",commentCountPlural:"{count} comments",addComment:"Add comment...",addReply:"Add reply...",save:"Save",cancel:"Cancel",edit:"Edit",delete:"Delete",showMore:"more",showLess:"less",emptyState:"Add annotations to be able to comment on them."},blendMode:{normal:"Normal",multiply:"Multiply",screen:"Screen",overlay:"Overlay",darken:"Darken",lighten:"Lighten",colorDodge:"Color Dodge",colorBurn:"Color Burn",hardLight:"Hard Light",softLight:"Soft Light",difference:"Difference",exclusion:"Exclusion",hue:"Hue",saturation:"Saturation",color:"Color",luminosity:"Luminosity"},print:{title:"Print Settings",loading:"Preparing document...",pages:"Pages to print",all:"All pages",current:"Current page ({currentPage})",specify:"Specify pages",specifyEG:"e.g., 1-3, 5, 8-10",total:"Total pages in document: {totalPages}",annotation:"Include annotations",printing:"Printing...",print:"Print",cancel:"Cancel"},protect:{title:"Protect Document",cancel:"Cancel",apply:"Apply Protection",applying:"Applying...",applyFailed:"Failed to apply protection. Please try again.",removeFailed:"Failed to remove protection. Please try again.",passwordMismatch:"Passwords do not match",noProtectionSelected:"Select at least one protection option to apply.",bothPasswordsNote:"Users who open with the document password will have restricted permissions. Use the owner password to unlock full access.",openPassword:{title:"Require password to open",description:"Users must enter a password to view this document.",label:"Document Password",placeholder:"Enter password",confirm:"Confirm Password",confirmPlaceholder:"Confirm password"},ownerPassword:{label:"Owner Password",placeholder:"Enter owner password",confirm:"Confirm Owner Password",confirmPlaceholder:"Confirm owner password"},permissions:{title:"Restrict permissions",description:"Limit what users can do with this document.",allowedActions:"Allowed actions",print:"Print",printHighQuality:"Print high quality",copy:"Copy content",accessibility:"Extract for accessibility",modify:"Modify content",annotations:"Add/modify annotations & comments",fillForms:"Fill forms & sign",assemble:"Assemble & extract pages"},encrypted:{title:"Document is Protected",description:"This document is protected by the owner. Enter the owner password to modify security settings.",enterOwnerPassword:"Enter Owner Password to Modify",unlockAndEdit:"Unlock & Edit"},modifyProtection:{title:"Modify Protection",description:"Choose how you want to modify the document protection.",changeOption:"Change Passwords or Permissions",changeDescription:"Update the document password or permission settings.",removeOption:"Remove All Protection",removeDescription:"Remove password protection from this document."},removeProtection:{title:"Remove Protection",warning:"Are you sure you want to remove protection?",description:"This will remove all password protection from the document. Anyone will be able to open and modify it.",confirm:"Remove Protection"}},security:{protected:{title:"This Document is Protected",description:"This file is protected and some features may be disabled. Go to Security in the document menu to view or unlock permissions.",viewPermissions:"View permissions"},viewPermissions:{title:"Document Permissions",description:"This file is restricted by the owner and requires a password to unlock certain actions.",restrictedActions:"Restricted Actions"},unlock:{label:"Enter Owner Password to Unlock File",placeholder:"Enter owner password",button:"Unlock file",invalidPassword:"Invalid password. Please try again.",failed:"Failed to unlock. Please try again.",success:"Owner permissions unlocked! You now have full access."}},common:{close:"Close",back:"Back",cancel:"Cancel"},link:{title:"Insert Link",url:"URL",page:"Page",enterUrl:"Enter URL",enterPage:"Enter Page Number",pageRange:"Page 1 to {totalPages}",link:"Link"}}},{code:"nl",name:"Nederlands",translations:{search:{placeholder:"Zoeken",caseSensitive:"Hoofdlettergevoelig",wholeWord:"Heel woord",resultsFound:"{count} resultaten gevonden",page:"Pagina {page}"},zoom:{in:"Inzoomen",out:"Uitzoomen",fitWidth:"Aanbreedte aanpassen",fitPage:"Aan pagina aanpassen",marquee:"Lijstzoom",menu:"Zoommenu",level:"Zoomniveau ({level}%)",dragTip:"Drag to select area to zoom"},pan:{toggle:"Pan-modus wisselen"},pointer:{toggle:"Aanwijzermodus wisselen"},capture:{screenshot:"Schermafbeelding",dragTip:"Sleep om een gebied te selecteren om vast te leggen",title:"Screenshot voorbeeld",download:"Downloaden",cancel:"Annuleren"},document:{menu:"Documentmenu",open:"Openen",close:"Sluiten",print:"Afdrukken",protect:"Beveiliging",export:"Exporteren",fullscreen:"Volledig scherm",loading:"Document laden..."},emptyState:{title:"Geen documenten geopend",description:"Open een PDF-document om te beginnen.",descriptionMulti:"U kunt meerdere documenten bekijken met tabs.",openButton:"Document openen",supportedFormats:"Ondersteund formaat: PDF"},passwordPrompt:{title:"Wachtwoord vereist",required:"Dit document is beveiligd met een wachtwoord. Voer het wachtwoord in om te openen.",incorrect:"Het ingevoerde wachtwoord was onjuist. Probeer het opnieuw.",incorrectWarning:"Onjuist wachtwoord. Controleer en probeer opnieuw.",label:"Wachtwoord",placeholder:"Voer documentwachtwoord in",open:"Openen",opening:"Openen...",cancel:"Annuleren",close:"Sluiten"},documentError:{title:"Fout bij laden van document",unknown:"Er is een onbekende fout opgetreden",errorCode:"Foutcode: {code}",close:"Document sluiten"},panel:{sidebar:"Zijbalk",search:"Zoeken",comment:"Opmerking",thumbnails:"Miniaturen",outline:"Overzicht",annotationStyle:"Annotatiestijl",redaction:"Redactie Zijbalk"},menu:{viewControls:"Weergave-instellingen",zoomControls:"Zoom-instellingen",moreOptions:"Meer opties"},outline:{title:"Overzicht",loading:"Overzicht laden...",noOutline:"Geen overzicht beschikbaar",noBookmarks:"Dit document bevat geen bladwijzers"},page:{settings:"Pagina-instellingen",single:"Enkele pagina",twoOdd:"Twee pagina's (Oneven)",twoEven:"Twee pagina's (Even)",vertical:"Verticaal",horizontal:"Horizontaal",spreadMode:"Spreidingsmodus",scrollLayout:"Scrollindeling",rotation:"Paginarotatie",next:"Volgende pagina",previous:"Vorige pagina"},rotate:{clockwise:"Met de klok mee draaien",counterClockwise:"Tegen de klok in draaien"},selection:{copy:"Selectie kopiëren"},mode:{view:"Weergave",annotate:"Annoteren",shapes:"Vormen",redact:"Redigeren"},annotation:{text:"Tekst",highlight:"Markeren",strikeout:"Doorhalen",underline:"Onderstrepen",squiggly:"Golflijn",rectangle:"Rechthoek",circle:"Cirkel",line:"Lijn",arrow:"Pijl",polygon:"Veelhoek",polyline:"Polylijn",ink:"Inkt",stamp:"Stempel",freeText:"Vrije tekst",square:"Vierkant",style:"Annotatiestijl",styles:"{type} stijlen",defaults:"{type} standaardwaarden",color:"Kleur",opacity:"Dekking",blendMode:"Overvloeimodus",strokeWidth:"Lijndikte",strokeColor:"Lijnkleur",borderStyle:"Randstijl",fillColor:"Vulkleur",fontSize:"Lettergrootte",fontFamily:"Lettertype",textAlign:"Tekstuitlijning",verticalAlign:"Verticale uitlijning",lineEnding:"Lijneinde",lineStart:"Lijnbegin",lineEnd:"Lijneinde",font:"Lettertype",fontColor:"Tekstkleur",backgroundColor:"Achtergrondkleur",noStyles:"Er zijn geen stijlen voor deze annotatie.",noStylesStamp:"Er zijn geen stijlen voor stempels.",selectAnnotation:"Selecteer een annotatie om stijlen te zien",deleteSelected:"Geselecteerde annotatie verwijderen",deleteAllSelected:"Selectie verwijderen",multiSelect:"{count} annotaties geselecteerd",group:"Groeperen",ungroup:"Groepering opheffen",moreTools:"Meer gereedschappen",addLink:"Link toevoegen",removeLink:"Link verwijderen",gotoLink:"Ga naar link",comment:"Opmerking",redact:"Redigeren",overlayText:"Overlaytekst",overlayTextPlaceholder:"bijv. GEREDIGEERD",rotation:"Rotatie"},redaction:{redact:"Redigeren",area:"Gebied redigeren",text:"Tekst redigeren",apply:"Redactie toepassen",applyAll:"Alles toepassen",clearAll:"Alles wissen",deleteSelected:"Geselecteerde redactie verwijderen",commitSelected:"Geselecteerde redactie toepassen",emptyState:"Geen openstaande redacties",panel:{title:"Redacties",itemCount:"{count} openstaande redactie",itemCountPlural:"{count} openstaande redacties",clearAll:"Alles wissen",redactAll:"Alles redigeren"}},history:{undo:"Ongedaan maken",redo:"Opnieuw doen"},comments:{page:"Pagina {page}",commentCount:"{count} opmerking",commentCountPlural:"{count} opmerkingen",addComment:"Opmerking toevoegen...",addReply:"Antwoord toevoegen...",save:"Opslaan",cancel:"Annuleren",edit:"Bewerken",delete:"Verwijderen",showMore:"meer",showLess:"minder",emptyState:"Voeg annotaties toe om erop te kunnen reageren."},blendMode:{normal:"Normaal",multiply:"Vermenigvuldigen",screen:"Bleken",overlay:"Bedekken",darken:"Donkerder",lighten:"Lichter",colorDodge:"Kleur tegenhouden",colorBurn:"Kleur doordrukken",hardLight:"Hard licht",softLight:"Zacht licht",difference:"Verschil",exclusion:"Uitsluiting",hue:"Kleurtoon",saturation:"Verzadiging",color:"Kleur",luminosity:"Helderheid"},print:{title:"Afdrukinstellingen",loading:"Document voorbereiden...",pages:"Af te drukken pagina's",all:"Alle pagina's",current:"Huidige pagina ({currentPage})",specify:"Pagina's",specifyEG:"bijv. 1-3, 5, 8-10",total:"Totaal aantal pagina's in document: {totalPages}",annotation:"Inclusief annotaties",printing:"Afdrukken...",print:"Afdrukken",cancel:"Annuleren"},protect:{title:"Document beveiligen",cancel:"Annuleren",apply:"Beveiliging toepassen",applying:"Bezig met toepassen...",applyFailed:"Beveiliging kon niet worden toegepast. Probeer het opnieuw.",removeFailed:"Beveiliging kon niet worden verwijderd. Probeer het opnieuw.",passwordMismatch:"Wachtwoorden komen niet overeen",noProtectionSelected:"Selecteer minimaal één beveiligingsoptie.",bothPasswordsNote:"Gebruikers die openen met het documentwachtwoord hebben beperkte rechten. Gebruik het eigenaarswachtwoord voor volledige toegang.",openPassword:{title:"Wachtwoord vereist om te openen",description:"Gebruikers moeten een wachtwoord invoeren om dit document te bekijken.",label:"Documentwachtwoord",placeholder:"Wachtwoord invoeren",confirm:"Wachtwoord bevestigen",confirmPlaceholder:"Wachtwoord bevestigen"},ownerPassword:{label:"Eigenaarswachtwoord",placeholder:"Eigenaarswachtwoord invoeren",confirm:"Eigenaarswachtwoord bevestigen",confirmPlaceholder:"Eigenaarswachtwoord bevestigen"},permissions:{title:"Rechten beperken",description:"Beperk wat gebruikers met dit document kunnen doen.",allowedActions:"Toegestane acties",print:"Afdrukken",printHighQuality:"Hoge kwaliteit afdrukken",copy:"Inhoud kopiëren",accessibility:"Extraheren voor toegankelijkheid",modify:"Inhoud wijzigen",annotations:"Annotaties & opmerkingen toevoegen/wijzigen",fillForms:"Formulieren invullen & ondertekenen",assemble:"Document samenstellen & pagina's extraheren"},encrypted:{title:"Document is beveiligd",description:"Dit document is beveiligd door de eigenaar. Voer het eigenaarswachtwoord in om beveiligingsinstellingen te wijzigen.",enterOwnerPassword:"Voer eigenaarswachtwoord in om te wijzigen",unlockAndEdit:"Ontgrendelen & Bewerken"},modifyProtection:{title:"Beveiliging wijzigen",description:"Kies hoe u de documentbeveiliging wilt wijzigen.",changeOption:"Wachtwoorden of rechten wijzigen",changeDescription:"Update het documentwachtwoord of rechtinstellingen.",removeOption:"Alle beveiliging verwijderen",removeDescription:"Verwijder wachtwoordbeveiliging van dit document."},removeProtection:{title:"Beveiliging verwijderen",warning:"Weet u zeker dat u de beveiliging wilt verwijderen?",description:"Dit verwijdert alle wachtwoordbeveiliging van het document. Iedereen kan het openen en wijzigen.",confirm:"Beveiliging verwijderen"}},security:{protected:{title:"Dit document is beveiligd",description:"Dit bestand is beveiligd en sommige functies zijn mogelijk uitgeschakeld. Ga naar Beveiliging in het documentmenu om rechten te bekijken of te ontgrendelen.",viewPermissions:"Rechten bekijken"},viewPermissions:{title:"Documentrechten",description:"Dit bestand is beperkt door de eigenaar en vereist een wachtwoord om bepaalde acties te ontgrendelen.",restrictedActions:"Beperkte acties"},unlock:{label:"Voer eigenaarswachtwoord in om te ontgrendelen",placeholder:"Eigenaarswachtwoord invoeren",button:"Bestand ontgrendelen",invalidPassword:"Ongeldig wachtwoord. Probeer het opnieuw.",failed:"Ontgrendelen mislukt. Probeer het opnieuw.",success:"Eigenaarrechten ontgrendeld! U heeft nu volledige toegang."}},common:{close:"Sluiten",back:"Terug",cancel:"Annuleren"},link:{title:"Link invoegen",url:"URL",page:"Pagina",enterUrl:"URL invoeren",enterPage:"Paginanummer invoeren",pageRange:"Pagina 1 tot {totalPages}",link:"Koppelen"}}},{code:"de",name:"Deutsch",translations:{search:{placeholder:"Suchen",caseSensitive:"Groß-/Kleinschreibung",wholeWord:"Ganzes Wort",resultsFound:"{count} Ergebnisse gefunden",page:"Seite {page}"},zoom:{in:"Vergrößern",out:"Verkleinern",fitWidth:"An Breite anpassen",fitPage:"An Seite anpassen",marquee:"Laufrahmen-Zoom",menu:"Zoom-Menü",level:"Zoomstufe ({level}%)",dragTip:"Drag to select area to zoom"},pan:{toggle:"Verschieben-Modus umschalten"},pointer:{toggle:"Zeiger-Modus umschalten"},capture:{screenshot:"Screenshot",dragTip:"Ziehen Sie, um den Bereich zum Erfassen auszuwählen",title:"Screenshot-Vorschau",download:"Herunterladen",cancel:"Abbrechen"},document:{menu:"Dokument-Menü",open:"Öffnen",close:"Schließen",print:"Drucken",protect:"Sicherheit",export:"Exportieren",fullscreen:"Vollbild",loading:"Dokument wird geladen..."},emptyState:{title:"Keine Dokumente geöffnet",description:"Öffnen Sie ein PDF-Dokument, um zu beginnen.",descriptionMulti:"Sie können mehrere Dokumente mit Tabs anzeigen.",openButton:"Dokument öffnen",supportedFormats:"Unterstütztes Format: PDF"},passwordPrompt:{title:"Passwort erforderlich",required:"Dieses Dokument ist passwortgeschützt. Bitte geben Sie das Passwort ein.",incorrect:"Das eingegebene Passwort war falsch. Bitte versuchen Sie es erneut.",incorrectWarning:"Falsches Passwort. Bitte überprüfen und erneut versuchen.",label:"Passwort",placeholder:"Dokumentpasswort eingeben",open:"Öffnen",opening:"Öffnen...",cancel:"Abbrechen",close:"Schließen"},documentError:{title:"Fehler beim Laden des Dokuments",unknown:"Ein unbekannter Fehler ist aufgetreten",errorCode:"Fehlercode: {code}",close:"Dokument schließen"},panel:{sidebar:"Seitenleiste",search:"Suchen",comment:"Kommentar",thumbnails:"Miniaturansichten",outline:"Gliederung",annotationStyle:"Anmerkungsstil",redaction:"Schwärzungs-Seitenleiste"},menu:{viewControls:"Ansichtseinstellungen",zoomControls:"Zoom-Einstellungen",moreOptions:"Weitere Optionen"},outline:{title:"Gliederung",loading:"Gliederung wird geladen...",noOutline:"Keine Gliederung verfügbar",noBookmarks:"Dieses Dokument enthält keine Lesezeichen"},page:{settings:"Seiteneinstellungen",single:"Einzelseite",twoOdd:"Zwei Seiten (Ungerade)",twoEven:"Zwei Seiten (Gerade)",vertical:"Vertikal",horizontal:"Horizontal",spreadMode:"Doppelseiten-Modus",scrollLayout:"Scroll-Layout",rotation:"Seitendrehung",next:"Nächste Seite",previous:"Vorherige Seite"},rotate:{clockwise:"Im Uhrzeigersinn drehen",counterClockwise:"Gegen den Uhrzeigersinn drehen"},selection:{copy:"Auswahl kopieren"},mode:{view:"Ansicht",annotate:"Annotieren",shapes:"Formen",redact:"Schwärzen"},annotation:{text:"Text",highlight:"Markieren",strikeout:"Durchstreichen",underline:"Unterstreichen",squiggly:"Wellenlinie",rectangle:"Rechteck",circle:"Kreis",line:"Linie",arrow:"Pfeil",polygon:"Polygon",polyline:"Polylinie",ink:"Freihand",stamp:"Stempel",freeText:"Freitext",square:"Quadrat",style:"Anmerkungsstil",styles:"{type}-Stile",defaults:"{type}-Standardwerte",color:"Farbe",opacity:"Deckkraft",blendMode:"Mischmodus",strokeWidth:"Strichstärke",strokeColor:"Strichfarbe",borderStyle:"Rahmenstil",fillColor:"Füllfarbe",fontSize:"Schriftgröße",fontFamily:"Schriftart",textAlign:"Textausrichtung",verticalAlign:"Vertikale Ausrichtung",lineEnding:"Linienende",lineStart:"Linienanfang",lineEnd:"Linienende",font:"Schriftart",fontColor:"Schriftfarbe",backgroundColor:"Hintergrundfarbe",noStyles:"Für diese Anmerkung gibt es keine Stile.",noStylesStamp:"Für Stempel gibt es keine Stile.",selectAnnotation:"Wählen Sie eine Anmerkung aus, um Stile anzuzeigen",deleteSelected:"Ausgewählte Anmerkung löschen",deleteAllSelected:"Ausgewählte löschen",multiSelect:"{count} Anmerkungen ausgewählt",group:"Gruppieren",ungroup:"Gruppierung aufheben",moreTools:"Weitere Werkzeuge",addLink:"Link hinzufügen",removeLink:"Link entfernen",gotoLink:"Zum Link gehen",comment:"Kommentar",redact:"Schwärzen",overlayText:"Überlagerungstext",overlayTextPlaceholder:"z.B. GESCHWÄRZT",rotation:"Drehung"},redaction:{redact:"Schwärzen",area:"Bereich schwärzen",text:"Text schwärzen",apply:"Schwärzung anwenden",applyAll:"Alle anwenden",clearAll:"Alle löschen",deleteSelected:"Ausgewählte Schwärzung löschen",commitSelected:"Ausgewählte Schwärzung anwenden",emptyState:"Keine ausstehenden Schwärzungen",panel:{title:"Schwärzungen",itemCount:"{count} ausstehende Schwärzung",itemCountPlural:"{count} ausstehende Schwärzungen",clearAll:"Alle löschen",redactAll:"Alle schwärzen"}},history:{undo:"Rückgängig",redo:"Wiederholen"},comments:{page:"Seite {page}",commentCount:"{count} Kommentar",commentCountPlural:"{count} Kommentare",addComment:"Kommentar hinzufügen...",addReply:"Antwort hinzufügen...",save:"Speichern",cancel:"Abbrechen",edit:"Bearbeiten",delete:"Löschen",showMore:"mehr",showLess:"weniger",emptyState:"Fügen Sie Anmerkungen hinzu, um sie kommentieren zu können."},blendMode:{normal:"Normal",multiply:"Multiplizieren",screen:"Negativ multiplizieren",overlay:"Ineinanderkopieren",darken:"Abdunkeln",lighten:"Aufhellen",colorDodge:"Farbig abwedeln",colorBurn:"Farbig nachbelichten",hardLight:"Hartes Licht",softLight:"Weiches Licht",difference:"Differenz",exclusion:"Ausschluss",hue:"Farbton",saturation:"Sättigung",color:"Farbe",luminosity:"Luminanz"},print:{title:"Druckeinstellungen",loading:"Dokument wird vorbereitet...",pages:"Zu druckende Seiten",all:"Alle Seiten",current:"Aktuelle Seite ({currentPage})",specify:"Seiten angeben",specifyEG:"z.B. 1-3, 5, 8-10",total:"Gesamtseitenzahl im Dokument: {totalPages}",annotation:"Anmerkungen einbeziehen",printing:"Drucken...",print:"Drucken",cancel:"Abbrechen"},protect:{title:"Dokument schützen",cancel:"Abbrechen",apply:"Schutz anwenden",applying:"Wird angewendet...",applyFailed:"Schutz konnte nicht angewendet werden. Bitte versuchen Sie es erneut.",removeFailed:"Schutz konnte nicht entfernt werden. Bitte versuchen Sie es erneut.",passwordMismatch:"Passwörter stimmen nicht überein",noProtectionSelected:"Wählen Sie mindestens eine Schutzoption aus.",bothPasswordsNote:"Benutzer, die das Dokumentpasswort eingeben, haben eingeschränkte Berechtigungen. Verwenden Sie das Eigentümerpasswort für vollen Zugriff.",openPassword:{title:"Passwort zum Öffnen erforderlich",description:"Benutzer müssen ein Passwort eingeben, um dieses Dokument anzuzeigen.",label:"Dokumentpasswort",placeholder:"Passwort eingeben",confirm:"Passwort bestätigen",confirmPlaceholder:"Passwort bestätigen"},ownerPassword:{label:"Eigentümerpasswort",placeholder:"Eigentümerpasswort eingeben",confirm:"Eigentümerpasswort bestätigen",confirmPlaceholder:"Eigentümerpasswort bestätigen"},permissions:{title:"Berechtigungen einschränken",description:"Beschränken Sie, was Benutzer mit diesem Dokument tun können.",allowedActions:"Erlaubte Aktionen",print:"Drucken",printHighQuality:"In hoher Qualität drucken",copy:"Inhalt kopieren",accessibility:"Für Barrierefreiheit extrahieren",modify:"Inhalt ändern",annotations:"Anmerkungen & Kommentare hinzufügen/ändern",fillForms:"Formulare ausfüllen & unterschreiben",assemble:"Dokument zusammenstellen & Seiten extrahieren"},encrypted:{title:"Dokument ist geschützt",description:"Dieses Dokument ist vom Eigentümer geschützt. Geben Sie das Eigentümerpasswort ein, um die Sicherheitseinstellungen zu ändern.",enterOwnerPassword:"Eigentümerpasswort eingeben zum Ändern",unlockAndEdit:"Entsperren & Bearbeiten"},modifyProtection:{title:"Schutz ändern",description:"Wählen Sie, wie Sie den Dokumentschutz ändern möchten.",changeOption:"Passwörter oder Berechtigungen ändern",changeDescription:"Aktualisieren Sie das Dokumentpasswort oder die Berechtigungseinstellungen.",removeOption:"Gesamten Schutz entfernen",removeDescription:"Passwortschutz von diesem Dokument entfernen."},removeProtection:{title:"Schutz entfernen",warning:"Sind Sie sicher, dass Sie den Schutz entfernen möchten?",description:"Dadurch wird der gesamte Passwortschutz vom Dokument entfernt. Jeder kann es öffnen und bearbeiten.",confirm:"Schutz entfernen"}},security:{protected:{title:"Dieses Dokument ist geschützt",description:"Diese Datei ist geschützt und einige Funktionen sind möglicherweise deaktiviert. Gehen Sie zu Sicherheit im Dokumentmenü, um Berechtigungen anzuzeigen oder freizuschalten.",viewPermissions:"Berechtigungen anzeigen"},viewPermissions:{title:"Dokumentberechtigungen",description:"Diese Datei ist vom Eigentümer eingeschränkt und erfordert ein Passwort, um bestimmte Aktionen freizuschalten.",restrictedActions:"Eingeschränkte Aktionen"},unlock:{label:"Eigentümerpasswort eingeben zum Entsperren",placeholder:"Eigentümerpasswort eingeben",button:"Datei entsperren",invalidPassword:"Ungültiges Passwort. Bitte versuchen Sie es erneut.",failed:"Entsperren fehlgeschlagen. Bitte versuchen Sie es erneut.",success:"Eigentümerberechtigungen entsperrt! Sie haben jetzt vollen Zugriff."}},common:{close:"Schließen",back:"Zurück",cancel:"Abbrechen"},link:{title:"Link einfügen",url:"URL",page:"Seite",enterUrl:"URL eingeben",enterPage:"Seitennummer eingeben",pageRange:"Seite 1 bis {totalPages}",link:"Verknüpfen"}}},{code:"fr",name:"Français",translations:{search:{placeholder:"Rechercher",caseSensitive:"Respecter la casse",wholeWord:"Mot entier",resultsFound:"{count} résultats trouvés",page:"Page {page}"},zoom:{in:"Zoom avant",out:"Zoom arrière",fitWidth:"Ajuster à la largeur",fitPage:"Ajuster à la page",marquee:"Zoom de sélection",menu:"Menu Zoom",level:"Niveau de zoom ({level}%)",dragTip:"Drag to select area to zoom"},pan:{toggle:"Basculer le mode déplacement"},pointer:{toggle:"Basculer le mode pointeur"},capture:{screenshot:"Capture d'écran",dragTip:"Faites glisser pour sélectionner la zone à capturer",title:"Aperçu de la capture",download:"Télécharger",cancel:"Annuler"},document:{menu:"Menu Document",open:"Ouvrir",close:"Fermer",print:"Imprimer",protect:"Sécurité",export:"Exporter",fullscreen:"Plein écran",loading:"Chargement du document..."},emptyState:{title:"Aucun document ouvert",description:"Ouvrez un document PDF pour commencer.",descriptionMulti:"Vous pouvez afficher plusieurs documents avec des onglets.",openButton:"Ouvrir un document",supportedFormats:"Format pris en charge : PDF"},passwordPrompt:{title:"Mot de passe requis",required:"Ce document est protégé par mot de passe. Veuillez entrer le mot de passe.",incorrect:"Le mot de passe saisi est incorrect. Veuillez réessayer.",incorrectWarning:"Mot de passe incorrect. Veuillez vérifier et réessayer.",label:"Mot de passe",placeholder:"Entrer le mot de passe du document",open:"Ouvrir",opening:"Ouverture...",cancel:"Annuler",close:"Fermer"},documentError:{title:"Erreur lors du chargement du document",unknown:"Une erreur inconnue est survenue",errorCode:"Code erreur : {code}",close:"Fermer le document"},panel:{sidebar:"Barre latérale",search:"Rechercher",comment:"Commentaire",thumbnails:"Miniatures",outline:"Plan",annotationStyle:"Style d'annotation",redaction:"Barre latérale de caviardage"},menu:{viewControls:"Contrôles d'affichage",zoomControls:"Contrôles de zoom",moreOptions:"Plus d'options"},outline:{title:"Plan",loading:"Chargement du plan...",noOutline:"Aucun plan disponible",noBookmarks:"Ce document ne contient pas de signets"},page:{settings:"Paramètres de page",single:"Page unique",twoOdd:"Deux pages (Impair)",twoEven:"Deux pages (Pair)",vertical:"Vertical",horizontal:"Horizontal",spreadMode:"Mode double page",scrollLayout:"Disposition de défilement",rotation:"Rotation de page",next:"Page suivante",previous:"Page précédente"},rotate:{clockwise:"Tourner dans le sens horaire",counterClockwise:"Tourner dans le sens antihoraire"},selection:{copy:"Copier la sélection"},mode:{view:"Affichage",annotate:"Annoter",shapes:"Formes",redact:"Caviarder"},annotation:{text:"Texte",highlight:"Surligner",strikeout:"Barrer",underline:"Souligner",squiggly:"Ondulé",rectangle:"Rectangle",circle:"Cercle",line:"Ligne",arrow:"Flèche",polygon:"Polygone",polyline:"Polyligne",ink:"Encre",stamp:"Tampon",freeText:"Texte libre",square:"Carré",style:"Style d'annotation",styles:"Styles de {type}",defaults:"Valeurs par défaut de {type}",color:"Couleur",opacity:"Opacité",blendMode:"Mode de fusion",strokeWidth:"Épaisseur du trait",strokeColor:"Couleur du trait",borderStyle:"Style de bordure",fillColor:"Couleur de remplissage",fontSize:"Taille de police",fontFamily:"Police",textAlign:"Alignement du texte",verticalAlign:"Alignement vertical",lineEnding:"Fin de ligne",lineStart:"Début de ligne",lineEnd:"Fin de ligne",font:"Police",fontColor:"Couleur du texte",backgroundColor:"Couleur de fond",noStyles:"Il n'y a pas de styles pour cette annotation.",noStylesStamp:"Il n'y a pas de styles pour les tampons.",selectAnnotation:"Sélectionnez une annotation pour voir les styles",deleteSelected:"Supprimer l'annotation sélectionnée",deleteAllSelected:"Supprimer la sélection",multiSelect:"{count} annotations sélectionnées",group:"Grouper",ungroup:"Dissocier",moreTools:"Plus d'outils",addLink:"Ajouter un lien",removeLink:"Supprimer le lien",gotoLink:"Aller au lien",comment:"Commentaire",redact:"Caviarder",overlayText:"Texte de superposition",overlayTextPlaceholder:"ex: CAVIARDÉ",rotation:"Rotation"},redaction:{redact:"Caviarder",area:"Caviarder la zone",text:"Caviarder le texte",apply:"Appliquer le caviardage",applyAll:"Tout appliquer",clearAll:"Tout effacer",deleteSelected:"Supprimer la rédaction sélectionnée",commitSelected:"Appliquer la rédaction sélectionnée",emptyState:"Aucun caviardage en attente",panel:{title:"Caviardages",itemCount:"{count} caviardage en attente",itemCountPlural:"{count} caviardages en attente",clearAll:"Tout effacer",redactAll:"Tout caviarder"}},history:{undo:"Annuler",redo:"Refaire"},comments:{page:"Page {page}",commentCount:"{count} commentaire",commentCountPlural:"{count} commentaires",addComment:"Ajouter un commentaire...",addReply:"Ajouter une réponse...",save:"Enregistrer",cancel:"Annuler",edit:"Modifier",delete:"Supprimer",showMore:"plus",showLess:"moins",emptyState:"Ajoutez des annotations pour pouvoir les commenter."},blendMode:{normal:"Normal",multiply:"Produit",screen:"Superposition",overlay:"Incrustation",darken:"Obscurcir",lighten:"Éclaircir",colorDodge:"Densité couleur -",colorBurn:"Densité couleur +",hardLight:"Lumière crue",softLight:"Lumière tamisée",difference:"Différence",exclusion:"Exclusion",hue:"Teinte",saturation:"Saturation",color:"Couleur",luminosity:"Luminosité"},print:{title:"Paramètres d'impression",loading:"Préparation du document...",pages:"Pages à imprimer",all:"Toutes les pages",current:"Page actuelle ({currentPage})",specify:"Spécifier les pages",specifyEG:"ex : 1-3, 5, 8-10",total:"Nombre total de pages dans le document : {totalPages}",annotation:"Inclure les annotations",printing:"Impression...",print:"Imprimer",cancel:"Annuler"},protect:{title:"Protéger le document",cancel:"Annuler",apply:"Appliquer la protection",applying:"Application en cours...",applyFailed:"Échec de l'application de la protection. Veuillez réessayer.",removeFailed:"Échec de la suppression de la protection. Veuillez réessayer.",passwordMismatch:"Les mots de passe ne correspondent pas",noProtectionSelected:"Sélectionnez au moins une option de protection.",bothPasswordsNote:"Les utilisateurs qui ouvrent avec le mot de passe du document auront des permissions limitées. Utilisez le mot de passe propriétaire pour un accès complet.",openPassword:{title:"Mot de passe requis pour l'ouverture",description:"Les utilisateurs doivent entrer un mot de passe pour voir ce document.",label:"Mot de passe du document",placeholder:"Entrer le mot de passe",confirm:"Confirmer le mot de passe",confirmPlaceholder:"Confirmer le mot de passe"},ownerPassword:{label:"Mot de passe propriétaire",placeholder:"Entrer le mot de passe propriétaire",confirm:"Confirmer le mot de passe propriétaire",confirmPlaceholder:"Confirmer le mot de passe propriétaire"},permissions:{title:"Restreindre les permissions",description:"Limitez ce que les utilisateurs peuvent faire avec ce document.",allowedActions:"Actions autorisées",print:"Imprimer",printHighQuality:"Imprimer en haute qualité",copy:"Copier le contenu",accessibility:"Extraire pour l'accessibilité",modify:"Modifier le contenu",annotations:"Ajouter/modifier les annotations et commentaires",fillForms:"Remplir les formulaires et signer",assemble:"Assembler le document et extraire les pages"},encrypted:{title:"Document protégé",description:"Ce document est protégé par le propriétaire. Entrez le mot de passe propriétaire pour modifier les paramètres de sécurité.",enterOwnerPassword:"Entrer le mot de passe propriétaire pour modifier",unlockAndEdit:"Déverrouiller & Modifier"},modifyProtection:{title:"Modifier la protection",description:"Choisissez comment vous voulez modifier la protection du document.",changeOption:"Modifier les mots de passe ou les permissions",changeDescription:"Mettre à jour le mot de passe du document ou les paramètres de permissions.",removeOption:"Supprimer toute la protection",removeDescription:"Supprimer la protection par mot de passe de ce document."},removeProtection:{title:"Supprimer la protection",warning:"Êtes-vous sûr de vouloir supprimer la protection ?",description:"Cela supprimera toute la protection par mot de passe du document. Tout le monde pourra l'ouvrir et le modifier.",confirm:"Supprimer la protection"}},security:{protected:{title:"Ce document est protégé",description:"Ce fichier est protégé et certaines fonctionnalités peuvent être désactivées. Allez dans Sécurité dans le menu document pour afficher ou déverrouiller les permissions.",viewPermissions:"Voir les permissions"},viewPermissions:{title:"Permissions du document",description:"Ce fichier est restreint par le propriétaire et nécessite un mot de passe pour débloquer certaines actions.",restrictedActions:"Actions restreintes"},unlock:{label:"Entrer le mot de passe propriétaire pour déverrouiller",placeholder:"Entrer le mot de passe propriétaire",button:"Déverrouiller le fichier",invalidPassword:"Mot de passe invalide. Veuillez réessayer.",failed:"Échec du déverrouillage. Veuillez réessayer.",success:"Permissions propriétaire déverrouillées ! Vous avez maintenant un accès complet."}},common:{close:"Fermer",back:"Retour",cancel:"Annuler"},link:{title:"Insérer un lien",url:"URL",page:"Page",enterUrl:"Entrer l'URL",enterPage:"Entrer le numéro de page",pageRange:"Page 1 à {totalPages}",link:"Lier"}}},{code:"es",name:"Español",translations:{search:{placeholder:"Buscar",caseSensitive:"Distinguir mayúsculas",wholeWord:"Palabra completa",resultsFound:"{count} resultados encontrados",page:"Página {page}"},zoom:{in:"Acercar",out:"Alejar",fitWidth:"Ajustar al ancho",fitPage:"Ajustar a la página",marquee:"Zoom de selección",menu:"Menú de zoom",level:"Nivel de zoom ({level}%)",dragTip:"Drag to select area to zoom"},pan:{toggle:"Alternar modo desplazamiento"},pointer:{toggle:"Alternar modo puntero"},capture:{screenshot:"Captura de pantalla",dragTip:"Arrastre para seleccionar el área a capturar",title:"Vista previa de la captura",download:"Descargar",cancel:"Cancelar"},document:{menu:"Menú del documento",open:"Abrir",close:"Cerrar",print:"Imprimir",protect:"Seguridad",export:"Exportar",fullscreen:"Pantalla completa",loading:"Cargando documento..."},emptyState:{title:"No hay documentos abiertos",description:"Abra un documento PDF para comenzar.",descriptionMulti:"Puede ver varios documentos usando pestañas.",openButton:"Abrir documento",supportedFormats:"Formato compatible: PDF"},passwordPrompt:{title:"Contraseña requerida",required:"Este documento está protegido con contraseña. Por favor, ingrese la contraseña para abrirlo.",incorrect:"La contraseña ingresada es incorrecta. Por favor, inténtelo de nuevo.",incorrectWarning:"Contraseña incorrecta. Por favor, verifique e inténtelo de nuevo.",label:"Contraseña",placeholder:"Ingrese la contraseña del documento",open:"Abrir",opening:"Abriendo...",cancel:"Cancelar",close:"Cerrar"},documentError:{title:"Error al cargar el documento",unknown:"Ha ocurrido un error desconocido",errorCode:"Código de error: {code}",close:"Cerrar documento"},panel:{sidebar:"Barra lateral",search:"Buscar",comment:"Comentario",thumbnails:"Miniaturas",outline:"Esquema",annotationStyle:"Estilo de anotación",redaction:"Barra lateral de redacción"},menu:{viewControls:"Controles de vista",zoomControls:"Controles de zoom",moreOptions:"Más opciones"},outline:{title:"Esquema",loading:"Cargando esquema...",noOutline:"No hay esquema disponible",noBookmarks:"Este documento no contiene marcadores"},page:{settings:"Configuración de página",single:"Página única",twoOdd:"Dos páginas (Impar)",twoEven:"Dos páginas (Par)",vertical:"Vertical",horizontal:"Horizontal",spreadMode:"Modo de doble página",scrollLayout:"Diseño de desplazamiento",rotation:"Rotación de página",next:"Página siguiente",previous:"Página anterior"},rotate:{clockwise:"Rotar en sentido horario",counterClockwise:"Rotar en sentido antihorario"},selection:{copy:"Copiar selección"},mode:{view:"Ver",annotate:"Anotar",shapes:"Formas",redact:"Redactar"},annotation:{text:"Texto",highlight:"Resaltar",strikeout:"Tachar",underline:"Subrayar",squiggly:"Ondulado",rectangle:"Rectángulo",circle:"Círculo",line:"Línea",arrow:"Flecha",polygon:"Polígono",polyline:"Polilínea",ink:"Tinta",stamp:"Sello",freeText:"Texto libre",square:"Cuadrado",style:"Estilo de anotación",styles:"Estilos de {type}",defaults:"Valores predeterminados de {type}",color:"Color",opacity:"Opacidad",blendMode:"Modo de fusión",strokeWidth:"Grosor del trazo",strokeColor:"Color del trazo",borderStyle:"Estilo del borde",fillColor:"Color de relleno",fontSize:"Tamaño de fuente",fontFamily:"Fuente",textAlign:"Alineación del texto",verticalAlign:"Alineación vertical",lineEnding:"Final de línea",lineStart:"Inicio de línea",lineEnd:"Final de línea",font:"Fuente",fontColor:"Color de fuente",backgroundColor:"Color de fondo",noStyles:"No hay estilos para esta anotación.",noStylesStamp:"No hay estilos para los sellos.",selectAnnotation:"Seleccione una anotación para ver los estilos",deleteSelected:"Eliminar anotación seleccionada",deleteAllSelected:"Eliminar selección",multiSelect:"{count} anotaciones seleccionadas",group:"Agrupar",ungroup:"Desagrupar",moreTools:"Más herramientas",addLink:"Agregar enlace",removeLink:"Eliminar enlace",gotoLink:"Ir al enlace",comment:"Comentario",redact:"Redactar",overlayText:"Texto superpuesto",overlayTextPlaceholder:"ej: REDACTADO",rotation:"Rotación"},redaction:{redact:"Redactar",area:"Redactar área",text:"Redactar texto",apply:"Aplicar redacción",applyAll:"Aplicar todo",clearAll:"Borrar todo",deleteSelected:"Eliminar redacción seleccionada",commitSelected:"Aplicar redacción seleccionada",emptyState:"No hay redacciones pendientes",panel:{title:"Redacciones",itemCount:"{count} redacción pendiente",itemCountPlural:"{count} redacciones pendientes",clearAll:"Borrar todo",redactAll:"Redactar todo"}},history:{undo:"Deshacer",redo:"Rehacer"},comments:{page:"Página {page}",commentCount:"{count} comentario",commentCountPlural:"{count} comentarios",addComment:"Añadir comentario...",addReply:"Añadir respuesta...",save:"Guardar",cancel:"Cancelar",edit:"Editar",delete:"Eliminar",showMore:"más",showLess:"menos",emptyState:"Añada anotaciones para poder comentarlas."},blendMode:{normal:"Normal",multiply:"Multiplicar",screen:"Trama",overlay:"Superponer",darken:"Oscurecer",lighten:"Aclarar",colorDodge:"Sobreexponer color",colorBurn:"Subexponer color",hardLight:"Luz fuerte",softLight:"Luz suave",difference:"Diferencia",exclusion:"Exclusión",hue:"Tono",saturation:"Saturación",color:"Color",luminosity:"Luminosidad"},print:{title:"Configuración de impresión",loading:"Preparando documento...",pages:"Páginas a imprimir",all:"Todas las páginas",current:"Página actual ({currentPage})",specify:"Especificar páginas",specifyEG:"ej: 1-3, 5, 8-10",total:"Total de páginas en el documento: {totalPages}",annotation:"Incluir anotaciones",printing:"Imprimiendo...",print:"Imprimir",cancel:"Cancelar"},protect:{title:"Proteger documento",cancel:"Cancelar",apply:"Aplicar protección",applying:"Aplicando...",applyFailed:"No se pudo aplicar la protección. Por favor, inténtelo de nuevo.",removeFailed:"No se pudo eliminar la protección. Por favor, inténtelo de nuevo.",passwordMismatch:"Las contraseñas no coinciden",noProtectionSelected:"Seleccione al menos una opción de protección.",bothPasswordsNote:"Los usuarios que abran con la contraseña del documento tendrán permisos restringidos. Use la contraseña de propietario para acceso completo.",openPassword:{title:"Contraseña requerida para abrir",description:"Los usuarios deben ingresar una contraseña para ver este documento.",label:"Contraseña del documento",placeholder:"Ingresar contraseña",confirm:"Confirmar contraseña",confirmPlaceholder:"Confirmar contraseña"},ownerPassword:{label:"Contraseña de propietario",placeholder:"Ingresar contraseña de propietario",confirm:"Confirmar contraseña de propietario",confirmPlaceholder:"Confirmar contraseña de propietario"},permissions:{title:"Restringir permisos",description:"Limite lo que los usuarios pueden hacer con este documento.",allowedActions:"Acciones permitidas",print:"Imprimir",printHighQuality:"Imprimir alta calidad",copy:"Copiar contenido",accessibility:"Extraer para accesibilidad",modify:"Modificar contenido",annotations:"Añadir/modificar anotaciones y comentarios",fillForms:"Rellenar formularios y firmar",assemble:"Ensamblar documento y extraer páginas"},encrypted:{title:"Documento protegido",description:"Este documento está protegido por el propietario. Ingrese la contraseña de propietario para modificar la configuración de seguridad.",enterOwnerPassword:"Ingrese la contraseña de propietario para modificar",unlockAndEdit:"Desbloquear y Editar"},modifyProtection:{title:"Modificar protección",description:"Elija cómo desea modificar la protección del documento.",changeOption:"Cambiar contraseñas o permisos",changeDescription:"Actualizar la contraseña del documento o la configuración de permisos.",removeOption:"Eliminar toda la protección",removeDescription:"Eliminar la protección por contraseña de este documento."},removeProtection:{title:"Eliminar protección",warning:"¿Está seguro de que desea eliminar la protección?",description:"Esto eliminará toda la protección por contraseña del documento. Cualquiera podrá abrirlo y modificarlo.",confirm:"Eliminar protección"}},security:{protected:{title:"Este documento está protegido",description:"Este archivo está protegido y algunas funciones pueden estar deshabilitadas. Vaya a Seguridad en el menú del documento para ver o desbloquear los permisos.",viewPermissions:"Ver permisos"},viewPermissions:{title:"Permisos del documento",description:"Este archivo está restringido por el propietario y requiere una contraseña para desbloquear ciertas acciones.",restrictedActions:"Acciones restringidas"},unlock:{label:"Ingrese la contraseña de propietario para desbloquear",placeholder:"Ingresar contraseña de propietario",button:"Desbloquear archivo",invalidPassword:"Contraseña inválida. Por favor, inténtelo de nuevo.",failed:"Error al desbloquear. Por favor, inténtelo de nuevo.",success:"¡Permisos de propietario desbloqueados! Ahora tiene acceso completo."}},common:{close:"Cerrar",back:"Atrás",cancel:"Cancelar"},link:{title:"Insertar enlace",url:"URL",page:"Página",enterUrl:"Introducir URL",enterPage:"Introducir número de página",pageRange:"Página 1 a {totalPages}",link:"Enlazar"}}},{code:"zh-CN",name:"简体中文",translations:{search:{placeholder:"搜索",caseSensitive:"大小写敏感",wholeWord:"全词匹配",resultsFound:"{count} 个结果",page:"第{page}页"},zoom:{in:"放大",out:"缩小",fitWidth:"适合宽度",fitPage:"适合页面",marquee:"框选放大",menu:"缩放菜单",level:"缩放比例 ({level}%)",dragTip:"拖动鼠标选择要放大的区域"},pan:{toggle:"拖动模式"},pointer:{toggle:"光标模式"},capture:{screenshot:"截图",dragTip:"拖动鼠标选择要截取的区域",title:"截取的PDF区域",download:"下载",cancel:"取消"},document:{menu:"文件选项",open:"打开",close:"关闭",print:"打印",protect:"安全",export:"导出",fullscreen:"全屏",loading:"文件加载中..."},emptyState:{title:"尚无打开的文件",description:"请点击“+ 打开文件”按钮选择并打开一个PDF文件。",descriptionMulti:"您可以使用标签页同时打开多个文件。",openButton:"打开文件",supportedFormats:"支持的文件格式为: PDF"},passwordPrompt:{title:"请输入密码",required:"该文件设置有密码保护,要打开文件请输入密码。",incorrect:"你输入的密码错误,请重新输入。",incorrectWarning:"密码错误,请检查后重新输入。",label:"密码",placeholder:"请输入文件密码",open:"打开",opening:"打开中...",cancel:"取消",close:"关闭"},documentError:{title:"文件加载出错",unknown:"未知错误",errorCode:"错误码: {code}",close:"关闭文件"},panel:{sidebar:"大纲与书签",search:"搜索",comment:"评论",thumbnails:"缩略图",outline:"大纲",annotationStyle:"批注样式",redaction:"遮蔽侧边栏"},menu:{viewControls:"视图控件",zoomControls:"缩放控件",moreOptions:"更多选项"},outline:{title:"大纲",loading:"大纲加载中...",noOutline:"没有大纲",noBookmarks:"该文件不含书签"},page:{settings:"页面设置",single:"单页视图",twoOdd:"双页视图",twoEven:"书籍视图",vertical:"垂直滚动",horizontal:"水平滚动",spreadMode:"跨页模式",scrollLayout:"滚动布局",rotation:"页面转向",next:"下一页",previous:"上一页"},rotate:{clockwise:"顺时针旋转",counterClockwise:"逆时针旋转"},selection:{copy:"复制"},mode:{view:"阅读",annotate:"批注",shapes:"形状",redact:"遮蔽"},annotation:{text:"任意文本",highlight:"高亮",strikeout:"删除线",underline:"下划线",squiggly:"下划曲线",rectangle:"矩形",circle:"圆形",line:"直线",arrow:"带箭头直线",polygon:"多边形",polyline:"多段线",ink:"自由绘制",stamp:"印章",freeText:"任意文本",square:"矩形",style:"批注样式",styles:"{type} 样式",defaults:"{type} 默认值",color:"颜色",opacity:"透明度",blendMode:"混合模式",strokeWidth:"线条宽度",strokeColor:"线条颜色",borderStyle:"线条样式",fillColor:"填充色",fontSize:"字号",fontFamily:"字体",textAlign:"左右对齐",verticalAlign:"上下对齐",lineEnding:"行尾",lineStart:"线条起点",lineEnd:"线条结尾",font:"字体",fontColor:"字色",backgroundColor:"背景色",noStyles:"该批注无需设置样式。",noStylesStamp:"印章无需设置样式。",selectAnnotation:"在此处查看选中批注的样式。",deleteSelected:"删除选中的批注",deleteAllSelected:"删除选中",multiSelect:"已选择 {count} 个批注",group:"分组",ungroup:"取消分组",moreTools:"更多工具",addLink:"添加链接",removeLink:"移除链接",gotoLink:"跳转到链接",comment:"评论",redact:"遮蔽",overlayText:"覆盖文字",overlayTextPlaceholder:"例如:已遮蔽",rotation:"旋转"},redaction:{redact:"遮蔽",area:"遮蔽区域",text:"遮蔽文本",apply:"应用遮蔽",applyAll:"全部应用",clearAll:"全部取消",deleteSelected:"取消遮蔽",commitSelected:"应用遮蔽",emptyState:"暂无待处理的遮蔽",panel:{title:"遮蔽",itemCount:"{count} 个待处理遮蔽",itemCountPlural:"{count} 个待处理遮蔽",clearAll:"全部取消",redactAll:"全部遮蔽"}},history:{undo:"撤销",redo:"恢复"},comments:{page:"第{page}页",commentCount:"{count}条评论",commentCountPlural:"{count}条评论",addComment:"新增评论...",addReply:"新增回复...",save:"保存",cancel:"取消",edit:"编辑",delete:"删除",showMore:"展开",showLess:"收起",emptyState:"添加批注后,可以在这里对批注进行评论。"},blendMode:{normal:"正常",multiply:"正片",screen:"屏幕",overlay:"叠加",darken:"变暗",lighten:"变亮",colorDodge:"色彩减淡",colorBurn:"颜色加深",hardLight:"强光",softLight:"柔光",difference:"差值",exclusion:"排除",hue:"色相",saturation:"饱和度",color:"颜色",luminosity:"亮度"},print:{title:"打印设置",loading:"正在处理...",pages:"要打印的页码",all:"所有页",current:"当前页({currentPage})",specify:"指定页",specifyEG:"例如:1-3, 5, 8-10",total:"文档总页数:{totalPages}",annotation:"包含批注",printing:"打印中...",print:"打印",cancel:"取消"},protect:{title:"文档保护",cancel:"取消",apply:"应用保护",applying:"正在应用...",applyFailed:"无法应用保护。请重试。",removeFailed:"无法移除保护。请重试。",passwordMismatch:"密码不匹配",noProtectionSelected:"请至少选择一种保护方式。",bothPasswordsNote:"使用文档密码打开的用户将受到权限限制。使用所有者密码可获得完全访问权限。",openPassword:{title:"需要密码才能打开",description:"用户必须输入密码才能查看此文档。",label:"文档密码",placeholder:"输入密码",confirm:"确认密码",confirmPlaceholder:"确认密码"},ownerPassword:{label:"所有者密码",placeholder:"输入所有者密码",confirm:"确认所有者密码",confirmPlaceholder:"确认所有者密码"},permissions:{title:"限制权限",description:"限制用户对此文档的操作。",allowedActions:"允许的操作",print:"打印",printHighQuality:"高质量打印",copy:"复制内容",accessibility:"提取辅助功能",modify:"修改内容",annotations:"添加/修改批注和评论",fillForms:"填写表单和签名",assemble:"组装文档和提取页面"},encrypted:{title:"文档受保护",description:"此文档已被所有者保护。请输入所有者密码以修改安全设置。",enterOwnerPassword:"输入所有者密码以修改",unlockAndEdit:"解锁并编辑"},modifyProtection:{title:"修改保护",description:"选择如何修改文档保护。",changeOption:"更改密码或权限",changeDescription:"更新文档密码或权限设置。",removeOption:"移除所有保护",removeDescription:"移除此文档的密码保护。"},removeProtection:{title:"移除保护",warning:"确定要移除保护吗?",description:"这将移除文档的所有密码保护。任何人都可以打开和修改它。",confirm:"移除保护"}},security:{protected:{title:"此文档受保护",description:'此文件受保护,某些功能可能被禁用。请在文档菜单中点击"安全"以查看或解锁权限。',viewPermissions:"查看权限"},viewPermissions:{title:"文档权限",description:"此文件受所有者限制,需要密码才能解锁某些操作。",restrictedActions:"受限操作"},unlock:{label:"输入所有者密码以解锁文件",placeholder:"输入所有者密码",button:"解锁文件",invalidPassword:"密码无效。请重试。",failed:"解锁失败。请重试。",success:"所有者权限已解锁!您现在拥有完全访问权限。"}},common:{close:"关闭",back:"返回",cancel:"取消"},link:{title:"插入链接",url:"网址",page:"页面",enterUrl:"输入网址",enterPage:"输入页码",pageRange:"第1页到第{totalPages}页",link:"链接"}}}],paramResolvers:Rb},ui:{schema:{id:"pdf-viewer-ui",version:"1.0.0",toolbars:{"main-toolbar":{id:"main-toolbar",position:{placement:"top",slot:"main",order:0},permanent:!0,responsive:{localeOverrides:{groups:[{id:"chinese-languages",locales:["zh-CN"],breakpoints:{sm:{replaceHide:["zoom-toolbar","mode-select-button","overflow-tabs-button"],replaceShow:["view-mode","annotate-mode","shapes-mode","redact-mode","pan-button","pointer-button","divider-3"]},md:{replaceShow:["view-mode","annotate-mode","shapes-mode","redact-mode","zoom-toolbar","pan-button","pointer-button","divider-3"],replaceHide:["zoom-menu-button","mode-select-button","overflow-tabs-button"]}}},{id:"germanic-languages",locales:["de","nl"],breakpoints:{md:{replaceShow:["view-mode","annotate-mode","zoom-toolbar","pan-button","pointer-button","divider-3","overflow-tabs-button"]}}}]},breakpoints:{xxxs:{maxWidth:400,hide:["annotate-mode","view-mode","shapes-mode","redact-mode","zoom-toolbar","pan-button","pointer-button","divider-3","page-settings-button","zoom-menu-button","divider-2","overflow-tabs-button"],show:["mode-select-button"]},xxs:{minWidth:400,show:["page-settings-button","zoom-menu-button","divider-2"],hide:["overflow-left-action-menu-button"]},xs:{minWidth:500,maxWidth:640,show:["pan-button","pointer-button","divider-3"]},sm:{minWidth:640,maxWidth:768,hide:["shapes-mode","redact-mode","zoom-toolbar","mode-select-button"],show:["view-mode","annotate-mode","overflow-tabs-button","pan-button","pointer-button","divider-3"]},md:{minWidth:768,show:["view-mode","annotate-mode","shapes-mode","zoom-toolbar","pan-button","pointer-button","divider-3","overflow-tabs-button"],hide:["zoom-menu-button","mode-select-button"]},lg:{minWidth:1024,show:["shapes-mode","redact-mode"],hide:["overflow-tabs-button"]}}},items:[{type:"group",id:"left-group",alignment:"start",gap:2,items:[{type:"command-button",id:"document-menu-button",commandId:"document:menu",variant:"icon",categories:["document","document-menu"]},{type:"divider",id:"divider-1",orientation:"vertical"},{type:"command-button",id:"sidebar-button",commandId:"panel:toggle-sidebar",variant:"icon",categories:["panel","panel-sidebar"]},{type:"command-button",id:"overflow-left-action-menu-button",commandId:"left-action-menu:overflow-menu",variant:"icon",categories:["ui","ui-menu"]},{type:"command-button",id:"page-settings-button",commandId:"page:settings",variant:"icon",categories:["page","page-settings"]}]},{type:"divider",id:"divider-2",orientation:"vertical"},{type:"group",id:"center-group",alignment:"center",gap:2,items:[{type:"command-button",id:"zoom-menu-button",commandId:"zoom:toggle-menu-mobile",variant:"icon",categories:["zoom","zoom-menu"]},{type:"custom",id:"zoom-toolbar",componentId:"zoom-toolbar",categories:["zoom"]},{type:"divider",id:"divider-3",orientation:"vertical",visibilityDependsOn:{itemIds:["zoom-toolbar","zoom-menu-button"]}},{type:"command-button",id:"pan-button",commandId:"pan:toggle",variant:"icon",categories:["tools","pan"]},{type:"command-button",id:"pointer-button",commandId:"pointer:toggle",variant:"icon",categories:["tools","pointer"]}]},{type:"spacer",id:"spacer-1",flex:!0},{type:"custom",id:"mode-select-button",componentId:"mode-select-button",categories:["mode"],visibilityDependsOn:{itemIds:["mode:annotate","mode:shapes","mode:redact"]}},{type:"tab-group",id:"mode-tabs",tabs:[{id:"view-mode",commandId:"mode:view",variant:"text",categories:["mode","mode-view"],visibilityDependsOn:{itemIds:["annotate-mode","shapes-mode","redact-mode"]}},{id:"annotate-mode",commandId:"mode:annotate",variant:"text",categories:["mode","mode-annotate","annotation"]},{id:"shapes-mode",commandId:"mode:shapes",variant:"text",categories:["mode","mode-shapes","annotation"]},{id:"redact-mode",commandId:"mode:redact",variant:"text",categories:["mode","mode-redact","redaction"]},{id:"overflow-tabs-button",commandId:"tabs:overflow-menu",variant:"icon",categories:["ui","ui-menu"],visibilityDependsOn:{menuId:"mode-tabs-overflow-menu"}}]},{type:"spacer",id:"spacer-2",flex:!0},{type:"group",id:"right-group",alignment:"end",gap:2,items:[{type:"command-button",id:"search-button",commandId:"panel:toggle-search",variant:"icon",categories:["panel","panel-search"]},{type:"command-button",id:"comment-button",commandId:"panel:toggle-comment",variant:"icon",categories:["panel","panel-comment"]}]}]},"annotation-toolbar":{id:"annotation-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-text","add-stamp","add-ink"],show:["overflow-annotation-tools"]},md:{minWidth:640,hide:["overflow-annotation-tools"],show:["add-text","add-stamp","add-ink"]}}},permanent:!1,categories:["annotation"],items:[{type:"spacer",id:"spacer-3",flex:!0},{type:"group",id:"annotation-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-highlight",commandId:"annotation:add-highlight",variant:"icon",categories:["annotation","annotation-markup","annotation-highlight"]},{type:"command-button",id:"add-strikeout",commandId:"annotation:add-strikeout",variant:"icon",categories:["annotation","annotation-markup","annotation-strikeout"]},{type:"command-button",id:"add-underline",commandId:"annotation:add-underline",variant:"icon",categories:["annotation","annotation-markup","annotation-underline"]},{type:"command-button",id:"add-squiggly",commandId:"annotation:add-squiggly",variant:"icon",categories:["annotation","annotation-markup","annotation-squiggly"]},{type:"command-button",id:"add-ink",commandId:"annotation:add-ink",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-text",commandId:"annotation:add-text",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"add-stamp",commandId:"annotation:add-stamp",variant:"icon",categories:["annotation","annotation-stamp"]},{type:"command-button",id:"overflow-annotation-tools",commandId:"annotation:overflow-tools",variant:"icon",categories:["annotation","annotation-overflow"]},{type:"divider",id:"annotation-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"annotation-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-4",flex:!0}]},"shapes-toolbar":{id:"shapes-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-polygon","add-polyline"],show:["overflow-shapes-tools"]},md:{minWidth:640,hide:["overflow-shapes-tools"],show:["add-polygon","add-polyline"]}}},permanent:!1,categories:["annotation","annotation-shape"],items:[{type:"spacer",id:"spacer-5",flex:!0},{type:"group",id:"shapes-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rectangle",commandId:"annotation:add-rectangle",variant:"icon",categories:["annotation","annotation-shape","annotation-rectangle"]},{type:"command-button",id:"add-circle",commandId:"annotation:add-circle",variant:"icon",categories:["annotation","annotation-shape","annotation-circle"]},{type:"command-button",id:"add-line",commandId:"annotation:add-line",variant:"icon",categories:["annotation","annotation-shape","annotation-line"]},{type:"command-button",id:"add-arrow",commandId:"annotation:add-arrow",variant:"icon",categories:["annotation","annotation-shape","annotation-arrow"]},{type:"command-button",id:"add-polygon",commandId:"annotation:add-polygon",variant:"icon",categories:["annotation","annotation-shape","annotation-polygon"]},{type:"command-button",id:"add-polyline",commandId:"annotation:add-polyline",variant:"icon",categories:["annotation","annotation-shape","annotation-polyline"]},{type:"command-button",id:"overflow-shapes-tools",commandId:"annotation:overflow-shapes",variant:"icon",categories:["annotation","annotation-shape","annotation-overflow"]},{type:"divider",id:"shapes-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"shapes-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-6",flex:!0}]},"redaction-toolbar":{id:"redaction-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["redaction"],items:[{type:"spacer",id:"spacer-7",flex:!0},{type:"group",id:"redaction-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"redact",commandId:"redaction:redact",variant:"icon",categories:["redaction","redaction-combined"]},{type:"divider",id:"redaction-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-redaction-panel",commandId:"panel:toggle-redaction",variant:"icon",categories:["panel","panel-redaction"]},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"redaction-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-8",flex:!0}]}},menus:{"left-action-menu":{id:"left-action-menu",categories:["ui"],items:[{type:"submenu",id:"page-settings-submenu",labelKey:"menu.viewControls",label:"View Controls",icon:"viewSettings",menuId:"page-settings-menu",categories:["page"]},{type:"submenu",id:"zoom-submenu",labelKey:"menu.zoomControls",label:"Zoom Controls",icon:"zoomIn",menuId:"zoom-menu",categories:["zoom"]},{type:"divider",id:"divider-15"},{type:"command",id:"pan-button-menu",commandId:"pan:toggle",categories:["tools","pan"]},{type:"command",id:"pointer-button-menu",commandId:"pointer:toggle",categories:["tools","pointer"]}]},"mode-tabs-overflow-menu":{id:"mode-tabs-overflow-menu",items:[{type:"command",id:"mode:view",commandId:"mode:view",categories:["mode","mode-view"]},{type:"command",id:"mode:annotate",commandId:"mode:annotate",categories:["mode","mode-annotate","annotation"]},{type:"command",id:"mode:shapes",commandId:"mode:shapes",categories:["mode","mode-shapes","annotation"]},{type:"command",id:"mode:redact",commandId:"mode:redact",categories:["mode","mode-redact","redaction"]}],responsive:{breakpoints:{xs:{maxWidth:640,show:["mode:view","mode:annotate","mode:shapes","mode:redact"]},sm:{minWidth:640,maxWidth:768,hide:["mode:view","mode:annotate"]},md:{minWidth:768,hide:["mode:view","mode:annotate","mode:shapes"]}},localeOverrides:{groups:[{id:"germanic-languages",locales:["de","nl"],breakpoints:{md:{replaceHide:["mode:view","mode:annotate"]}}}]}}},"zoom-levels-menu":{id:"zoom-levels-menu",categories:["zoom","zoom-level"],items:[{type:"command",id:"zoom-levels-menu:25",commandId:"zoom:25",categories:["zoom","zoom-level","zoom-level-25"]},{type:"command",id:"zoom-levels-menu:50",commandId:"zoom:50",categories:["zoom","zoom-level","zoom-level-50"]},{type:"command",id:"zoom-levels-menu:100",commandId:"zoom:100",categories:["zoom","zoom-level","zoom-level-100"]},{type:"command",id:"zoom-levels-menu:125",commandId:"zoom:125",categories:["zoom","zoom-level","zoom-level-125"]},{type:"command",id:"zoom-levels-menu:150",commandId:"zoom:150",categories:["zoom","zoom-level","zoom-level-150"]},{type:"command",id:"zoom-levels-menu:200",commandId:"zoom:200",categories:["zoom","zoom-level","zoom-level-200"]},{type:"command",id:"zoom-levels-menu:400",commandId:"zoom:400",categories:["zoom","zoom-level","zoom-level-400"]},{type:"command",id:"zoom-levels-menu:800",commandId:"zoom:800",categories:["zoom","zoom-level","zoom-level-800"]},{type:"command",id:"zoom-levels-menu:1600",commandId:"zoom:1600",categories:["zoom","zoom-level","zoom-level-1600"]}]},"zoom-menu":{id:"zoom-menu",categories:["zoom"],items:[{type:"command",id:"zoom-menu:25",commandId:"zoom:25",categories:["zoom","zoom-level","zoom-level-25"]},{type:"command",id:"zoom-menu:50",commandId:"zoom:50",categories:["zoom","zoom-level","zoom-level-50"]},{type:"command",id:"zoom-menu:100",commandId:"zoom:100",categories:["zoom","zoom-level","zoom-level-100"]},{type:"command",id:"zoom-menu:125",commandId:"zoom:125",categories:["zoom","zoom-level","zoom-level-125"]},{type:"command",id:"zoom-menu:150",commandId:"zoom:150",categories:["zoom","zoom-level","zoom-level-150"]},{type:"command",id:"zoom-menu:200",commandId:"zoom:200",categories:["zoom","zoom-level","zoom-level-200"]},{type:"command",id:"zoom-menu:400",commandId:"zoom:400",categories:["zoom","zoom-level","zoom-level-400"]},{type:"command",id:"zoom-menu:800",commandId:"zoom:800",categories:["zoom","zoom-level","zoom-level-800"]},{type:"command",id:"zoom-menu:1600",commandId:"zoom:1600",categories:["zoom","zoom-level","zoom-level-1600"]},{type:"submenu",id:"zoom-levels-submenu",labelKey:"zoom.level",label:"Zoom Levels",menuId:"zoom-levels-menu",categories:["zoom","zoom-level"]},{type:"divider",id:"divider-zoom-in-out"},{type:"command",id:"zoom-menu:in",commandId:"zoom:in",categories:["zoom","zoom-in"]},{type:"command",id:"zoom-menu:out",commandId:"zoom:out",categories:["zoom","zoom-out"]},{type:"divider",id:"divider-8"},{type:"command",id:"zoom:fit-page",commandId:"zoom:fit-page",categories:["zoom","zoom-fit-page"]},{type:"command",id:"zoom:fit-width",commandId:"zoom:fit-width",categories:["zoom","zoom-fit-width"]},{type:"divider",id:"divider-9"},{type:"command",id:"zoom:marquee",commandId:"zoom:marquee",categories:["zoom","zoom-marquee"]}],responsive:{breakpoints:{xs:{maxWidth:640,show:["zoom-levels-submenu","divider-zoom-in-out"],hide:["zoom-menu:25","zoom-menu:50","zoom-menu:100","zoom-menu:125","zoom-menu:150","zoom-menu:200","zoom-menu:400","zoom-menu:800","zoom-menu:1600"]},md:{minWidth:768,show:["zoom-menu:25","zoom-menu:50","zoom-menu:100","zoom-menu:125","zoom-menu:150","zoom-menu:200","zoom-menu:400","zoom-menu:800","zoom-menu:1600"],hide:["zoom-levels-submenu","divider-zoom-in-out","zoom-menu:in","zoom-menu:out"]}}}},"document-menu":{id:"document-menu",categories:["document"],items:[{type:"command",id:"document:open",commandId:"document:open",categories:["document","document-open"]},{type:"command",id:"document:close",commandId:"document:close",categories:["document","document-close"]},{type:"divider",id:"divider-10",visibilityDependsOn:{itemIds:["document:open","document:close"]}},{type:"command",id:"document:print",commandId:"document:print",categories:["document","document-print"]},{type:"command",id:"document:protect",commandId:"document:protect",categories:["document","document-protect"]},{type:"command",id:"document:capture",commandId:"document:capture",categories:["document","document-capture"]},{type:"command",id:"document:export",commandId:"document:export",categories:["document","document-export"]},{type:"divider",id:"divider-11",visibilityDependsOn:{itemIds:["document:export","document:print","document:capture","document:protect"]}},{type:"command",id:"document:fullscreen",commandId:"document:fullscreen",categories:["document","document-fullscreen"]}]},"annotation-tools-menu":{id:"annotation-tools-menu",categories:["annotation"],items:[{type:"command",id:"annotation:add-ink",commandId:"annotation:add-ink",categories:["annotation","annotation-ink"]},{type:"command",id:"annotation:add-text",commandId:"annotation:add-text",categories:["annotation","annotation-text"]},{type:"command",id:"annotation:add-stamp",commandId:"annotation:add-stamp",categories:["annotation","annotation-stamp"]}]},"shapes-tools-menu":{id:"shapes-tools-menu",categories:["annotation","annotation-shape"],items:[{type:"command",id:"annotation:add-polygon",commandId:"annotation:add-polygon",categories:["annotation","annotation-shape","annotation-polygon"]},{type:"command",id:"annotation:add-polyline",commandId:"annotation:add-polyline",categories:["annotation","annotation-shape","annotation-polyline"]}]},"page-settings-menu":{id:"page-settings-menu",categories:["page"],items:[{type:"section",id:"spread-mode-section",labelKey:"page.spreadMode",label:"Spread Mode",categories:["page","spread"],items:[{type:"command",id:"spread:none",commandId:"spread:none",categories:["page","spread","spread-none"]},{type:"command",id:"spread:odd",commandId:"spread:odd",categories:["page","spread","spread-odd"]},{type:"command",id:"spread:even",commandId:"spread:even",categories:["page","spread","spread-even"]}]},{type:"divider",id:"divider-13"},{type:"section",id:"scroll-layout-section",labelKey:"page.scrollLayout",label:"Scroll Layout",categories:["page","scroll"],items:[{type:"command",id:"scroll:vertical",commandId:"scroll:vertical",categories:["page","scroll","scroll-vertical"]},{type:"command",id:"scroll:horizontal",commandId:"scroll:horizontal",categories:["page","scroll","scroll-horizontal"]}]},{type:"divider",id:"divider-14"},{type:"section",id:"page-rotation-section",labelKey:"page.rotation",label:"Page Rotation",categories:["page","rotate"],items:[{type:"command",id:"rotate:clockwise",commandId:"rotate:clockwise",categories:["page","rotate","rotate-clockwise"]},{type:"command",id:"rotate:counter-clockwise",commandId:"rotate:counter-clockwise",categories:["page","rotate","rotate-counter-clockwise"]}]},{type:"divider",id:"divider-15"},{type:"command",id:"document:fullscreen",commandId:"document:fullscreen",categories:["document","document-fullscreen"]}]}},sidebars:{"sidebar-panel":{id:"sidebar-panel",position:{placement:"left",slot:"main",order:0},content:{type:"tabs",tabs:[{id:"thumbnails",labelKey:"panel.thumbnails",label:"Thumbnails",icon:"squares",componentId:"thumbnails-sidebar"},{id:"outline",labelKey:"panel.outline",label:"Outline",icon:"listTree",componentId:"outline-sidebar"}]},width:"250px",collapsible:!0,defaultOpen:!1},"annotation-panel":{id:"annotation-panel",position:{placement:"left",slot:"main",order:0},content:{type:"component",componentId:"annotation-sidebar"},width:"250px",collapsible:!0,defaultOpen:!1},"search-panel":{id:"search-panel",position:{placement:"right",slot:"main",order:0},content:{type:"component",componentId:"search-sidebar"},width:"250px",collapsible:!0,defaultOpen:!1},"comment-panel":{id:"comment-panel",position:{placement:"right",slot:"main",order:0},content:{type:"component",componentId:"comment-sidebar"},width:"250px",collapsible:!0,defaultOpen:!1},"redaction-panel":{id:"redaction-panel",position:{placement:"right",slot:"main",order:0},content:{type:"component",componentId:"redaction-sidebar"},width:"250px",collapsible:!0,defaultOpen:!1,categories:["redaction"]}},modals:{"print-modal":{id:"print-modal",content:{type:"component",componentId:"print-modal"},maxWidth:"28rem",closeOnClickOutside:!0,closeOnEscape:!0},"protect-modal":{id:"protect-modal",content:{type:"component",componentId:"protect-modal"},maxWidth:"28rem",closeOnClickOutside:!0,closeOnEscape:!0},"view-permissions-modal":{id:"view-permissions-modal",content:{type:"component",componentId:"view-permissions-modal"},maxWidth:"28rem",closeOnClickOutside:!0,closeOnEscape:!0},"link-modal":{id:"link-modal",content:{type:"component",componentId:"link-modal"},maxWidth:"28rem",closeOnClickOutside:!0,closeOnEscape:!0}},overlays:{"page-controls":{id:"page-controls",position:{anchor:"bottom-center",offset:{bottom:"1.5rem"}},content:{type:"component",componentId:"page-controls"},defaultEnabled:!0},"unlock-owner-overlay":{id:"unlock-owner-overlay",position:{anchor:"bottom-right",offset:{bottom:"1.5rem",right:"1.5rem"}},content:{type:"component",componentId:"unlock-owner-overlay"},defaultEnabled:!0}},selectionMenus:{annotation:{id:"annotation",categories:["annotation"],items:[{type:"command-button",id:"comment-button",commandId:"annotation:toggle-comment",variant:"icon",categories:["annotation","annotation-comment"]},{type:"command-button",id:"toggle-link",commandId:"annotation:toggle-link",variant:"icon",categories:["annotation","annotation-link"]},{type:"command-button",id:"toggle-annotation-style",commandId:"annotation:toggle-annotation-style",variant:"icon",categories:["annotation","annotation-style"]},{type:"command-button",id:"apply-redaction",commandId:"annotation:apply-redaction",variant:"icon",categories:["annotation","annotation-redaction"]},{type:"command-button",id:"delete-annotation",commandId:"annotation:delete-selected",variant:"icon",categories:["annotation","annotation-delete"]},{type:"command-button",id:"goto-link",commandId:"annotation:goto-link",variant:"icon-text",categories:["annotation","annotation-link"]}]},groupAnnotation:{id:"groupAnnotation",categories:["annotation","annotation-group"],items:[{type:"command-button",id:"toggle-group-annotations",commandId:"annotation:toggle-group",variant:"icon",categories:["annotation","annotation-group"]},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"command-button",id:"delete-all-annotations",commandId:"annotation:delete-all-selected",variant:"icon",categories:["annotation","annotation-delete","annotation-group"]}]},redaction:{id:"redaction",categories:["redaction"],items:[{type:"command-button",id:"delete-redaction",commandId:"redaction:delete-selected",variant:"icon",categories:["redaction","redaction-delete"]},{type:"command-button",id:"commit-redaction",commandId:"redaction:commit-selected",variant:"icon",categories:["redaction","redaction-commit"]}]},selection:{id:"selection",visibilityDependsOn:{itemIds:["copy-selection","add-highlight","add-strikeout","add-underline","add-squiggly","add-link","redact-text"]},items:[{type:"command-button",id:"copy-selection",commandId:"selection:copy",variant:"icon",categories:["selection","selection-copy"]},{type:"command-button",id:"add-highlight",commandId:"annotation:add-highlight",variant:"icon",categories:["annotation","annotation-markup","annotation-highlight"]},{type:"command-button",id:"add-strikeout",commandId:"annotation:add-strikeout",variant:"icon",categories:["annotation","annotation-markup","annotation-strikeout"]},{type:"command-button",id:"add-underline",commandId:"annotation:add-underline",variant:"icon",categories:["annotation","annotation-markup","annotation-underline"]},{type:"command-button",id:"add-squiggly",commandId:"annotation:add-squiggly",variant:"icon",categories:["annotation","annotation-markup","annotation-squiggly"]},{type:"command-button",id:"add-link",commandId:"annotation:add-link",variant:"icon",categories:["annotation","annotation-link"]},{type:"command-button",id:"redact-text",commandId:"redaction:redact-text",variant:"icon",categories:["redaction","redaction-text"]}]}}}},viewport:{viewportGap:10},scroll:{defaultStrategy:hi.Vertical},zoom:{defaultZoomLevel:Fa.FitPage},spread:{defaultSpreadMode:Di.None},rotation:{defaultRotation:Be.Degree0},pan:{},render:{defaultImageType:"image/png"},tiling:{tileSize:768,overlapPx:2.5,extraRings:0},thumbnails:{width:150,gap:10,buffer:3,labelHeight:30},annotations:{},search:{},selection:{},bookmarks:{},attachments:{},capture:{scale:2,imageType:"image/png"},redaction:{drawBlackBoxes:!0,useAnnotationMode:!0},print:{},export:{defaultFileName:"document.pdf"},fullscreen:{},history:{},interactionManager:{}};function Zb(e){var t=e.documentId,n=e.tabBarVisibility,o=void 0===n?"multiple":n,i=function(e){const t=la(),{provides:n}=Zr(),o=null==n?void 0:n.getSchema(),i=Yr(e);return{renderToolbar:(r,a)=>{const s=`${r}-${a}`;if(!o||!n||!i)return null;const l=i.activeToolbars[s],c=l?o.toolbars[l.toolbarId]:null;l&&!c&&console.warn(`Toolbar "${l.toolbarId}" not found in schema`);const d=c&&!c.permanent?()=>n.forDocument(e).closeToolbarSlot(r,a):void 0,u=t.toolbar;return He(H,{children:l&&c&&He(u,{schema:c,documentId:e,isOpen:l.isOpen,onClose:d})},`toolbar-slot-${s}`)},renderSidebar:(r,a)=>{var s;const l=`${r}-${a}`;if(!o||!n||!i)return null;const c=i.activeSidebars[l],d=c?null==(s=o.sidebars)?void 0:s[c.sidebarId]:null;c&&!d&&console.warn(`Sidebar "${c.sidebarId}" not found in schema`);const u=t.sidebar;return He(H,{children:c&&d&&He(u,{schema:d,documentId:e,isOpen:c.isOpen,onClose:()=>{n.forDocument(e).closeSidebarSlot(r,a)}})},`sidebar-slot-${l}`)},renderModal:()=>{var r;if(!o||!n||!i)return null;const a=t.modal;if(!a)return null;const s=i.activeModal,l=s?null==(r=o.modals)?void 0:r[s.modalId]:null;return s&&!l&&console.warn(`Modal "${s.modalId}" not found in schema`),He(H,{children:s&&l&&He(a,{schema:l,documentId:e,isOpen:s.isOpen,onClose:()=>{n.forDocument(e).closeModal()},onExited:()=>{n.forDocument(e).clearModal()},modalProps:s.props})},"modal-slot")},getActiveToolbars:()=>i?Object.entries(i.activeToolbars).map(([e,t])=>{const[n,o]=e.split("-");return{placement:n,slot:o,toolbarId:t.toolbarId,isOpen:t.isOpen}}):[],getActiveSidebars:()=>i?Object.entries(i.activeSidebars).map(([e,t])=>{const[n,o]=e.split("-");return{placement:n,slot:o,sidebarId:t.sidebarId,isOpen:t.isOpen}}):[],renderOverlays:()=>{if(!o||!n||!i)return null;const r=t.overlay;return r?He(H,{children:(o.overlays?Object.values(o.overlays):[]).filter(e=>!1!==i.enabledOverlays[e.id]).map(t=>He(r,{schema:t,documentId:e},t.id))},"overlays-slot"):null}}}(t),r=i.renderToolbar,a=i.renderSidebar,s=i.renderModal,l=i.renderOverlays,c=ja(t).translate,d=ca("selection",t),u=ca("annotation",t),h=ca("groupAnnotation",t),m=ca("redaction",t),g=(e=>{const t=No();return Re(()=>t?t.documentOrder.map(e=>t.documents[e]).filter(e=>null!=e):[],[t,e])})(),p=(()=>{const e=No();return Re(()=>{if(!e)return{activeDocumentId:null,activeDocument:null};const t=e.activeDocumentId;return{activeDocumentId:t,activeDocument:t?e.documents[t]??null:null}},[e])})();return F(H,null,F($b,{documentStates:g,activeDocumentId:p.activeDocumentId,visibility:o}),r("top","main"),r("top","secondary"),F("div",{id:"document-content",className:"bg-bg-surface flex flex-1 overflow-hidden"},a("left","main"),F("div",{className:"flex-1 overflow-hidden"},F(fa,{documentId:t},function(e){var n=e.documentState,o=e.isLoading,i=e.isError,r=e.isLoaded;return F(H,null,o&&F("div",{className:"flex h-full items-center justify-center"},F(uy,{size:"lg",text:c("document.loading")})),i&&F(Fb,{documentState:n}),r&&F("div",{className:"relative h-full w-full"},F(ph,{documentId:t},F(ui,{className:"bg-bg-app",documentId:t},F(ns,{documentId:t},F(Pi,{documentId:t,renderPage:function(e){var n=e.pageIndex;return F(ys,{documentId:t,pageIndex:n,style:{backgroundColor:"#fff"}},F(fh,{documentId:t,pageIndex:n},F(ls,{documentId:t,pageIndex:n,scale:.5,style:{pointerEvents:"none"}}),F(ic,{documentId:t,pageIndex:n,style:{pointerEvents:"none"}}),F(Fs,{documentId:t,pageIndex:n}),F(os,{documentId:t,pageIndex:n}),F(Em,{documentId:t,pageIndex:n}),F(Ul,{documentId:t,pageIndex:n,selectionMenu:d}),F(Sg,{documentId:t,pageIndex:n,selectionMenu:m}),F(Bh,{documentId:t,pageIndex:n,selectionMenu:u,groupSelectionMenu:h})))}})))),l()))})),a("right","main")),s())}var Yb=new yt([new pt,new vt]);function Xb(e){var t,o=e.config,i=e.onRegistryReady,r=function(e){const{wasmUrl:t=Ho,worker:n=!0,logger:o,encoderPoolSize:i,fontFallback:r}=e??{},[a,s]=Se(null),[l,c]=Se(!0),[d,u]=Se(null),h=De(null);return Ae(()=>{let e=!1;return(async()=>{try{const{createPdfiumEngine:e}=n?await import("./worker-engine-DZTIUfA0.js"):await import("./direct-engine-BKalS8iM.js"),a=await e(t,{logger:o,encoderPoolSize:i,fontFallback:r});h.current=a,s(a),c(!1)}catch(t){e||(u(t),c(!1))}})(),()=>{var t,n;e=!0,null==(n=null==(t=h.current)?void 0:t.closeAllDocuments)||n.call(t).wait(()=>{var e,t;null==(t=null==(e=h.current)?void 0:e.destroy)||t.call(e),h.current=null},En)}},[t,n,o,r]),{engine:a,isLoading:l,error:d}}(h(h({},o.wasmUrl&&{wasmUrl:o.wasmUrl}),{},{worker:o.worker,logger:o.log?Yb:void 0})),a=r.engine,s=r.isLoading,l=Re(function(){return{"thumbnails-sidebar":ry,"annotation-sidebar":fb,"zoom-toolbar":Dy,"search-sidebar":cy,"outline-sidebar":dy,"comment-sidebar":Py,"print-modal":Sb,"link-modal":Mb,"protect-modal":qb,"unlock-owner-overlay":Gb,"page-controls":Ab,"mode-select-button":Ub,"view-permissions-modal":Vb,"redaction-sidebar":bb}},[]),c=Re(function(){return{toolbar:$v,sidebar:Kv,modal:iy,overlay:Ib,menu:Xv,selectionMenu:wb}},[]);return F(H,null,F("style",null,Fe),!a||s?F("div",{className:"flex h-full w-full items-center justify-center"},F(uy,{size:"lg",text:"Initializing PDF engine..."})):F(To,{config:{logger:o.log?Yb:void 0,permissions:o.permissions},onInitialized:(t=n(g().m(function e(t){return g().w(function(e){for(;;)switch(e.n){case 0:i&&t&&i(t);case 1:return e.a(2)}},e)})),function(e){return t.apply(this,arguments)}),engine:a,plugins:[go(ya,h(h(h({},Kb.documentManager),o.src&&{initialDocuments:[{url:o.src}]}),o.documentManager)),go(Pa,h(h(h({},Kb.commands),o.disabledCategories&&{disabledCategories:o.disabledCategories}),o.commands)),go($a,h(h({},Kb.i18n),o.i18n)),go(Kr,h(h(h({},Kb.ui),o.disabledCategories&&{disabledCategories:o.disabledCategories}),o.ui)),go(si,h(h({},Kb.viewport),o.viewport)),go(Si,h(h({},Kb.scroll),o.scroll)),go(Qa,h(h({},Kb.zoom),o.zoom)),go(Fi,h(h({},Kb.spread),o.spread)),go(vs,h(h({},Kb.rotation),o.rotation)),go(xm,h(h({},Kb.pan),o.pan)),go(ss,h(h({},Kb.render),o.render)),go(tc,h(h({},Kb.tiling),o.tiling)),go(fc,h(h({},Kb.thumbnails),o.thumbnails)),go(qh,h(h({},Kb.annotations),o.annotations)),go($s,h(h({},Kb.search),o.search)),go(Hl,h(h({},Kb.selection),o.selection)),go(dm,h(h({},Kb.bookmarks),o.bookmarks)),go(Rg,h(h({},Kb.attachments),o.attachments)),go(zm,h(h({},Kb.capture),o.capture)),go(Mg,h(h({},Kb.redaction),o.redaction)),go(Xh,h(h({},Kb.print),o.print)),go(gm,h(h({},Kb.export),o.export)),go(rm,h(h({},Kb.fullscreen),o.fullscreen)),go(Bm,h(h({},Kb.history),o.history)),go(lh,h(h({},Kb.interactionManager),o.interactionManager))]},function(e){var t=e.pluginsReady,n=e.activeDocumentId;return F(H,null,t?F(H,null,n?F(ha,{documentId:n,components:l,renderers:c,className:"relative flex h-full w-full select-none flex-col"},F(Zb,{documentId:n,tabBarVisibility:o.tabBar}),F(Hb,{documentId:n}),F(gy,{documentId:n})):F(jb,null)):F("div",{className:"flex h-full items-center justify-center"},F(uy,{size:"lg",text:"Initializing plugins..."})))}))}var Qb="undefined"!=typeof HTMLElement?HTMLElement:r(function e(){i(this,e)}),Jb=function(){function e(){var t;return i(this,e),s(t=o(this,e),"_resolveRegistry",null),s(t,"themeStyleEl",null),s(t,"systemPreferenceCleanup",null),s(t,"handleRegistryReady",function(e){t._resolveRegistry&&(t._resolveRegistry(e),t._resolveRegistry=null)}),t.root=t.attachShadow({mode:"open"}),t._registryPromise=new Promise(function(e){t._resolveRegistry=e}),t}return c(e,Qb),r(e,[{key:"connectedCallback",value:function(){this._config||(this._config={src:this.getAttribute("src")||"/demo.pdf",worker:"false"!==this.getAttribute("worker"),theme:this.parseThemeAttribute()}),this.setupTheme(),this.renderViewer()}},{key:"disconnectedCallback",value:function(){var e;null===(e=this.systemPreferenceCleanup)||void 0===e||e.call(this),this.systemPreferenceCleanup=null,ce(null,this.root)}},{key:"parseThemeAttribute",value:function(){var e=this.getAttribute("theme");if(e)return["light","dark","system"].includes(e)?{preference:e}:void 0}},{key:"config",get:function(){return this._config},set:function(e){this._config=e,e.icons&&af(e.icons),this.isConnected&&(this.setupTheme(),this.renderViewer())}},{key:"registry",get:function(){return this._registryPromise}},{key:"themePreference",get:function(){var e;return(null===(e=this._config)||void 0===e||null===(e=e.theme)||void 0===e?void 0:e.preference)||"system"}},{key:"activeColorScheme",get:function(){return Nb(this.themePreference)}},{key:"activeTheme",get:function(){return this.resolveActiveTheme()}},{key:"resolveActiveTheme",value:function(){var e,t,n,o=null===(e=this._config)||void 0===e?void 0:e.theme,i=Nb((null==o?void 0:o.preference)||"system"),r="dark"===i?Tb:zb,a=null==o?void 0:o[i];return n=r,(t=a)?_b(n,t):n}},{key:"setupTheme",value:function(){var e,t,n=this;null===(e=this.systemPreferenceCleanup)||void 0===e||e.call(this),this.systemPreferenceCleanup=null,"system"===((null===(t=this._config)||void 0===t||null===(t=t.theme)||void 0===t?void 0:t.preference)||"system")&&(this.systemPreferenceCleanup=function(e){if("undefined"==typeof window)return function(){};var t=window.matchMedia("(prefers-color-scheme: dark)"),n=function(t){return e(t.matches?"dark":"light")};return t.addEventListener("change",n),function(){return t.removeEventListener("change",n)}}(function(e){n.injectTheme(),n.dispatchEvent(new CustomEvent("themechange",{detail:{preference:"system",colorScheme:e,theme:n.activeTheme},bubbles:!0}))})),this.injectTheme()}},{key:"injectTheme",value:function(){var e=Lb(this.resolveActiveTheme()),t=this.root.querySelector("style[data-embedpdf-theme]");t||((t=document.createElement("style")).setAttribute("data-embedpdf-theme",""),this.root.appendChild(t)),this.themeStyleEl=t,this.themeStyleEl.textContent=e,this.setAttribute("data-color-scheme",this.activeColorScheme)}},{key:"setTheme",value:function(e){this._config&&(this._config.theme="string"==typeof e?h(h({},this._config.theme),{},{preference:e}):h(h({},this._config.theme),e),this.setupTheme(),this.dispatchEvent(new CustomEvent("themechange",{detail:{preference:this.themePreference,colorScheme:this.activeColorScheme,theme:this.activeTheme},bubbles:!0})))}},{key:"registerIcon",value:function(e,t){rf(e,t)}},{key:"registerIcons",value:function(e){af(e)}},{key:"renderViewer",value:function(){this._config&&(ce(F(Xb,{config:this._config,onRegistryReady:this.handleRegistryReady}),this.root),this.injectTheme())}}])}(),ew=["type","target"],tw="2.6.2";"undefined"==typeof customElements||customElements.get("embedpdf-container")||customElements.define("embedpdf-container",Jb);var nw={version:tw,init:function(e){if("container"===e.type)return function(e){e.type,e.target;var t=m(e,ew),n=document.createElement("embedpdf-container");return n.config=t,e.target.appendChild(n),n}(e)}};export{Wm as $,Nt as A,Ge as B,ot as C,mt as D,Mt as E,Et as F,on as G,Vt as H,Tn as I,su as J,Pg as K,cm as L,Rm as M,gt as N,ka as O,Qt as P,ga as Q,Be as R,Jb as S,Ct as T,hm as U,nm as V,Fm as W,Oa as X,rh as Y,bm as Z,Zh as _,Jt as a,mg as a0,rs as a1,ps as a2,Ii as a3,hi as a4,Os as a5,kl as a6,Di as a7,Oi as a8,pc as a9,ec as aa,Ur as ab,ai as ac,Fa as ad,Xa as ae,_b as af,Tb as ag,nw as ah,En as ai,zb as aj,rf as ak,af as al,tw as am,_t as b,Xt as c,St as d,Ot as e,Ut as f,Ft as g,Lt as h,Rn as i,Pt as j,Tt as k,At as l,en as m,nn as n,$t as o,rn as p,an as q,Ze as r,Pn as s,Ye as t,zn as u,Ht as v,tn as w,qt as x,Gt as y,jt as z}; diff --git a/src/components/BootstrapBlazor.EmbedPDF/wwwroot/embedpdf-xgzA9lZs.js b/src/components/BootstrapBlazor.EmbedPDF/wwwroot/embedpdf-xgzA9lZs.js new file mode 100644 index 00000000..017babcf --- /dev/null +++ b/src/components/BootstrapBlazor.EmbedPDF/wwwroot/embedpdf-xgzA9lZs.js @@ -0,0 +1,3 @@ +function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,a=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){s=!0,r=e},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw r}}}}function s(e,t,n){return(t=b(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function l(e){return l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},l(e)}function c(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&f(e,t)}function d(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(d=function(){return!!e})()}function u(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function h(e){for(var t=1;t3?(i=g===o)&&(l=r[(s=r[4])?5:(s=3,3)],r[4]=r[5]=e):r[0]<=m&&((i=n<2&&mo||o>g)&&(r[4]=n,r[5]=o,h.n=g,s=0))}if(i||n>1)return a;throw u=!0,o}return function(i,d,g){if(c>1)throw TypeError("Generator is already running");for(u&&1===d&&m(d,g),s=d,l=g;(t=s<2?e:l)||!u;){r||(s?s<3?(s>1&&(h.n=-1),m(s,l)):h.n=l:h.v=l);try{if(c=2,r){if(s||(i="next"),t=r[i]){if(!(t=t.call(r,l)))throw TypeError("iterator result is not an object");if(!t.done)return t;l=t.value,s<2&&(s=0)}else 1===s&&(t=r.return)&&t.call(r),s<2&&(l=TypeError("The iterator does not provide a '"+i+"' method"),s=1);r=e}else if((t=(u=h.n<0)?l:n.call(o,h))!==a)break}catch(t){r=e,s=1,l=t}finally{c=1}}return{value:t,done:u}}}(n,i,r),!0),c}var a={};function s(){}function l(){}function c(){}t=Object.getPrototypeOf;var d=[][o]?t(t([][o]())):(p(t={},o,function(){return this}),t),u=c.prototype=s.prototype=Object.create(d);function h(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,c):(e.__proto__=c,p(e,i,"GeneratorFunction")),e.prototype=Object.create(u),e}return l.prototype=c,p(u,"constructor",c),p(c,"constructor",l),l.displayName="GeneratorFunction",p(c,i,"GeneratorFunction"),p(u),p(u,i,"Generator"),p(u,o,function(){return this}),p(u,"toString",function(){return"[object Generator]"}),(g=function(){return{w:r,m:h}})()}function p(e,t,n,o){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}p=function(e,t,n,o){function r(t,n){p(e,t,function(e){return this._invoke(t,n,e)})}t?i?i(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(r("next",0),r("throw",1),r("return",2))},p(e,t,n,o)}function f(e,t){return f=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},f(e,t)}function v(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var o,i,r,a,s=[],l=!0,c=!1;try{if(r=(n=n.call(e)).next,0===t);else for(;!(l=(o=r.call(n)).done)&&(s.push(o.value),s.length!==t);l=!0);}catch(e){c=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return s}}(e,t)||x(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function y(t){return function(t){if(Array.isArray(t))return e(t)}(t)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(t)||x(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function b(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var o=n.call(e,t);if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function w(e){return w="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},w(e)}function x(t,n){if(t){if("string"==typeof t)return e(t,n);var o={}.toString.call(t).slice(8,-1);return"Object"===o&&t.constructor&&(o=t.constructor.name),"Map"===o||"Set"===o?Array.from(t):"Arguments"===o||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o)?e(t,n):void 0}}var C,k,I,S,A,M,P,D,R,z,T,E,_={},N=[],L=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,O=Array.isArray;function $(e,t){for(var n in t)e[n]=t[n];return e}function j(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function F(e,t,n){var o,i,r,a={};for(r in t)"key"==r?o=t[r]:"ref"==r?i=t[r]:a[r]=t[r];if(arguments.length>2&&(a.children=arguments.length>3?C.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(r in e.defaultProps)void 0===a[r]&&(a[r]=e.defaultProps[r]);return U(e,a,o,i,null)}function U(e,t,n,o,i){var r={type:e,props:t,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==i?++I:i,__i:-1,__u:0};return null==i&&null!=k.vnode&&k.vnode(r),r}function H(e){return e.children}function W(e,t){this.props=e,this.context=t}function B(e,t){if(null==t)return e.__?B(e.__,e.__i+1):null;for(var n;ts&&S.sort(P),e=S.shift(),s=S.length,e.__d&&(n=void 0,o=void 0,i=(o=(t=e).__v).__e,r=[],a=[],t.__P&&((n=$({},o)).__v=o.__v+1,k.vnode&&k.vnode(n),te(t.__P,n,o,t.__n,t.__P.namespaceURI,32&o.__u?[i]:null,r,null==i?B(o):i,!!(32&o.__u),a),n.__v=o.__v,n.__.__k[n.__i]=n,oe(r,n,a),o.__e=o.__=null,n.__e!=i&&q(n)));V.__r=0}function K(e,t,n,o,i,r,a,s,l,c,d){var u,h,m,g,p,f,v,y=o&&o.__k||N,b=t.length;for(l=function(e,t,n,o,i){var r,a,s,l,c,d=n.length,u=d,h=0;for(e.__k=new Array(i),r=0;r0?a=e.__k[r]=U(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):e.__k[r]=a,l=r+h,a.__=e,a.__b=e.__b+1,s=null,-1!=(c=a.__i=X(a,n,l,u))&&(u--,(s=n[c])&&(s.__u|=2)),null==s||null==s.__v?(-1==c&&(i>d?h--:il?h--:h++,a.__u|=4))):e.__k[r]=null;if(u)for(r=0;r(d?1:0))for(i=n-1,r=n+1;i>=0||r=0?i--:r++])&&!(2&c.__u)&&s==c.key&&l==c.type)return a;return-1}function Q(e,t,n){"-"==t[0]?e.setProperty(t,null==n?"":n):e[t]=null==n?"":"number"!=typeof n||L.test(t)?n:n+"px"}function J(e,t,n,o,i){var r,a;e:if("style"==t)if("string"==typeof n)e.style.cssText=n;else{if("string"==typeof o&&(e.style.cssText=o=""),o)for(t in o)n&&t in n||Q(e.style,t,"");if(n)for(t in n)o&&n[t]==o[t]||Q(e.style,t,n[t])}else if("o"==t[0]&&"n"==t[1])r=t!=(t=t.replace(D,"$1")),a=t.toLowerCase(),t=a in e||"onFocusOut"==t||"onFocusIn"==t?a.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+r]=n,n?o?n.u=o.u:(n.u=R,e.addEventListener(t,r?T:z,r)):e.removeEventListener(t,r?T:z,r);else{if("http://www.w3.org/2000/svg"==i)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=t&&"height"!=t&&"href"!=t&&"list"!=t&&"form"!=t&&"tabIndex"!=t&&"download"!=t&&"rowSpan"!=t&&"colSpan"!=t&&"role"!=t&&"popover"!=t&&t in e)try{e[t]=null==n?"":n;break e}catch(e){}"function"==typeof n||(null==n||!1===n&&"-"!=t[4]?e.removeAttribute(t):e.setAttribute(t,"popover"==t&&1==n?"":n))}}function ee(e){return function(t){if(this.l){var n=this.l[t.type+e];if(null==t.t)t.t=R++;else if(t.t0?e:O(e)?e.map(ie):$({},e)}function re(e,t,n,o,i,r,a,s,l){var c,d,u,h,m,g,p,f=n.props||_,v=t.props,y=t.type;if("svg"==y?i="http://www.w3.org/2000/svg":"math"==y?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),null!=r)for(c=0;c=n.__.length&&n.__.push({}),n.__[e]}function Se(e){return pe=1,Ae(je,e)}function Ae(e,t,n){var o=Ie(ue++,2);if(o.t=e,!o.__c&&(o.__=[n?n(t):je(void 0,t),function(e){var t=o.__N?o.__N[0]:o.__[0],n=o.t(t,e);t!==n&&(o.__N=[n,o.__[1]],o.__c.setState({}))}],o.__c=he,!he.__f)){var i=function(e,t,n){if(!o.__c.__H)return!0;var i=o.__c.__H.__.filter(function(e){return!!e.__c});if(i.every(function(e){return!e.__N}))return!r||r.call(this,e,t,n);var a=o.__c.props!==e;return i.forEach(function(e){if(e.__N){var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(a=!0)}}),r&&r.call(this,e,t,n)||a};he.__f=!0;var r=he.shouldComponentUpdate,a=he.componentWillUpdate;he.componentWillUpdate=function(e,t,n){if(this.__e){var o=r;r=void 0,i(e,t,n),r=o}a&&a.call(this,e,t,n)},he.shouldComponentUpdate=i}return o.__N||o.__}function Me(e,t){var n=Ie(ue++,3);!ve.__s&&$e(n.__H,t)&&(n.__=e,n.u=t,he.__H.__h.push(n))}function Pe(e,t){var n=Ie(ue++,4);!ve.__s&&$e(n.__H,t)&&(n.__=e,n.u=t,he.__h.push(n))}function De(e){return pe=5,Re(function(){return{current:e}},[])}function Re(e,t){var n=Ie(ue++,7);return $e(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function ze(e,t){return pe=8,Re(function(){return e},t)}function Te(e){var t=he.context[e.__c],n=Ie(ue++,9);return n.c=e,t?(null==n.__&&(n.__=!0,t.sub(he)),t.props.value):e.__}function Ee(){for(var e;e=fe.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(Le),e.__H.__h.forEach(Oe),e.__H.__h=[]}catch(t){e.__H.__h=[],ve.__e(t,e.__v)}}ve.__b=function(e){he=null,ye&&ye(e)},ve.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),ke&&ke(e,t)},ve.__r=function(e){be&&be(e),ue=0;var t=(he=e.__c).__H;t&&(me===he?(t.__h=[],he.__h=[],t.__.forEach(function(e){e.__N&&(e.__=e.__N),e.u=e.__N=void 0})):(t.__h.forEach(Le),t.__h.forEach(Oe),t.__h=[],ue=0)),me=he},ve.diffed=function(e){we&&we(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==fe.push(t)&&ge===ve.requestAnimationFrame||((ge=ve.requestAnimationFrame)||Ne)(Ee)),t.__H.__.forEach(function(e){e.u&&(e.__H=e.u),e.u=void 0})),me=he=null},ve.__c=function(e,t){t.some(function(e){try{e.__h.forEach(Le),e.__h=e.__h.filter(function(e){return!e.__||Oe(e)})}catch(n){t.some(function(e){e.__h&&(e.__h=[])}),t=[],ve.__e(n,e.__v)}}),xe&&xe(e,t)},ve.unmount=function(e){Ce&&Ce(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach(function(e){try{Le(e)}catch(e){t=e}}),n.__H=void 0,t&&ve.__e(t,n.__v))};var _e="function"==typeof requestAnimationFrame;function Ne(e){var t,n=function(){clearTimeout(o),_e&&cancelAnimationFrame(t),setTimeout(e)},o=setTimeout(n,35);_e&&(t=requestAnimationFrame(n))}function Le(e){var t=he,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),he=t}function Oe(e){var t=he;e.__c=e.__(),he=t}function $e(e,t){return!e||e.length!==t.length||t.some(function(t,n){return t!==e[n]})}function je(e,t){return"function"==typeof t?t(e):t}var Fe='/*! tailwindcss v4.1.18 | MIT License | https://tailwindcss.com */\n@layer properties;\n@layer theme, base, components, utilities;\n@layer theme {\n :root, :host {\n --font-sans: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji",\n "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";\n --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono",\n "Courier New", monospace;\n --color-red-500: oklch(63.7% 0.237 25.331);\n --color-yellow-500: oklch(79.5% 0.184 86.047);\n --color-green-500: oklch(72.3% 0.219 149.579);\n --color-teal-500: oklch(70.4% 0.14 182.503);\n --color-blue-500: oklch(62.3% 0.214 259.815);\n --color-indigo-500: oklch(58.5% 0.233 277.117);\n --color-purple-500: oklch(62.7% 0.265 303.9);\n --color-pink-500: oklch(65.6% 0.241 354.308);\n --color-gray-300: oklch(87.2% 0.01 258.338);\n --color-white: #fff;\n --spacing: 0.25rem;\n --container-sm: 24rem;\n --text-xs: 0.75rem;\n --text-xs--line-height: calc(1 / 0.75);\n --text-sm: 0.875rem;\n --text-sm--line-height: calc(1.25 / 0.875);\n --text-base: 1rem;\n --text-base--line-height: calc(1.5 / 1);\n --text-lg: 1.125rem;\n --text-lg--line-height: calc(1.75 / 1.125);\n --text-xl: 1.25rem;\n --text-xl--line-height: calc(1.75 / 1.25);\n --font-weight-medium: 500;\n --font-weight-semibold: 600;\n --font-weight-bold: 700;\n --leading-relaxed: 1.625;\n --radius-md: 0.375rem;\n --radius-lg: 0.5rem;\n --radius-xl: 0.75rem;\n --radius-2xl: 1rem;\n --ease-out: cubic-bezier(0, 0, 0.2, 1);\n --ease-in-out: cubic-bezier(0.4, 0, 0.2, 1);\n --animate-spin: spin 1s linear infinite;\n --animate-pulse: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;\n --default-transition-duration: 150ms;\n --default-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);\n --default-font-family: var(--font-sans);\n --default-mono-font-family: var(--font-mono);\n --color-bg-app: var(--ep-background-app);\n --color-bg-surface: var(--ep-background-surface);\n --color-bg-surface-alt: var(--ep-background-surface-alt);\n --color-bg-elevated: var(--ep-background-elevated);\n --color-bg-overlay: var(--ep-background-overlay);\n --color-bg-input: var(--ep-background-input);\n --color-fg-primary: var(--ep-foreground-primary);\n --color-fg-secondary: var(--ep-foreground-secondary);\n --color-fg-muted: var(--ep-foreground-muted);\n --color-fg-disabled: var(--ep-foreground-disabled);\n --color-fg-on-accent: var(--ep-foreground-on-accent);\n --color-border-default: var(--ep-border-default);\n --color-border-subtle: var(--ep-border-subtle);\n --color-border-strong: var(--ep-border-strong);\n --color-accent: var(--ep-accent-primary);\n --color-accent-hover: var(--ep-accent-primary-hover);\n --color-accent-light: var(--ep-accent-primary-light);\n --color-accent-fg: var(--ep-accent-primary-foreground);\n --color-interactive-hover: var(--ep-interactive-hover);\n --color-interactive-active: var(--ep-interactive-active);\n --color-interactive-selected: var(--ep-interactive-selected);\n --color-interactive-focus-ring: var(--ep-interactive-focus-ring);\n --color-state-error: var(--ep-state-error);\n --color-state-error-light: var(--ep-state-error-light);\n --color-state-warning: var(--ep-state-warning);\n --color-state-warning-light: var(--ep-state-warning-light);\n --color-state-success: var(--ep-state-success);\n --color-state-success-light: var(--ep-state-success-light);\n --color-state-info-light: var(--ep-state-info-light);\n --color-tooltip-bg: var(--ep-tooltip-background);\n --color-tooltip-fg: var(--ep-tooltip-foreground);\n }\n}\n@layer base {\n *, ::after, ::before, ::backdrop, ::file-selector-button {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n border: 0 solid;\n }\n html, :host {\n line-height: 1.5;\n -webkit-text-size-adjust: 100%;\n -moz-tab-size: 4;\n -o-tab-size: 4;\n tab-size: 4;\n font-family: var(--default-font-family, ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");\n font-feature-settings: var(--default-font-feature-settings, normal);\n font-variation-settings: var(--default-font-variation-settings, normal);\n -webkit-tap-highlight-color: transparent;\n }\n hr {\n height: 0;\n color: inherit;\n border-top-width: 1px;\n }\n abbr:where([title]) {\n -webkit-text-decoration: underline dotted;\n text-decoration: underline dotted;\n }\n h1, h2, h3, h4, h5, h6 {\n font-size: inherit;\n font-weight: inherit;\n }\n a {\n color: inherit;\n -webkit-text-decoration: inherit;\n text-decoration: inherit;\n }\n b, strong {\n font-weight: bolder;\n }\n code, kbd, samp, pre {\n font-family: var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);\n font-feature-settings: var(--default-mono-font-feature-settings, normal);\n font-variation-settings: var(--default-mono-font-variation-settings, normal);\n font-size: 1em;\n }\n small {\n font-size: 80%;\n }\n sub, sup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n }\n sub {\n bottom: -0.25em;\n }\n sup {\n top: -0.5em;\n }\n table {\n text-indent: 0;\n border-color: inherit;\n border-collapse: collapse;\n }\n :-moz-focusring {\n outline: auto;\n }\n progress {\n vertical-align: baseline;\n }\n summary {\n display: list-item;\n }\n ol, ul, menu {\n list-style: none;\n }\n img, svg, video, canvas, audio, iframe, embed, object {\n display: block;\n vertical-align: middle;\n }\n img, video {\n max-width: 100%;\n height: auto;\n }\n button, input, select, optgroup, textarea, ::file-selector-button {\n font: inherit;\n font-feature-settings: inherit;\n font-variation-settings: inherit;\n letter-spacing: inherit;\n color: inherit;\n border-radius: 0;\n background-color: transparent;\n opacity: 1;\n }\n :where(select:is([multiple], [size])) optgroup {\n font-weight: bolder;\n }\n :where(select:is([multiple], [size])) optgroup option {\n padding-inline-start: 20px;\n }\n ::file-selector-button {\n margin-inline-end: 4px;\n }\n ::-moz-placeholder {\n opacity: 1;\n }\n ::placeholder {\n opacity: 1;\n }\n @supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) {\n ::-moz-placeholder {\n color: currentcolor;\n @supports (color: color-mix(in lab, red, red)) {\n color: color-mix(in oklab, currentcolor 50%, transparent);\n }\n }\n ::placeholder {\n color: currentcolor;\n @supports (color: color-mix(in lab, red, red)) {\n color: color-mix(in oklab, currentcolor 50%, transparent);\n }\n }\n }\n textarea {\n resize: vertical;\n }\n ::-webkit-search-decoration {\n -webkit-appearance: none;\n }\n ::-webkit-date-and-time-value {\n min-height: 1lh;\n text-align: inherit;\n }\n ::-webkit-datetime-edit {\n display: inline-flex;\n }\n ::-webkit-datetime-edit-fields-wrapper {\n padding: 0;\n }\n ::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field {\n padding-block: 0;\n }\n ::-webkit-calendar-picker-indicator {\n line-height: 1;\n }\n :-moz-ui-invalid {\n box-shadow: none;\n }\n button, input:where([type="button"], [type="reset"], [type="submit"]), ::file-selector-button {\n -webkit-appearance: button;\n -moz-appearance: button;\n appearance: button;\n }\n ::-webkit-inner-spin-button, ::-webkit-outer-spin-button {\n height: auto;\n }\n [hidden]:where(:not([hidden="until-found"])) {\n display: none !important;\n }\n}\n@layer utilities {\n .pointer-events-auto {\n pointer-events: auto;\n }\n .pointer-events-none {\n pointer-events: none;\n }\n .invisible {\n visibility: hidden;\n }\n .visible {\n visibility: visible;\n }\n .absolute {\n position: absolute;\n }\n .fixed {\n position: fixed;\n }\n .relative {\n position: relative;\n }\n .static {\n position: static;\n }\n .sticky {\n position: sticky;\n }\n .inset-0 {\n inset: calc(var(--spacing) * 0);\n }\n .inset-x-0 {\n inset-inline: calc(var(--spacing) * 0);\n }\n .inset-y-0 {\n inset-block: calc(var(--spacing) * 0);\n }\n .top-0 {\n top: calc(var(--spacing) * 0);\n }\n .top-1\\/2 {\n top: calc(1/2 * 100%);\n }\n .top-4 {\n top: calc(var(--spacing) * 4);\n }\n .top-6 {\n top: calc(var(--spacing) * 6);\n }\n .right-0 {\n right: calc(var(--spacing) * 0);\n }\n .right-1 {\n right: calc(var(--spacing) * 1);\n }\n .right-2 {\n right: calc(var(--spacing) * 2);\n }\n .right-4 {\n right: calc(var(--spacing) * 4);\n }\n .bottom-0 {\n bottom: calc(var(--spacing) * 0);\n }\n .left-0 {\n left: calc(var(--spacing) * 0);\n }\n .left-1\\/2 {\n left: calc(1/2 * 100%);\n }\n .z-3 {\n z-index: 3;\n }\n .z-10 {\n z-index: 10;\n }\n .z-40 {\n z-index: 40;\n }\n .z-50 {\n z-index: 50;\n }\n .z-100 {\n z-index: 100;\n }\n .col-start-1 {\n grid-column-start: 1;\n }\n .row-start-1 {\n grid-row-start: 1;\n }\n .container {\n width: 100%;\n @media (width >= 40rem) {\n max-width: 40rem;\n }\n @media (width >= 48rem) {\n max-width: 48rem;\n }\n @media (width >= 64rem) {\n max-width: 64rem;\n }\n @media (width >= 80rem) {\n max-width: 80rem;\n }\n @media (width >= 96rem) {\n max-width: 96rem;\n }\n }\n .mx-4 {\n margin-inline: calc(var(--spacing) * 4);\n }\n .my-2 {\n margin-block: calc(var(--spacing) * 2);\n }\n .my-4 {\n margin-block: calc(var(--spacing) * 4);\n }\n .-mt-1 {\n margin-top: calc(var(--spacing) * -1);\n }\n .mt-0\\.5 {\n margin-top: calc(var(--spacing) * 0.5);\n }\n .mt-1 {\n margin-top: calc(var(--spacing) * 1);\n }\n .mt-2 {\n margin-top: calc(var(--spacing) * 2);\n }\n .mt-3 {\n margin-top: calc(var(--spacing) * 3);\n }\n .mt-4 {\n margin-top: calc(var(--spacing) * 4);\n }\n .mt-5 {\n margin-top: calc(var(--spacing) * 5);\n }\n .mt-6 {\n margin-top: calc(var(--spacing) * 6);\n }\n .-mr-1 {\n margin-right: calc(var(--spacing) * -1);\n }\n .mr-1\\.5 {\n margin-right: calc(var(--spacing) * 1.5);\n }\n .mr-2 {\n margin-right: calc(var(--spacing) * 2);\n }\n .mr-3 {\n margin-right: calc(var(--spacing) * 3);\n }\n .mr-4 {\n margin-right: calc(var(--spacing) * 4);\n }\n .mb-1 {\n margin-bottom: calc(var(--spacing) * 1);\n }\n .mb-1\\.5 {\n margin-bottom: calc(var(--spacing) * 1.5);\n }\n .mb-2 {\n margin-bottom: calc(var(--spacing) * 2);\n }\n .mb-3 {\n margin-bottom: calc(var(--spacing) * 3);\n }\n .mb-4 {\n margin-bottom: calc(var(--spacing) * 4);\n }\n .mb-6 {\n margin-bottom: calc(var(--spacing) * 6);\n }\n .ml-1 {\n margin-left: calc(var(--spacing) * 1);\n }\n .ml-2 {\n margin-left: calc(var(--spacing) * 2);\n }\n .block {\n display: block;\n }\n .contents {\n display: contents;\n }\n .flex {\n display: flex;\n }\n .grid {\n display: grid;\n }\n .hidden {\n display: none;\n }\n .inline {\n display: inline;\n }\n .inline-block {\n display: inline-block;\n }\n .inline-flex {\n display: inline-flex;\n }\n .h-1 {\n height: calc(var(--spacing) * 1);\n }\n .h-1\\.5 {\n height: calc(var(--spacing) * 1.5);\n }\n .h-2 {\n height: calc(var(--spacing) * 2);\n }\n .h-3 {\n height: calc(var(--spacing) * 3);\n }\n .h-3\\.5 {\n height: calc(var(--spacing) * 3.5);\n }\n .h-4 {\n height: calc(var(--spacing) * 4);\n }\n .h-5 {\n height: calc(var(--spacing) * 5);\n }\n .h-6 {\n height: calc(var(--spacing) * 6);\n }\n .h-7 {\n height: calc(var(--spacing) * 7);\n }\n .h-8 {\n height: calc(var(--spacing) * 8);\n }\n .h-9 {\n height: calc(var(--spacing) * 9);\n }\n .h-10 {\n height: calc(var(--spacing) * 10);\n }\n .h-16 {\n height: calc(var(--spacing) * 16);\n }\n .h-18 {\n height: calc(var(--spacing) * 18);\n }\n .h-\\[32px\\] {\n height: 32px;\n }\n .h-full {\n height: 100%;\n }\n .h-px {\n height: 1px;\n }\n .max-h-48 {\n max-height: calc(var(--spacing) * 48);\n }\n .max-h-60 {\n max-height: calc(var(--spacing) * 60);\n }\n .min-h-0 {\n min-height: calc(var(--spacing) * 0);\n }\n .\\!w-full {\n width: 100% !important;\n }\n .w-2 {\n width: calc(var(--spacing) * 2);\n }\n .w-3 {\n width: calc(var(--spacing) * 3);\n }\n .w-3\\.5 {\n width: calc(var(--spacing) * 3.5);\n }\n .w-4 {\n width: calc(var(--spacing) * 4);\n }\n .w-5 {\n width: calc(var(--spacing) * 5);\n }\n .w-6 {\n width: calc(var(--spacing) * 6);\n }\n .w-8 {\n width: calc(var(--spacing) * 8);\n }\n .w-9 {\n width: calc(var(--spacing) * 9);\n }\n .w-10 {\n width: calc(var(--spacing) * 10);\n }\n .w-12 {\n width: calc(var(--spacing) * 12);\n }\n .w-16 {\n width: calc(var(--spacing) * 16);\n }\n .w-18 {\n width: calc(var(--spacing) * 18);\n }\n .w-32 {\n width: calc(var(--spacing) * 32);\n }\n .w-\\[32px\\] {\n width: 32px;\n }\n .w-auto {\n width: auto;\n }\n .w-full {\n width: 100%;\n }\n .w-px {\n width: 1px;\n }\n .max-w-\\[150px\\] {\n max-width: 150px;\n }\n .max-w-\\[240px\\] {\n max-width: 240px;\n }\n .max-w-sm {\n max-width: var(--container-sm);\n }\n .min-w-0 {\n min-width: calc(var(--spacing) * 0);\n }\n .min-w-\\[8rem\\] {\n min-width: 8rem;\n }\n .min-w-\\[32px\\] {\n min-width: 32px;\n }\n .min-w-\\[120px\\] {\n min-width: 120px;\n }\n .min-w-\\[200px\\] {\n min-width: 200px;\n }\n .flex-1 {\n flex: 1;\n }\n .flex-shrink-0 {\n flex-shrink: 0;\n }\n .shrink-0 {\n flex-shrink: 0;\n }\n .-translate-x-1\\/2 {\n --tw-translate-x: calc(calc(1/2 * 100%) * -1);\n translate: var(--tw-translate-x) var(--tw-translate-y);\n }\n .translate-x-\\[1px\\] {\n --tw-translate-x: 1px;\n translate: var(--tw-translate-x) var(--tw-translate-y);\n }\n .-translate-y-1\\/2 {\n --tw-translate-y: calc(calc(1/2 * 100%) * -1);\n translate: var(--tw-translate-x) var(--tw-translate-y);\n }\n .translate-y-\\[1px\\] {\n --tw-translate-y: 1px;\n translate: var(--tw-translate-x) var(--tw-translate-y);\n }\n .scale-95 {\n --tw-scale-x: 95%;\n --tw-scale-y: 95%;\n --tw-scale-z: 95%;\n scale: var(--tw-scale-x) var(--tw-scale-y);\n }\n .scale-100 {\n --tw-scale-x: 100%;\n --tw-scale-y: 100%;\n --tw-scale-z: 100%;\n scale: var(--tw-scale-x) var(--tw-scale-y);\n }\n .rotate-45 {\n rotate: 45deg;\n }\n .rotate-180 {\n rotate: 180deg;\n }\n .transform {\n transform: var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,);\n }\n .animate-pulse {\n animation: var(--animate-pulse);\n }\n .animate-spin {\n animation: var(--animate-spin);\n }\n .cursor-default {\n cursor: default;\n }\n .cursor-grab {\n cursor: grab;\n }\n .cursor-not-allowed {\n cursor: not-allowed;\n }\n .cursor-pointer {\n cursor: pointer;\n }\n .touch-none {\n touch-action: none;\n }\n .resize {\n resize: both;\n }\n .appearance-none {\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n }\n .grid-cols-1 {\n grid-template-columns: repeat(1, minmax(0, 1fr));\n }\n .grid-cols-2 {\n grid-template-columns: repeat(2, minmax(0, 1fr));\n }\n .grid-cols-6 {\n grid-template-columns: repeat(6, minmax(0, 1fr));\n }\n .flex-col {\n flex-direction: column;\n }\n .flex-row {\n flex-direction: row;\n }\n .flex-wrap {\n flex-wrap: wrap;\n }\n .items-center {\n align-items: center;\n }\n .items-end {\n align-items: flex-end;\n }\n .items-start {\n align-items: flex-start;\n }\n .justify-between {\n justify-content: space-between;\n }\n .justify-center {\n justify-content: center;\n }\n .justify-end {\n justify-content: flex-end;\n }\n .justify-start {\n justify-content: flex-start;\n }\n .gap-1 {\n gap: calc(var(--spacing) * 1);\n }\n .gap-2 {\n gap: calc(var(--spacing) * 2);\n }\n .gap-3 {\n gap: calc(var(--spacing) * 3);\n }\n .gap-4 {\n gap: calc(var(--spacing) * 4);\n }\n .space-y-2 {\n :where(& > :not(:last-child)) {\n --tw-space-y-reverse: 0;\n margin-block-start: calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));\n margin-block-end: calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)));\n }\n }\n .space-y-3 {\n :where(& > :not(:last-child)) {\n --tw-space-y-reverse: 0;\n margin-block-start: calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));\n margin-block-end: calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)));\n }\n }\n .space-y-4 {\n :where(& > :not(:last-child)) {\n --tw-space-y-reverse: 0;\n margin-block-start: calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));\n margin-block-end: calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)));\n }\n }\n .space-y-5 {\n :where(& > :not(:last-child)) {\n --tw-space-y-reverse: 0;\n margin-block-start: calc(calc(var(--spacing) * 5) * var(--tw-space-y-reverse));\n margin-block-end: calc(calc(var(--spacing) * 5) * calc(1 - var(--tw-space-y-reverse)));\n }\n }\n .space-y-6 {\n :where(& > :not(:last-child)) {\n --tw-space-y-reverse: 0;\n margin-block-start: calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));\n margin-block-end: calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)));\n }\n }\n .gap-x-1 {\n -moz-column-gap: calc(var(--spacing) * 1);\n column-gap: calc(var(--spacing) * 1);\n }\n .space-x-2 {\n :where(& > :not(:last-child)) {\n --tw-space-x-reverse: 0;\n margin-inline-start: calc(calc(var(--spacing) * 2) * var(--tw-space-x-reverse));\n margin-inline-end: calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-x-reverse)));\n }\n }\n .space-x-3 {\n :where(& > :not(:last-child)) {\n --tw-space-x-reverse: 0;\n margin-inline-start: calc(calc(var(--spacing) * 3) * var(--tw-space-x-reverse));\n margin-inline-end: calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-x-reverse)));\n }\n }\n .gap-y-4 {\n row-gap: calc(var(--spacing) * 4);\n }\n .divide-y {\n :where(& > :not(:last-child)) {\n --tw-divide-y-reverse: 0;\n border-bottom-style: var(--tw-border-style);\n border-top-style: var(--tw-border-style);\n border-top-width: calc(1px * var(--tw-divide-y-reverse));\n border-bottom-width: calc(1px * calc(1 - var(--tw-divide-y-reverse)));\n }\n }\n .divide-border-subtle {\n :where(& > :not(:last-child)) {\n border-color: var(--color-border-subtle);\n }\n }\n .truncate {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n .overflow-auto {\n overflow: auto;\n }\n .overflow-hidden {\n overflow: hidden;\n }\n .overflow-x-auto {\n overflow-x: auto;\n }\n .overflow-y-auto {\n overflow-y: auto;\n }\n .rounded {\n border-radius: 0.25rem;\n }\n .rounded-\\[3px\\] {\n border-radius: 3px;\n }\n .rounded-full {\n border-radius: calc(infinity * 1px);\n }\n .rounded-lg {\n border-radius: var(--radius-lg);\n }\n .rounded-md {\n border-radius: var(--radius-md);\n }\n .rounded-none {\n border-radius: 0;\n }\n .rounded-xl {\n border-radius: var(--radius-xl);\n }\n .rounded-t-2xl {\n border-top-left-radius: var(--radius-2xl);\n border-top-right-radius: var(--radius-2xl);\n }\n .rounded-t-lg {\n border-top-left-radius: var(--radius-lg);\n border-top-right-radius: var(--radius-lg);\n }\n .rounded-l-md {\n border-top-left-radius: var(--radius-md);\n border-bottom-left-radius: var(--radius-md);\n }\n .rounded-r-md {\n border-top-right-radius: var(--radius-md);\n border-bottom-right-radius: var(--radius-md);\n }\n .border {\n border-style: var(--tw-border-style);\n border-width: 1px;\n }\n .border-0 {\n border-style: var(--tw-border-style);\n border-width: 0px;\n }\n .border-2 {\n border-style: var(--tw-border-style);\n border-width: 2px;\n }\n .border-3 {\n border-style: var(--tw-border-style);\n border-width: 3px;\n }\n .border-4 {\n border-style: var(--tw-border-style);\n border-width: 4px;\n }\n .border-t {\n border-top-style: var(--tw-border-style);\n border-top-width: 1px;\n }\n .border-r {\n border-right-style: var(--tw-border-style);\n border-right-width: 1px;\n }\n .border-r-0 {\n border-right-style: var(--tw-border-style);\n border-right-width: 0px;\n }\n .border-b {\n border-bottom-style: var(--tw-border-style);\n border-bottom-width: 1px;\n }\n .border-b-2 {\n border-bottom-style: var(--tw-border-style);\n border-bottom-width: 2px;\n }\n .border-l {\n border-left-style: var(--tw-border-style);\n border-left-width: 1px;\n }\n .border-none {\n --tw-border-style: none;\n border-style: none;\n }\n .border-\\[\\#cfd4da\\] {\n border-color: #cfd4da;\n }\n .border-accent {\n border-color: var(--color-accent);\n }\n .border-border-default {\n border-color: var(--color-border-default);\n }\n .border-border-strong {\n border-color: var(--color-border-strong);\n }\n .border-border-subtle {\n border-color: var(--color-border-subtle);\n }\n .border-gray-300 {\n border-color: var(--color-gray-300);\n }\n .border-state-error {\n border-color: var(--color-state-error);\n }\n .border-transparent {\n border-color: transparent;\n }\n .border-t-accent {\n border-top-color: var(--color-accent);\n }\n .border-r-accent {\n border-right-color: var(--color-accent);\n }\n .border-b-accent {\n border-bottom-color: var(--color-accent);\n }\n .border-b-transparent {\n border-bottom-color: transparent;\n }\n .bg-\\[\\#f8f9fa\\] {\n background-color: #f8f9fa;\n }\n .bg-accent {\n background-color: var(--color-accent);\n }\n .bg-accent-light {\n background-color: var(--color-accent-light);\n }\n .bg-accent\\/10 {\n background-color: var(--color-accent);\n @supports (color: color-mix(in lab, red, red)) {\n background-color: color-mix(in oklab, var(--color-accent) 10%, transparent);\n }\n }\n .bg-bg-app {\n background-color: var(--color-bg-app);\n }\n .bg-bg-elevated {\n background-color: var(--color-bg-elevated);\n }\n .bg-bg-input {\n background-color: var(--color-bg-input);\n }\n .bg-bg-overlay {\n background-color: var(--color-bg-overlay);\n }\n .bg-bg-surface {\n background-color: var(--color-bg-surface);\n }\n .bg-bg-surface-alt {\n background-color: var(--color-bg-surface-alt);\n }\n .bg-bg-surface\\/80 {\n background-color: var(--color-bg-surface);\n @supports (color: color-mix(in lab, red, red)) {\n background-color: color-mix(in oklab, var(--color-bg-surface) 80%, transparent);\n }\n }\n .bg-blue-500 {\n background-color: var(--color-blue-500);\n }\n .bg-border-default {\n background-color: var(--color-border-default);\n }\n .bg-border-subtle {\n background-color: var(--color-border-subtle);\n }\n .bg-green-500 {\n background-color: var(--color-green-500);\n }\n .bg-indigo-500 {\n background-color: var(--color-indigo-500);\n }\n .bg-inherit {\n background-color: inherit;\n }\n .bg-interactive-hover {\n background-color: var(--color-interactive-hover);\n }\n .bg-interactive-selected {\n background-color: var(--color-interactive-selected);\n }\n .bg-pink-500 {\n background-color: var(--color-pink-500);\n }\n .bg-purple-500 {\n background-color: var(--color-purple-500);\n }\n .bg-red-500 {\n background-color: var(--color-red-500);\n }\n .bg-state-error {\n background-color: var(--color-state-error);\n }\n .bg-state-error-light {\n background-color: var(--color-state-error-light);\n }\n .bg-state-info-light {\n background-color: var(--color-state-info-light);\n }\n .bg-state-success-light {\n background-color: var(--color-state-success-light);\n }\n .bg-state-warning-light {\n background-color: var(--color-state-warning-light);\n }\n .bg-teal-500 {\n background-color: var(--color-teal-500);\n }\n .bg-tooltip-bg {\n background-color: var(--color-tooltip-bg);\n }\n .bg-transparent {\n background-color: transparent;\n }\n .bg-white {\n background-color: var(--color-white);\n }\n .bg-yellow-500 {\n background-color: var(--color-yellow-500);\n }\n .p-0 {\n padding: calc(var(--spacing) * 0);\n }\n .p-1 {\n padding: calc(var(--spacing) * 1);\n }\n .p-1\\.5 {\n padding: calc(var(--spacing) * 1.5);\n }\n .p-2 {\n padding: calc(var(--spacing) * 2);\n }\n .p-3 {\n padding: calc(var(--spacing) * 3);\n }\n .p-4 {\n padding: calc(var(--spacing) * 4);\n }\n .p-5 {\n padding: calc(var(--spacing) * 5);\n }\n .p-6 {\n padding: calc(var(--spacing) * 6);\n }\n .p-8 {\n padding: calc(var(--spacing) * 8);\n }\n .p-\\[5px\\] {\n padding: 5px;\n }\n .px-1 {\n padding-inline: calc(var(--spacing) * 1);\n }\n .px-2 {\n padding-inline: calc(var(--spacing) * 2);\n }\n .px-3 {\n padding-inline: calc(var(--spacing) * 3);\n }\n .px-4 {\n padding-inline: calc(var(--spacing) * 4);\n }\n .px-5 {\n padding-inline: calc(var(--spacing) * 5);\n }\n .px-6 {\n padding-inline: calc(var(--spacing) * 6);\n }\n .py-1 {\n padding-block: calc(var(--spacing) * 1);\n }\n .py-1\\.5 {\n padding-block: calc(var(--spacing) * 1.5);\n }\n .py-2 {\n padding-block: calc(var(--spacing) * 2);\n }\n .py-2\\.5 {\n padding-block: calc(var(--spacing) * 2.5);\n }\n .py-3 {\n padding-block: calc(var(--spacing) * 3);\n }\n .py-4 {\n padding-block: calc(var(--spacing) * 4);\n }\n .pt-2 {\n padding-top: calc(var(--spacing) * 2);\n }\n .pt-3 {\n padding-top: calc(var(--spacing) * 3);\n }\n .pt-4 {\n padding-top: calc(var(--spacing) * 4);\n }\n .pr-2 {\n padding-right: calc(var(--spacing) * 2);\n }\n .pr-3 {\n padding-right: calc(var(--spacing) * 3);\n }\n .pr-6 {\n padding-right: calc(var(--spacing) * 6);\n }\n .pr-7 {\n padding-right: calc(var(--spacing) * 7);\n }\n .pr-9 {\n padding-right: calc(var(--spacing) * 9);\n }\n .pr-10 {\n padding-right: calc(var(--spacing) * 10);\n }\n .pb-3 {\n padding-bottom: calc(var(--spacing) * 3);\n }\n .pb-4 {\n padding-bottom: calc(var(--spacing) * 4);\n }\n .pl-2 {\n padding-left: calc(var(--spacing) * 2);\n }\n .pl-3 {\n padding-left: calc(var(--spacing) * 3);\n }\n .pl-4 {\n padding-left: calc(var(--spacing) * 4);\n }\n .pl-6 {\n padding-left: calc(var(--spacing) * 6);\n }\n .pl-8 {\n padding-left: calc(var(--spacing) * 8);\n }\n .text-center {\n text-align: center;\n }\n .text-left {\n text-align: left;\n }\n .text-right {\n text-align: right;\n }\n .text-base {\n font-size: var(--text-base);\n line-height: var(--tw-leading, var(--text-base--line-height));\n }\n .text-lg {\n font-size: var(--text-lg);\n line-height: var(--tw-leading, var(--text-lg--line-height));\n }\n .text-sm {\n font-size: var(--text-sm);\n line-height: var(--tw-leading, var(--text-sm--line-height));\n }\n .text-xl {\n font-size: var(--text-xl);\n line-height: var(--tw-leading, var(--text-xl--line-height));\n }\n .text-xs {\n font-size: var(--text-xs);\n line-height: var(--tw-leading, var(--text-xs--line-height));\n }\n .text-\\[13px\\] {\n font-size: 13px;\n }\n .leading-none {\n --tw-leading: 1;\n line-height: 1;\n }\n .leading-relaxed {\n --tw-leading: var(--leading-relaxed);\n line-height: var(--leading-relaxed);\n }\n .font-bold {\n --tw-font-weight: var(--font-weight-bold);\n font-weight: var(--font-weight-bold);\n }\n .font-medium {\n --tw-font-weight: var(--font-weight-medium);\n font-weight: var(--font-weight-medium);\n }\n .font-semibold {\n --tw-font-weight: var(--font-weight-semibold);\n font-weight: var(--font-weight-semibold);\n }\n .whitespace-nowrap {\n white-space: nowrap;\n }\n .text-accent {\n color: var(--color-accent);\n }\n .text-accent-fg {\n color: var(--color-accent-fg);\n }\n .text-fg-disabled {\n color: var(--color-fg-disabled);\n }\n .text-fg-muted {\n color: var(--color-fg-muted);\n }\n .text-fg-on-accent {\n color: var(--color-fg-on-accent);\n }\n .text-fg-primary {\n color: var(--color-fg-primary);\n }\n .text-fg-secondary {\n color: var(--color-fg-secondary);\n }\n .text-state-error {\n color: var(--color-state-error);\n }\n .text-state-success {\n color: var(--color-state-success);\n }\n .text-state-warning {\n color: var(--color-state-warning);\n }\n .text-tooltip-fg {\n color: var(--color-tooltip-fg);\n }\n .text-white {\n color: var(--color-white);\n }\n .uppercase {\n text-transform: uppercase;\n }\n .italic {\n font-style: italic;\n }\n .underline {\n text-decoration-line: underline;\n }\n .placeholder-fg-muted {\n &::-moz-placeholder {\n color: var(--color-fg-muted);\n }\n &::placeholder {\n color: var(--color-fg-muted);\n }\n }\n .accent-accent {\n accent-color: var(--color-accent);\n }\n .opacity-0 {\n opacity: 0%;\n }\n .opacity-50 {\n opacity: 50%;\n }\n .opacity-100 {\n opacity: 100%;\n }\n .shadow {\n --tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n .shadow-2xl {\n --tw-shadow: 0 25px 50px -12px var(--tw-shadow-color, rgb(0 0 0 / 0.25));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n .shadow-lg {\n --tw-shadow: 0 10px 15px -3px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 4px 6px -4px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n .shadow-md {\n --tw-shadow: 0 4px 6px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 2px 4px -2px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n .shadow-sm {\n --tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n .ring {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n .ring-1 {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n .ring-2 {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n .ring-accent {\n --tw-ring-color: var(--color-accent);\n }\n .ring-border-default {\n --tw-ring-color: var(--color-border-default);\n }\n .ring-interactive-focus-ring {\n --tw-ring-color: var(--color-interactive-focus-ring);\n }\n .outline {\n outline-style: var(--tw-outline-style);\n outline-width: 1px;\n }\n .outline-1 {\n outline-style: var(--tw-outline-style);\n outline-width: 1px;\n }\n .outline-2 {\n outline-style: var(--tw-outline-style);\n outline-width: 2px;\n }\n .-outline-offset-1 {\n outline-offset: calc(1px * -1);\n }\n .outline-offset-2 {\n outline-offset: 2px;\n }\n .outline-accent {\n outline-color: var(--color-accent);\n }\n .outline-border-default {\n outline-color: var(--color-border-default);\n }\n .backdrop-blur {\n --tw-backdrop-blur: blur(8px);\n backdrop-filter: var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);\n }\n .transition {\n transition-property: color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, --tw-gradient-from, --tw-gradient-via, --tw-gradient-to, opacity, box-shadow, transform, translate, scale, rotate, filter, backdrop-filter, display, content-visibility, overlay, pointer-events;\n transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));\n transition-duration: var(--tw-duration, var(--default-transition-duration));\n }\n .transition-\\[height\\] {\n transition-property: height;\n transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));\n transition-duration: var(--tw-duration, var(--default-transition-duration));\n }\n .transition-all {\n transition-property: all;\n transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));\n transition-duration: var(--tw-duration, var(--default-transition-duration));\n }\n .transition-colors {\n transition-property: color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, --tw-gradient-from, --tw-gradient-via, --tw-gradient-to;\n transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));\n transition-duration: var(--tw-duration, var(--default-transition-duration));\n }\n .transition-opacity {\n transition-property: opacity;\n transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));\n transition-duration: var(--tw-duration, var(--default-transition-duration));\n }\n .transition-transform {\n transition-property: transform, translate, scale, rotate;\n transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));\n transition-duration: var(--tw-duration, var(--default-transition-duration));\n }\n .duration-150 {\n --tw-duration: 150ms;\n transition-duration: 150ms;\n }\n .duration-200 {\n --tw-duration: 200ms;\n transition-duration: 200ms;\n }\n .duration-300 {\n --tw-duration: 300ms;\n transition-duration: 300ms;\n }\n .ease-in-out {\n --tw-ease: var(--ease-in-out);\n transition-timing-function: var(--ease-in-out);\n }\n .ease-out {\n --tw-ease: var(--ease-out);\n transition-timing-function: var(--ease-out);\n }\n .outline-none {\n --tw-outline-style: none;\n outline-style: none;\n }\n .select-none {\n -webkit-user-select: none;\n -moz-user-select: none;\n user-select: none;\n }\n .group-hover\\:opacity-100 {\n &:is(:where(.group):hover *) {\n @media (hover: hover) {\n opacity: 100%;\n }\n }\n }\n .peer-checked\\:opacity-100 {\n &:is(:where(.peer):checked ~ *) {\n opacity: 100%;\n }\n }\n .placeholder\\:text-fg-muted {\n &::-moz-placeholder {\n color: var(--color-fg-muted);\n }\n &::placeholder {\n color: var(--color-fg-muted);\n }\n }\n .first\\:mt-0 {\n &:first-child {\n margin-top: calc(var(--spacing) * 0);\n }\n }\n .checked\\:border-accent {\n &:checked {\n border-color: var(--color-accent);\n }\n }\n .checked\\:bg-accent {\n &:checked {\n background-color: var(--color-accent);\n }\n }\n .hover\\:border-accent {\n &:hover {\n @media (hover: hover) {\n border-color: var(--color-accent);\n }\n }\n }\n .hover\\:border-state-error {\n &:hover {\n @media (hover: hover) {\n border-color: var(--color-state-error);\n }\n }\n }\n .hover\\:border-b-accent {\n &:hover {\n @media (hover: hover) {\n border-bottom-color: var(--color-accent);\n }\n }\n }\n .hover\\:border-b-fg-muted {\n &:hover {\n @media (hover: hover) {\n border-bottom-color: var(--color-fg-muted);\n }\n }\n }\n .hover\\:\\!bg-accent-hover {\n &:hover {\n @media (hover: hover) {\n background-color: var(--color-accent-hover) !important;\n }\n }\n }\n .hover\\:bg-accent {\n &:hover {\n @media (hover: hover) {\n background-color: var(--color-accent);\n }\n }\n }\n .hover\\:bg-accent-hover {\n &:hover {\n @media (hover: hover) {\n background-color: var(--color-accent-hover);\n }\n }\n }\n .hover\\:bg-bg-surface {\n &:hover {\n @media (hover: hover) {\n background-color: var(--color-bg-surface);\n }\n }\n }\n .hover\\:bg-border-default {\n &:hover {\n @media (hover: hover) {\n background-color: var(--color-border-default);\n }\n }\n }\n .hover\\:bg-interactive-hover {\n &:hover {\n @media (hover: hover) {\n background-color: var(--color-interactive-hover);\n }\n }\n }\n .hover\\:bg-state-error-light {\n &:hover {\n @media (hover: hover) {\n background-color: var(--color-state-error-light);\n }\n }\n }\n .hover\\:bg-state-error\\/90 {\n &:hover {\n @media (hover: hover) {\n background-color: var(--color-state-error);\n @supports (color: color-mix(in lab, red, red)) {\n background-color: color-mix(in oklab, var(--color-state-error) 90%, transparent);\n }\n }\n }\n }\n .hover\\:bg-transparent {\n &:hover {\n @media (hover: hover) {\n background-color: transparent;\n }\n }\n }\n .hover\\:text-accent-hover {\n &:hover {\n @media (hover: hover) {\n color: var(--color-accent-hover);\n }\n }\n }\n .hover\\:text-fg-on-accent {\n &:hover {\n @media (hover: hover) {\n color: var(--color-fg-on-accent);\n }\n }\n }\n .hover\\:text-fg-primary {\n &:hover {\n @media (hover: hover) {\n color: var(--color-fg-primary);\n }\n }\n }\n .hover\\:text-fg-secondary {\n &:hover {\n @media (hover: hover) {\n color: var(--color-fg-secondary);\n }\n }\n }\n .hover\\:shadow-md {\n &:hover {\n @media (hover: hover) {\n --tw-shadow: 0 4px 6px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 2px 4px -2px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n }\n }\n .hover\\:ring {\n &:hover {\n @media (hover: hover) {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n }\n }\n .hover\\:ring-0 {\n &:hover {\n @media (hover: hover) {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n }\n }\n .hover\\:ring-accent {\n &:hover {\n @media (hover: hover) {\n --tw-ring-color: var(--color-accent);\n }\n }\n }\n .hover\\:ring-transparent {\n &:hover {\n @media (hover: hover) {\n --tw-ring-color: transparent;\n }\n }\n }\n .focus\\:border-accent {\n &:focus {\n border-color: var(--color-accent);\n }\n }\n .focus\\:border-blue-500 {\n &:focus {\n border-color: var(--color-blue-500);\n }\n }\n .focus\\:border-state-error {\n &:focus {\n border-color: var(--color-state-error);\n }\n }\n .focus\\:border-transparent {\n &:focus {\n border-color: transparent;\n }\n }\n .focus\\:ring-1 {\n &:focus {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n }\n .focus\\:ring-2 {\n &:focus {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n }\n .focus\\:ring-accent {\n &:focus {\n --tw-ring-color: var(--color-accent);\n }\n }\n .focus\\:ring-blue-500 {\n &:focus {\n --tw-ring-color: var(--color-blue-500);\n }\n }\n .focus\\:outline-none {\n &:focus {\n --tw-outline-style: none;\n outline-style: none;\n }\n }\n .active\\:cursor-grabbing {\n &:active {\n cursor: grabbing;\n }\n }\n .active\\:bg-interactive-active {\n &:active {\n background-color: var(--color-interactive-active);\n }\n }\n .disabled\\:cursor-not-allowed {\n &:disabled {\n cursor: not-allowed;\n }\n }\n .disabled\\:opacity-40 {\n &:disabled {\n opacity: 40%;\n }\n }\n .disabled\\:opacity-50 {\n &:disabled {\n opacity: 50%;\n }\n }\n .disabled\\:hover\\:bg-transparent {\n &:disabled {\n &:hover {\n @media (hover: hover) {\n background-color: transparent;\n }\n }\n }\n }\n .disabled\\:hover\\:ring-0 {\n &:disabled {\n &:hover {\n @media (hover: hover) {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n }\n }\n }\n .sm\\:grid-cols-2 {\n @media (width >= 40rem) {\n grid-template-columns: repeat(2, minmax(0, 1fr));\n }\n }\n .md\\:flex {\n @media (width >= 48rem) {\n display: flex;\n }\n }\n .md\\:h-auto {\n @media (width >= 48rem) {\n height: auto;\n }\n }\n .md\\:max-h-\\[80vh\\] {\n @media (width >= 48rem) {\n max-height: 80vh;\n }\n }\n .md\\:w-\\[28rem\\] {\n @media (width >= 48rem) {\n width: 28rem;\n }\n }\n .md\\:w-\\[32rem\\] {\n @media (width >= 48rem) {\n width: 32rem;\n }\n }\n .md\\:w-\\[36rem\\] {\n @media (width >= 48rem) {\n width: 36rem;\n }\n }\n .md\\:w-\\[48rem\\] {\n @media (width >= 48rem) {\n width: 48rem;\n }\n }\n .md\\:max-w-\\[90vw\\] {\n @media (width >= 48rem) {\n max-width: 90vw;\n }\n }\n .md\\:flex-none {\n @media (width >= 48rem) {\n flex: none;\n }\n }\n .md\\:items-center {\n @media (width >= 48rem) {\n align-items: center;\n }\n }\n .md\\:justify-center {\n @media (width >= 48rem) {\n justify-content: center;\n }\n }\n .md\\:rounded-lg {\n @media (width >= 48rem) {\n border-radius: var(--radius-lg);\n }\n }\n .md\\:border {\n @media (width >= 48rem) {\n border-style: var(--tw-border-style);\n border-width: 1px;\n }\n }\n .md\\:border-border-subtle {\n @media (width >= 48rem) {\n border-color: var(--color-border-subtle);\n }\n }\n .md\\:shadow-lg {\n @media (width >= 48rem) {\n --tw-shadow: 0 10px 15px -3px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 4px 6px -4px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n }\n}\n@import url(\'https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600&display=swap\');\n:host {\n --tw-translate-x: 0;\n --tw-translate-y: 0;\n --tw-translate-z: 0;\n --tw-rotate-x: rotateX(0);\n --tw-rotate-y: rotateY(0);\n --tw-rotate-z: rotateZ(0);\n --tw-skew-x: skewX(0);\n --tw-skew-y: skewY(0);\n --tw-border-style: solid;\n --tw-gradient-from: #0000;\n --tw-gradient-via: #0000;\n --tw-gradient-to: #0000;\n --tw-gradient-from-position: 0%;\n --tw-gradient-via-position: 50%;\n --tw-gradient-to-position: 100%;\n --tw-shadow: 0 0 #0000;\n --tw-inset-shadow: 0 0 #0000;\n --tw-ring-shadow: 0 0 #0000;\n --tw-inset-ring-shadow: 0 0 #0000;\n --tw-ring-offset-width: 0px;\n --tw-ring-offset-color: #fff;\n --tw-ring-offset-shadow: 0 0 #0000;\n --tw-outline-style: solid;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n width: 100%;\n height: 100%;\n font-family: \'Open Sans\', system-ui, sans-serif;\n color: var(--ep-foreground-primary);\n background-color: var(--ep-background-surface);\n}\n:host *::-webkit-scrollbar {\n width: 8px;\n height: 8px;\n}\n:host *::-webkit-scrollbar-track {\n background: var(--ep-scrollbar-track);\n}\n:host *::-webkit-scrollbar-thumb {\n background: var(--ep-scrollbar-thumb);\n border-radius: 4px;\n}\n:host *::-webkit-scrollbar-thumb:hover {\n background: var(--ep-scrollbar-thumb-hover);\n}\n@property --tw-translate-x {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-translate-y {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-translate-z {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-scale-x {\n syntax: "*";\n inherits: false;\n initial-value: 1;\n}\n@property --tw-scale-y {\n syntax: "*";\n inherits: false;\n initial-value: 1;\n}\n@property --tw-scale-z {\n syntax: "*";\n inherits: false;\n initial-value: 1;\n}\n@property --tw-rotate-x {\n syntax: "*";\n inherits: false;\n}\n@property --tw-rotate-y {\n syntax: "*";\n inherits: false;\n}\n@property --tw-rotate-z {\n syntax: "*";\n inherits: false;\n}\n@property --tw-skew-x {\n syntax: "*";\n inherits: false;\n}\n@property --tw-skew-y {\n syntax: "*";\n inherits: false;\n}\n@property --tw-space-y-reverse {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-space-x-reverse {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-divide-y-reverse {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-border-style {\n syntax: "*";\n inherits: false;\n initial-value: solid;\n}\n@property --tw-leading {\n syntax: "*";\n inherits: false;\n}\n@property --tw-font-weight {\n syntax: "*";\n inherits: false;\n}\n@property --tw-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-shadow-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-shadow-alpha {\n syntax: "";\n inherits: false;\n initial-value: 100%;\n}\n@property --tw-inset-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-inset-shadow-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-inset-shadow-alpha {\n syntax: "";\n inherits: false;\n initial-value: 100%;\n}\n@property --tw-ring-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-ring-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-inset-ring-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-inset-ring-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-ring-inset {\n syntax: "*";\n inherits: false;\n}\n@property --tw-ring-offset-width {\n syntax: "";\n inherits: false;\n initial-value: 0px;\n}\n@property --tw-ring-offset-color {\n syntax: "*";\n inherits: false;\n initial-value: #fff;\n}\n@property --tw-ring-offset-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-outline-style {\n syntax: "*";\n inherits: false;\n initial-value: solid;\n}\n@property --tw-backdrop-blur {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-brightness {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-contrast {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-grayscale {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-hue-rotate {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-invert {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-opacity {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-saturate {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-sepia {\n syntax: "*";\n inherits: false;\n}\n@property --tw-duration {\n syntax: "*";\n inherits: false;\n}\n@property --tw-ease {\n syntax: "*";\n inherits: false;\n}\n@keyframes spin {\n to {\n transform: rotate(360deg);\n }\n}\n@keyframes pulse {\n 50% {\n opacity: 0.5;\n }\n}\n@layer properties {\n @supports ((-webkit-hyphens: none) and (not (margin-trim: inline))) or ((-moz-orient: inline) and (not (color:rgb(from red r g b)))) {\n *, ::before, ::after, ::backdrop {\n --tw-translate-x: 0;\n --tw-translate-y: 0;\n --tw-translate-z: 0;\n --tw-scale-x: 1;\n --tw-scale-y: 1;\n --tw-scale-z: 1;\n --tw-rotate-x: initial;\n --tw-rotate-y: initial;\n --tw-rotate-z: initial;\n --tw-skew-x: initial;\n --tw-skew-y: initial;\n --tw-space-y-reverse: 0;\n --tw-space-x-reverse: 0;\n --tw-divide-y-reverse: 0;\n --tw-border-style: solid;\n --tw-leading: initial;\n --tw-font-weight: initial;\n --tw-shadow: 0 0 #0000;\n --tw-shadow-color: initial;\n --tw-shadow-alpha: 100%;\n --tw-inset-shadow: 0 0 #0000;\n --tw-inset-shadow-color: initial;\n --tw-inset-shadow-alpha: 100%;\n --tw-ring-color: initial;\n --tw-ring-shadow: 0 0 #0000;\n --tw-inset-ring-color: initial;\n --tw-inset-ring-shadow: 0 0 #0000;\n --tw-ring-inset: initial;\n --tw-ring-offset-width: 0px;\n --tw-ring-offset-color: #fff;\n --tw-ring-offset-shadow: 0 0 #0000;\n --tw-outline-style: solid;\n --tw-backdrop-blur: initial;\n --tw-backdrop-brightness: initial;\n --tw-backdrop-contrast: initial;\n --tw-backdrop-grayscale: initial;\n --tw-backdrop-hue-rotate: initial;\n --tw-backdrop-invert: initial;\n --tw-backdrop-opacity: initial;\n --tw-backdrop-saturate: initial;\n --tw-backdrop-sepia: initial;\n --tw-duration: initial;\n --tw-ease: initial;\n }\n }\n}\n',Ue=0;function He(e,t,n,o,i,r){t||(t={});var a,s,l=t;if("ref"in l)for(s in l={},t)"ref"==s?a=t[s]:l[s]=t[s];var c={type:e,props:l,key:n,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Ue,__i:-1,__u:0,__source:i,__self:r};if("function"==typeof e&&(a=e.defaultProps))for(s in a)void 0===l[s]&&(l[s]=a[s]);return k.vnode&&k.vnode(c),c}var We=(e=>(e[e.Degree0=0]="Degree0",e[e.Degree90=1]="Degree90",e[e.Degree180=2]="Degree180",e[e.Degree270=3]="Degree270",e))(We||{});function Be(e){return{x:Math.floor(e.x),y:Math.floor(e.y)}}function qe(e){return{width:Math.ceil(e.width),height:Math.ceil(e.height)}}function Ge(e){return{origin:Be(e.origin),size:qe(e.size)}}function Ve(e){const{width:t,height:n}=e;return{width:n,height:t}}function Ke(e,t,n){return{width:(e=t%2==0?e:Ve(e)).width*n,height:e.height*n}}function Ze(e){const t=[e.p1.x,e.p2.x,e.p3.x,e.p4.x],n=[e.p1.y,e.p2.y,e.p3.y,e.p4.y];return{origin:{x:Math.min(...t),y:Math.min(...n)},size:{width:Math.max(...t)-Math.min(...t),height:Math.max(...n)-Math.min(...n)}}}function Ye(e){return{p1:{x:e.origin.x,y:e.origin.y},p2:{x:e.origin.x+e.size.width,y:e.origin.y},p3:{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height},p4:{x:e.origin.x,y:e.origin.y+e.size.height}}}function Xe(e,t,n){let o=t.x,i=t.y;switch(n){case 0:o=t.x,i=t.y;break;case 1:o=e.height-t.y,i=t.x;break;case 2:o=e.width-t.x,i=e.height-t.y;break;case 3:o=t.y,i=e.width-t.x}return{x:o,y:i}}function Qe(e,t){return{x:e.x*t,y:e.y*t}}function Je(e){if(0===e.length)return{origin:{x:0,y:0},size:{width:0,height:0}};const t=e.map(e=>e.x),n=e.map(e=>e.y),o=Math.min(...t),i=Math.min(...n);return{origin:{x:o,y:i},size:{width:Math.max(...t)-o,height:Math.max(...n)-i}}}function et(e,t){return{origin:{x:e.origin.x-t,y:e.origin.y-t},size:{width:e.size.width+2*t,height:e.size.height+2*t}}}function tt(e,t,n){let o=t.origin.x,i=t.origin.y,r=t.size;switch(n){case 0:break;case 1:o=e.height-t.origin.y-t.size.height,i=t.origin.x,r=Ve(t.size);break;case 2:o=e.width-t.origin.x-t.size.width,i=e.height-t.origin.y-t.size.height;break;case 3:o=t.origin.y,i=e.width-t.origin.x-t.size.width,r=Ve(t.size)}return{origin:{x:o,y:i},size:{width:r.width,height:r.height}}}function nt(e,t){return{origin:{x:e.origin.x*t,y:e.origin.y*t},size:{width:e.size.width*t,height:e.size.height*t}}}function ot(e,t,n,o){return nt(tt(e,t,n),o)}const it={origin:{x:0,y:0},size:{width:0,height:0}};function rt(e){if(0===e.length)return null;let t=e[0].origin.x,n=e[0].origin.y,o=e[0].origin.x+e[0].size.width,i=e[0].origin.y+e[0].size.height;for(const r of e)t=Math.min(t,r.origin.x),n=Math.min(n,r.origin.y),o=Math.max(o,r.origin.x+r.size.width),i=Math.max(i,r.origin.y+r.size.height);return{origin:{x:t,y:n},size:{width:o-t,height:i-n}}}function at(e){const t=e%360;return t<0?t+360:t}function st(e){return{x:e.origin.x+e.size.width/2,y:e.origin.y+e.size.height/2}}function lt(e,t,n){const o=n*Math.PI/180,i=Math.cos(o),r=Math.sin(o),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}}function ct(e,t,n){return e.map(e=>lt(e,t,n))}function dt(e,t,n){return Je(ct([{x:e.origin.x,y:e.origin.y},{x:e.origin.x+e.size.width,y:e.origin.y},{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height},{x:e.origin.x,y:e.origin.y+e.size.height}],n,t))}function ut(e,t){return dt(e,t,st(e))}function ht(e,t,n){const o=n*Math.PI/180,i=Math.cos(o),r=Math.sin(o),a=1-i,s=r,l=-r,c=1-i,d=a*c-s*l,u=st(e);if(Math.abs(d)<1e-10)return u;const h=st(t),m=h.x-(i*u.x-r*u.y),g=h.y-(r*u.x+i*u.y);return{x:(c*m-s*g)/d,y:(-l*m+a*g)/d}}function mt(e,t,n,o){const i=e.origin.x,r=e.origin.y,a=e.size.width,s=e.size.height,l=n/a,c=o/s,d=n/s,u=o/a;switch(t){case 0:return{a:l,b:0,c:0,d:c,e:-l*i,f:-c*r};case 3:return{a:0,b:-u,c:d,d:0,e:-d*r,f:u*(i+a)};case 2:return{a:-l,b:0,c:0,d:-c,e:l*(i+a),f:c*(r+s)};case 1:return{a:0,b:u,c:-d,d:0,e:d*(r+s),f:-u*i}}}class gt{isEnabled(){return!1}debug(){}info(){}warn(){}error(){}perf(){}}class pt{isEnabled(){return!0}debug(e,t,...n){console.debug(`${e}.${t}`,...n)}info(e,t,...n){console.info(`${e}.${t}`,...n)}warn(e,t,...n){console.warn(`${e}.${t}`,...n)}error(e,t,...n){console.error(`${e}.${t}`,...n)}perf(e,t,n,o,...i){console.info(`${e}.${t}.${n}.${o}`,...i)}}class ft{constructor(e,t){this.logger=e,this.level=t}isEnabled(e){return this.level<={debug:0,info:1,warn:2,error:3}[e]}debug(e,t,...n){this.level<=0&&this.logger.debug(e,t,...n)}info(e,t,...n){this.level<=1&&this.logger.info(e,t,...n)}warn(e,t,...n){this.level<=2&&this.logger.warn(e,t,...n)}error(e,t,...n){this.level<=3&&this.logger.error(e,t,...n)}perf(e,t,n,o,...i){this.logger.perf(e,t,n,o,...i)}}class vt{constructor(){this.marks=new Map}isEnabled(){return!1}debug(e,t,...n){}info(e,t,...n){}warn(e,t,...n){}error(e,t,...n){}perf(e,t,n,o,i,...r){const a=`${e}.${t}.${n}.${o}.${i}`;switch(o){case"Begin":globalThis.performance.mark(a,{detail:r}),this.marks.set(`${e}.${t}.${n}.${i}`,Date.now());break;case"End":globalThis.performance.mark(a,{detail:r});const o=`${e}.${t}.${n}.Measure.${i}`,s=`${e}.${t}.${n}.Begin.${i}`;globalThis.performance.measure(o,s,a);const l=this.marks.get(`${e}.${t}.${n}.${i}`);if(l){const o=Date.now()-l;console.info(`⏱️ ${e}.${t}.${n}.${i}: ${o}ms`),this.marks.delete(`${e}.${t}.${n}.${i}`)}}}}class yt{constructor(e){this.loggers=e}isEnabled(e){return this.loggers.some(t=>t.isEnabled(e))}debug(e,t,...n){for(const o of this.loggers)o.debug(e,t,...n)}info(e,t,...n){for(const o of this.loggers)o.info(e,t,...n)}warn(e,t,...n){for(const o of this.loggers)o.warn(e,t,...n)}error(e,t,...n){for(const o of this.loggers)o.error(e,t,...n)}perf(e,t,n,o,...i){for(const r of this.loggers)r.perf(e,t,n,o,...i)}}var bt=(e=>(e[e.Pending=0]="Pending",e[e.Resolved=1]="Resolved",e[e.Rejected=2]="Rejected",e[e.Aborted=3]="Aborted",e))(bt||{});class wt extends Error{constructor(e){super(`Task aborted: ${JSON.stringify(e)}`),this.name="TaskAbortedError",this.reason=e}}class xt extends Error{constructor(e){super(`Task rejected: ${JSON.stringify(e)}`),this.name="TaskRejectedError",this.reason=e}}class Ct{constructor(){this.state={stage:0},this.resolvedCallbacks=[],this.rejectedCallbacks=[],this._promise=null,this.progressCbs=[]}toPromise(){return this._promise||(this._promise=new Promise((e,t)=>{this.wait(t=>e(t),e=>{"abort"===e.type?t(new wt(e.reason)):t(new xt(e.reason))})})),this._promise}wait(e,t){switch(this.state.stage){case 0:this.resolvedCallbacks.push(e),this.rejectedCallbacks.push(t);break;case 1:e(this.state.result);break;case 2:t({type:"reject",reason:this.state.reason});break;case 3:t({type:"abort",reason:this.state.reason})}}resolve(e){if(0===this.state.stage){this.state={stage:1,result:e};for(const t of this.resolvedCallbacks)try{t(e)}catch(e){}this.resolvedCallbacks=[],this.rejectedCallbacks=[]}}reject(e){if(0===this.state.stage){this.state={stage:2,reason:e};for(const t of this.rejectedCallbacks)try{t({type:"reject",reason:e})}catch(e){}this.resolvedCallbacks=[],this.rejectedCallbacks=[]}}abort(e){if(0===this.state.stage){this.state={stage:3,reason:e};for(const t of this.rejectedCallbacks)try{t({type:"abort",reason:e})}catch(e){}this.resolvedCallbacks=[],this.rejectedCallbacks=[]}}fail(e){"abort"===e.type?this.abort(e.reason):this.reject(e.reason)}onProgress(e){this.progressCbs.push(e)}progress(e){for(const t of this.progressCbs)t(e)}static all(e){const t=new Ct;if(0===e.length)return t.resolve([]),t;const n=new Array(e.length);let o=0,i=!1;return e.forEach((r,a)=>{r.wait(r=>{i||(n[a]=r,o++,o===e.length&&(i=!0,t.resolve(n)))},e=>{i||(i=!0,"abort"===e.type?t.abort(e.reason):t.reject(e.reason))})}),t}static allSettled(e){const t=new Ct;if(0===e.length)return t.resolve([]),t;const n=new Array(e.length);let o=0;return e.forEach((i,r)=>{i.wait(i=>{n[r]={status:"resolved",value:i},o++,o===e.length&&t.resolve(n)},i=>{n[r]={status:"abort"===i.type?"aborted":"rejected",reason:i.reason},o++,o===e.length&&t.resolve(n)})}),t}static race(e){const t=new Ct;if(0===e.length)return t.reject("No tasks provided"),t;let n=!1;return e.forEach(e=>{e.wait(e=>{n||(n=!0,t.resolve(e))},e=>{n||(n=!0,"abort"===e.type?t.abort(e.reason):t.reject(e.reason))})}),t}static withProgress(e,t){const n=Ct.all(e);if(t){let n=0;e.forEach(o=>{o.wait(()=>{n++,t(n,e.length)},()=>{n++,t(n,e.length)})})}return n}}const kt=Object.freeze(["­","​","⁠","\ufeff","￾","￿"]),It=new RegExp(`[${kt.join("")}]`,"g");function St(e){return e.replace(It,"")}var At=(e=>(e[e.Unknown=0]="Unknown",e[e.XYZ=1]="XYZ",e[e.FitPage=2]="FitPage",e[e.FitHorizontal=3]="FitHorizontal",e[e.FitVertical=4]="FitVertical",e[e.FitRectangle=5]="FitRectangle",e[e.FitBoundingBox=6]="FitBoundingBox",e[e.FitBoundingBoxHorizontal=7]="FitBoundingBoxHorizontal",e[e.FitBoundingBoxVertical=8]="FitBoundingBoxVertical",e))(At||{}),Mt=(e=>(e[e.NotSet=0]="NotSet",e[e.True=1]="True",e[e.False=2]="False",e[e.Unknown=3]="Unknown",e))(Mt||{}),Pt=(e=>(e[e.Unknown=-1]="Unknown",e[e.Courier=0]="Courier",e[e.Courier_Bold=1]="Courier_Bold",e[e.Courier_BoldOblique=2]="Courier_BoldOblique",e[e.Courier_Oblique=3]="Courier_Oblique",e[e.Helvetica=4]="Helvetica",e[e.Helvetica_Bold=5]="Helvetica_Bold",e[e.Helvetica_BoldOblique=6]="Helvetica_BoldOblique",e[e.Helvetica_Oblique=7]="Helvetica_Oblique",e[e.Times_Roman=8]="Times_Roman",e[e.Times_Bold=9]="Times_Bold",e[e.Times_BoldItalic=10]="Times_BoldItalic",e[e.Times_Italic=11]="Times_Italic",e[e.Symbol=12]="Symbol",e[e.ZapfDingbats=13]="ZapfDingbats",e))(Pt||{}),Dt=(e=>(e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right",e))(Dt||{}),Rt=(e=>(e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom",e))(Rt||{}),zt=(e=>(e[e.Normal=0]="Normal",e[e.Multiply=1]="Multiply",e[e.Screen=2]="Screen",e[e.Overlay=3]="Overlay",e[e.Darken=4]="Darken",e[e.Lighten=5]="Lighten",e[e.ColorDodge=6]="ColorDodge",e[e.ColorBurn=7]="ColorBurn",e[e.HardLight=8]="HardLight",e[e.SoftLight=9]="SoftLight",e[e.Difference=10]="Difference",e[e.Exclusion=11]="Exclusion",e[e.Hue=12]="Hue",e[e.Saturation=13]="Saturation",e[e.Color=14]="Color",e[e.Luminosity=15]="Luminosity",e))(zt||{}),Tt=(e=>(e[e.Contain=0]="Contain",e[e.Cover=1]="Cover",e[e.Stretch=2]="Stretch",e))(Tt||{}),Et=(e=>(e[e.Unsupported=0]="Unsupported",e[e.Goto=1]="Goto",e[e.RemoteGoto=2]="RemoteGoto",e[e.URI=3]="URI",e[e.LaunchAppOrOpenFile=4]="LaunchAppOrOpenFile",e))(Et||{});const _t=1,Nt=2,Lt=4;var Ot=(e=>(e[e.UNKNOWN=0]="UNKNOWN",e[e.TEXT=1]="TEXT",e[e.LINK=2]="LINK",e[e.FREETEXT=3]="FREETEXT",e[e.LINE=4]="LINE",e[e.SQUARE=5]="SQUARE",e[e.CIRCLE=6]="CIRCLE",e[e.POLYGON=7]="POLYGON",e[e.POLYLINE=8]="POLYLINE",e[e.HIGHLIGHT=9]="HIGHLIGHT",e[e.UNDERLINE=10]="UNDERLINE",e[e.SQUIGGLY=11]="SQUIGGLY",e[e.STRIKEOUT=12]="STRIKEOUT",e[e.STAMP=13]="STAMP",e[e.CARET=14]="CARET",e[e.INK=15]="INK",e[e.POPUP=16]="POPUP",e[e.FILEATTACHMENT=17]="FILEATTACHMENT",e[e.SOUND=18]="SOUND",e[e.MOVIE=19]="MOVIE",e[e.WIDGET=20]="WIDGET",e[e.SCREEN=21]="SCREEN",e[e.PRINTERMARK=22]="PRINTERMARK",e[e.TRAPNET=23]="TRAPNET",e[e.WATERMARK=24]="WATERMARK",e[e.THREED=25]="THREED",e[e.RICHMEDIA=26]="RICHMEDIA",e[e.XFAWIDGET=27]="XFAWIDGET",e[e.REDACT=28]="REDACT",e))(Ot||{}),$t=(e=>(e[e.Normal=0]="Normal",e[e.Rollover=1]="Rollover",e[e.Down=2]="Down",e))($t||{}),jt=(e=>(e[e.Unknown=-1]="Unknown",e[e.Comment=0]="Comment",e[e.Key=1]="Key",e[e.Note=2]="Note",e[e.Help=3]="Help",e[e.NewParagraph=4]="NewParagraph",e[e.Paragraph=5]="Paragraph",e[e.Insert=6]="Insert",e[e.Graph=7]="Graph",e[e.PushPin=8]="PushPin",e[e.Paperclip=9]="Paperclip",e[e.Tag=10]="Tag",e[e.Speaker=11]="Speaker",e[e.Mic=12]="Mic",e[e.Approved=13]="Approved",e[e.Experimental=14]="Experimental",e[e.NotApproved=15]="NotApproved",e[e.AsIs=16]="AsIs",e[e.Expired=17]="Expired",e[e.NotForPublicRelease=18]="NotForPublicRelease",e[e.Confidential=19]="Confidential",e[e.Final=20]="Final",e[e.Sold=21]="Sold",e[e.Departmental=22]="Departmental",e[e.ForComment=23]="ForComment",e[e.TopSecret=24]="TopSecret",e[e.Draft=25]="Draft",e[e.ForPublicRelease=26]="ForPublicRelease",e))(jt||{}),Ft=(e=>(e[e.None=0]="None",e[e.Square=1]="Square",e[e.Circle=2]="Circle",e[e.Diamond=3]="Diamond",e[e.OpenArrow=4]="OpenArrow",e[e.ClosedArrow=5]="ClosedArrow",e[e.Butt=6]="Butt",e[e.ROpenArrow=7]="ROpenArrow",e[e.RClosedArrow=8]="RClosedArrow",e[e.Slash=9]="Slash",e[e.Unknown=10]="Unknown",e))(Ft||{}),Ut=(e=>(e[e.Unknown=0]="Unknown",e[e.Reply=1]="Reply",e[e.Group=2]="Group",e))(Ut||{}),Ht=(e=>(e[e.UNKNOWN=0]="UNKNOWN",e[e.PUSHBUTTON=1]="PUSHBUTTON",e[e.CHECKBOX=2]="CHECKBOX",e[e.RADIOBUTTON=3]="RADIOBUTTON",e[e.COMBOBOX=4]="COMBOBOX",e[e.LISTBOX=5]="LISTBOX",e[e.TEXTFIELD=6]="TEXTFIELD",e[e.SIGNATURE=7]="SIGNATURE",e[e.XFA=8]="XFA",e[e.XFA_CHECKBOX=9]="XFA_CHECKBOX",e[e.XFA_COMBOBOX=10]="XFA_COMBOBOX",e[e.XFA_IMAGEFIELD=11]="XFA_IMAGEFIELD",e[e.XFA_LISTBOX=12]="XFA_LISTBOX",e[e.XFA_PUSHBUTTON=13]="XFA_PUSHBUTTON",e[e.XFA_SIGNATURE=14]="XFA_SIGNATURE",e[e.XFA_TEXTFIELD=15]="XFA_TEXTFIELD",e))(Ht||{}),Wt=(e=>(e[e.Color=0]="Color",e[e.InteriorColor=1]="InteriorColor",e[e.OverlayColor=2]="OverlayColor",e))(Wt||{}),Bt=(e=>(e[e.UNKNOWN=0]="UNKNOWN",e[e.SOLID=1]="SOLID",e[e.DASHED=2]="DASHED",e[e.BEVELED=3]="BEVELED",e[e.INSET=4]="INSET",e[e.UNDERLINE=5]="UNDERLINE",e[e.CLOUDY=6]="CLOUDY",e))(Bt||{}),qt=(e=>(e[e.UNKNOWN=0]="UNKNOWN",e[e.TEXT=1]="TEXT",e[e.PATH=2]="PATH",e[e.IMAGE=3]="IMAGE",e[e.SHADING=4]="SHADING",e[e.FORM=5]="FORM",e))(qt||{});const Gt=Object.freeze({1:"invisible",2:"hidden",4:"print",8:"noZoom",16:"noRotate",32:"noView",64:"readOnly",128:"locked",256:"toggleNoView"}),Vt=Object.entries(Gt).reduce((e,[t,n])=>(e[n]=Number(t),e),{});function Kt(e){return Object.keys(Gt).filter(t=>0!==(e&t)).map(e=>Gt[e])}function Zt(e){return e.reduce((e,t)=>e|Vt[t],0)}var Yt=(e=>(e[e.Create=0]="Create",e[e.Read=1]="Read",e[e.Update=2]="Update",e[e.Delete=3]="Delete",e))(Yt||{}),Xt=(e=>(e[e.None=0]="None",e[e.MatchCase=1]="MatchCase",e[e.MatchWholeWord=2]="MatchWholeWord",e[e.MatchConsecutive=4]="MatchConsecutive",e))(Xt||{}),Qt=(e=>(e[e.Print=4]="Print",e[e.ModifyContents=8]="ModifyContents",e[e.CopyContents=16]="CopyContents",e[e.ModifyAnnotations=32]="ModifyAnnotations",e[e.FillForms=256]="FillForms",e[e.ExtractForAccessibility=512]="ExtractForAccessibility",e[e.AssembleDocument=1024]="AssembleDocument",e[e.PrintHighQuality=2048]="PrintHighQuality",e[e.AllowAll=3900]="AllowAll",e))(Qt||{});class Jt extends Error{constructor(e,t){const n=e.map(e=>Qt[e]).join(", ");super(`Permission denied. Required: ${n}`),this.requiredFlags=e,this.currentPermissions=t,this.name="PermissionDeniedError"}}var en=(e=>(e[e.Display=0]="Display",e[e.Print=1]="Print",e))(en||{}),tn=(e=>(e[e.Ok=0]="Ok",e[e.Unknown=1]="Unknown",e[e.NotFound=2]="NotFound",e[e.WrongFormat=3]="WrongFormat",e[e.Password=4]="Password",e[e.Security=5]="Security",e[e.PageError=6]="PageError",e[e.XFALoad=7]="XFALoad",e[e.XFALayout=8]="XFALayout",e[e.Cancelled=9]="Cancelled",e[e.Initialization=10]="Initialization",e[e.NotReady=11]="NotReady",e[e.NotSupport=12]="NotSupport",e[e.LoadDoc=13]="LoadDoc",e[e.DocNotOpen=14]="DocNotOpen",e[e.CantCloseDoc=15]="CantCloseDoc",e[e.CantCreateNewDoc=16]="CantCreateNewDoc",e[e.CantImportPages=17]="CantImportPages",e[e.CantCreateAnnot=18]="CantCreateAnnot",e[e.CantSetAnnotRect=19]="CantSetAnnotRect",e[e.CantSetAnnotContent=20]="CantSetAnnotContent",e[e.CantRemoveInkList=21]="CantRemoveInkList",e[e.CantAddInkStoke=22]="CantAddInkStoke",e[e.CantReadAttachmentSize=23]="CantReadAttachmentSize",e[e.CantReadAttachmentContent=24]="CantReadAttachmentContent",e[e.CantFocusAnnot=25]="CantFocusAnnot",e[e.CantSelectText=26]="CantSelectText",e[e.CantSelectOption=27]="CantSelectOption",e[e.CantCheckField=28]="CantCheckField",e[e.CantSetAnnotString=29]="CantSetAnnotString",e))(tn||{});class nn{static create(){return new Ct}static resolve(e){const t=new Ct;return t.resolve(e),t}static reject(e){const t=new Ct;return t.reject(e),t}static abort(e){const t=new Ct;return t.reject(e),t}}function on(e){const t=e=>(e=>Math.max(0,Math.min(255,e)))(e).toString(16).padStart(2,"0");return`#${t(e.red)}${t(e.green)}${t(e.blue)}`}function rn(e){/^#?[0-9a-f]{3}$/i.test(e)&&(e=e.replace(/^#?([0-9a-f])([0-9a-f])([0-9a-f])$/i,"#$1$1$2$2$3$3").toLowerCase());const[,t,n,o]=/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(e)??(()=>{throw new Error(`Invalid hex colour: "${e}"`)})();return{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(o,16)}}function an(e){return(e=>Math.max(0,Math.min(255,e)))(e)/255}function sn(e){return((e,t=255)=>Math.max(0,Math.min(t,e)))(Math.round(255*e))}function ln(e){if(!(null==e?void 0:e.startsWith("D:"))||e.length<16)return;const t=+e.slice(2,6),n=+e.slice(6,8)-1,o=+e.slice(8,10),i=+e.slice(10,12),r=+e.slice(12,14),a=+e.slice(14,16);return new Date(Date.UTC(t,n,o,i,r,a))}function cn(e=new Date){const t=(e,t=2)=>e.toString().padStart(t,"0");return`D:${e.getUTCFullYear()}${t(e.getUTCMonth()+1)}${t(e.getUTCDate())}${t(e.getUTCHours())}${t(e.getUTCMinutes())}${t(e.getUTCSeconds())}`}const dn=Object.freeze([{id:Dt.Left,label:"Left",css:"left"},{id:Dt.Center,label:"Center",css:"center"},{id:Dt.Right,label:"Right",css:"right"}]),un=dn.reduce((e,t)=>(e[t.id]=t,e),{});function hn(e){return function(e){return un[e]??un[Dt.Left]}(e).css}dn.reduce((e,t)=>(e[t.css]=t.id,e),{}),dn.map(e=>({value:e.id,label:e.label}));var mn=(e=>(e.Courier="Courier",e.Helvetica="Helvetica",e.Times="Times",e.Symbol="Symbol",e.ZapfDingbats="ZapfDingbats",e.Unknown="Unknown",e))(mn||{});const gn=Pt.Helvetica,pn={id:Pt.Helvetica,family:"Helvetica",bold:!1,italic:!1,label:"Helvetica",css:"Helvetica, Arial, sans-serif"},fn=Object.freeze([{id:Pt.Courier,family:"Courier",bold:!1,italic:!1,label:"Courier",css:"Courier, monospace"},{id:Pt.Courier_Bold,family:"Courier",bold:!0,italic:!1,label:"Courier Bold",css:"Courier, monospace"},{id:Pt.Courier_BoldOblique,family:"Courier",bold:!0,italic:!0,label:"Courier Bold Oblique",css:"Courier, monospace"},{id:Pt.Courier_Oblique,family:"Courier",bold:!1,italic:!0,label:"Courier Oblique",css:"Courier, monospace"},pn,{id:Pt.Helvetica_Bold,family:"Helvetica",bold:!0,italic:!1,label:"Helvetica Bold",css:"Helvetica, Arial, sans-serif"},{id:Pt.Helvetica_BoldOblique,family:"Helvetica",bold:!0,italic:!0,label:"Helvetica Bold Oblique",css:"Helvetica, Arial, sans-serif"},{id:Pt.Helvetica_Oblique,family:"Helvetica",bold:!1,italic:!0,label:"Helvetica Oblique",css:"Helvetica, Arial, sans-serif"},{id:Pt.Times_Roman,family:"Times",bold:!1,italic:!1,label:"Times Roman",css:'"Times New Roman", Times, serif'},{id:Pt.Times_Bold,family:"Times",bold:!0,italic:!1,label:"Times Bold",css:'"Times New Roman", Times, serif'},{id:Pt.Times_BoldItalic,family:"Times",bold:!0,italic:!0,label:"Times Bold Italic",css:'"Times New Roman", Times, serif'},{id:Pt.Times_Italic,family:"Times",bold:!1,italic:!0,label:"Times Italic",css:'"Times New Roman", Times, serif'},{id:Pt.Symbol,family:"Symbol",bold:!1,italic:!1,label:"Symbol",css:"Symbol, serif"},{id:Pt.ZapfDingbats,family:"ZapfDingbats",bold:!1,italic:!1,label:"Zapf Dingbats",css:"ZapfDingbats, serif"}]),vn=fn.reduce((e,t)=>(e[t.id]=t,e),{}),yn=new Map;for(const e of fn)yn.set(`${e.family}_${e.bold}_${e.italic}`,e.id);function bn(e){return vn[e]??pn}function wn(e){return bn(e).family}function xn(e){return bn(e).bold}function Cn(e){return bn(e).italic}function kn(e,{bold:t,italic:n}){return yn.get(`${e}_${t}_${n}`)??gn}function In(e){const t=bn(e);return{fontFamily:t.css,fontWeight:t.bold?"bold":"normal",fontStyle:t.italic?"italic":"normal"}}Object.values(mn).filter(e=>"Unknown"!==e).map(e=>({value:e,label:e}));const Sn=[...new Set(fn.map(e=>e.family))];function An(e){switch(e){case"Courier":return"Courier";case"Helvetica":default:return"Helvetica";case"Times":return"Times";case"Symbol":return"Symbol";case"ZapfDingbats":return"ZapfDingbats"}}const Mn=Object.freeze([{id:zt.Normal,label:"Normal",css:"normal"},{id:zt.Multiply,label:"Multiply",css:"multiply"},{id:zt.Screen,label:"Screen",css:"screen"},{id:zt.Overlay,label:"Overlay",css:"overlay"},{id:zt.Darken,label:"Darken",css:"darken"},{id:zt.Lighten,label:"Lighten",css:"lighten"},{id:zt.ColorDodge,label:"Color Dodge",css:"color-dodge"},{id:zt.ColorBurn,label:"Color Burn",css:"color-burn"},{id:zt.HardLight,label:"Hard Light",css:"hard-light"},{id:zt.SoftLight,label:"Soft Light",css:"soft-light"},{id:zt.Difference,label:"Difference",css:"difference"},{id:zt.Exclusion,label:"Exclusion",css:"exclusion"},{id:zt.Hue,label:"Hue",css:"hue"},{id:zt.Saturation,label:"Saturation",css:"saturation"},{id:zt.Color,label:"Color",css:"color"},{id:zt.Luminosity,label:"Luminosity",css:"luminosity"}]),Pn=Mn.reduce((e,t)=>(e[t.id]=t,e),{});function Dn(e){return function(e){return Pn[e]??Pn[zt.Normal]}(e).css}Mn.reduce((e,t)=>(e[t.css]=t.id,e),{}),Mn.map(e=>({value:e.id,label:e.label}));const Rn=Mn.map(e=>e.id);function zn(e){if(e instanceof gt)return{type:"noop"};if(e instanceof pt)return{type:"console"};if(e instanceof vt)return{type:"perf"};if(e instanceof ft){const t=e;return{type:"level",config:{level:t.level,logger:zn(t.logger)}}}if(e instanceof yt){return{type:"all",config:{loggers:e.loggers.map(zn)}}}return{type:"noop"}}const Tn=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function En(e){return Tn.test(e)}function _n(){var e;if("function"==typeof(null==(e=globalThis.crypto)?void 0:e.randomUUID))return globalThis.crypto.randomUUID();const t=function(e){var t;if("function"==typeof(null==(t=globalThis.crypto)?void 0:t.getRandomValues))return globalThis.crypto.getRandomValues(new Uint8Array(e));if("function"==typeof require)try{const{randomBytes:t}=require("crypto");return t(e)}catch{}const n=new Uint8Array(e);for(let t=0;te.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}class Nn extends Ct{constructor(e={}){super(),this.children=new Map,this.childResults=[],this.completedCount=0,this.expectedCount=0,this.isFinalized=!1,this.config={aggregate:e.aggregate??(e=>e),onChildComplete:e.onChildComplete??(()=>{}),failFast:e.failFast??!0}}addChild(e,t){if(this.state.stage!==bt.Pending)return this.state.stage===bt.Aborted&&e.abort(this.state.reason),this;const n=t??this.expectedCount;return this.expectedCount=Math.max(this.expectedCount,n+1),this.children.set(e,n),e.wait(t=>this.handleChildSuccess(e,t,n),t=>this.handleChildError(e,t,n)),this}finalize(){return this.isFinalized||(this.isFinalized=!0,0===this.expectedCount&&this.resolve(this.config.aggregate([]))),this}handleChildSuccess(e,t,n){if(this.state.stage!==bt.Pending)return;this.childResults[n]=t,this.completedCount++,this.children.delete(e);const o=this.config.onChildComplete(this.completedCount,this.expectedCount,t,n);if(void 0!==o&&this.progress(o),this.completedCount===this.expectedCount){const e=this.config.aggregate(this.childResults);this.resolve(e)}}handleChildError(e,t,n){if(this.state.stage===bt.Pending)if(this.children.delete(e),this.config.failFast){for(const[e]of this.children)e.abort("Sibling task failed");this.children.clear(),this.fail(t)}else if(this.childResults[n]=void 0,this.completedCount++,this.completedCount===this.expectedCount){const e=this.config.aggregate(this.childResults);this.resolve(e)}}abort(e){for(const[t]of this.children)t.abort(e);this.children.clear(),super.abort(e)}reject(e){for(const[t]of this.children)t.abort(e);this.children.clear(),super.reject(e)}getPendingCount(){return this.children.size}getCompletedCount(){return this.completedCount}static gather(e){const t=new Nn({aggregate:e=>e,onChildComplete:(e,t)=>({completed:e,total:t})});return e.forEach((e,n)=>t.addChild(e,n)),t.finalize(),t}static gatherIndexed(e){const t=new Nn({aggregate:e=>{const t={};return e.forEach((e,n)=>{t[n]=e}),t},onChildComplete:(e,t,n,o)=>({page:o,result:n})});return e.forEach((e,n)=>t.addChild(e,n)),t.finalize(),t}static gatherFrom(e,t){const n=new Nn(t);return e.forEach((e,t)=>n.addChild(e,t)),n.finalize(),n}static first(e){let t=!1;const n=new Nn({aggregate:e=>e[0],failFast:!1});return n.handleChildSuccess=(e,o)=>{if(!t){t=!0;for(const[t]of n.children)t!==e&&t.abort("Race won by sibling");n.resolve(o)}},e.forEach((e,t)=>n.addChild(e,t)),n.finalize(),n}}function Ln(){}class On{constructor(){this.dependencyGraph=new Map}addNode(e,t=[]){this.dependencyGraph.set(e,new Set(t))}hasCircularDependencies(){const e=new Set,t=new Set,n=o=>{e.add(o),t.add(o);const i=this.dependencyGraph.get(o)||new Set;for(const o of i)if(e.has(o)){if(t.has(o))return!0}else if(n(o))return!0;return t.delete(o),!1};for(const t of this.dependencyGraph.keys())if(!e.has(t)&&n(t))return!0;return!1}resolveLoadOrder(){if(this.hasCircularDependencies())throw new Error("Circular dependencies detected");const e=[],t=new Set,n=new Set,o=i=>{if(n.has(i))throw new Error("Circular dependency");if(t.has(i))return;n.add(i);const r=this.dependencyGraph.get(i)||new Set;for(const e of r)o(e);n.delete(i),t.add(i),e.push(i)};for(const e of this.dependencyGraph.keys())t.has(e)||o(e);return e}}class $n extends Error{constructor(e){super(e),this.name="PluginRegistrationError"}}class jn extends Error{constructor(e){super(e),this.name="PluginNotFoundError"}}class Fn extends Error{constructor(e){super(e),this.name="CircularDependencyError"}}class Un extends Error{constructor(e){super(e),this.name="PluginConfigurationError"}}class Hn{constructor(e,t){this.store=e,this.pluginId=t}getState(){return this.store.getState().plugins[this.pluginId]}dispatch(e){return this.store.dispatchToPlugin(this.pluginId,e)}subscribeToState(e){return this.store.subscribeToPlugin(this.pluginId,(t,n,o)=>{e(t,n,o)})}onAction(e,t){return this.store.onAction(e,(e,n,o)=>{t(e,n.plugins[this.pluginId],o.plugins[this.pluginId])})}}const Wn="START_LOADING_DOCUMENT",Bn="UPDATE_DOCUMENT_LOADING_PROGRESS",qn="SET_DOCUMENT_LOADED",Gn="SET_DOCUMENT_ERROR",Vn="RETRY_LOADING_DOCUMENT",Kn="CLOSE_DOCUMENT",Zn="SET_ACTIVE_DOCUMENT",Yn="REORDER_DOCUMENTS",Xn="MOVE_DOCUMENT",Qn="UPDATE_DOCUMENT_SECURITY",Jn="REFRESH_PAGES",eo="SET_SCALE",to="SET_ROTATION",no=[Wn,Bn,qn,Kn,Zn,Gn,Vn,"REFRESH_DOCUMENT",Jn,"SET_PAGES",eo,to,"SET_DEFAULT_SCALE","SET_DEFAULT_ROTATION",Yn,Xn,Qn],oo=(e,t,n,o,i,r,a)=>({type:Wn,payload:{documentId:e,name:t,scale:n,rotation:o,passwordProvided:i,autoActivate:r,permissions:a}}),io=(e,t)=>({type:Kn,payload:{documentId:e,nextActiveDocumentId:t}}),ro=(e,t)=>({type:Jn,payload:{documentId:e,pageIndexes:t}}),ao=(e,t)=>({type:to,payload:{rotation:e,documentId:t}});class so{constructor(e,t){this.initialCoreState=t,this.pluginReducers={},this.listeners=[],this.pluginListeners={},this.isDispatching=!1,this.state={core:t,plugins:{}},this.coreReducer=e}addPluginReducer(e,t,n){this.state.plugins[e]=n,this.pluginReducers[e]=t}dispatchToCore(e){if(!this.coreReducer)return this.getState();if(this.isDispatching)throw new Error("Reducers may not dispatch actions. To trigger cascading actions, dispatch from a listener callback instead.");const t=this.getState();try{this.isDispatching=!0,this.state.core=this.coreReducer(this.state.core,e)}finally{this.isDispatching=!1}return this.listeners.forEach(n=>{const o=this.getState();n(e,o,t)}),this.getState()}dispatchToPlugin(e,t,n=!0){if(this.isDispatching)throw new Error("Reducers may not dispatch actions. To trigger cascading actions, dispatch from a listener callback instead.");const o=this.getState(),i=this.pluginReducers[e];if(!i)return o.plugins[e];const r=o.plugins[e];try{this.isDispatching=!0;const n=i(r,t);this.state.plugins[e]=n}finally{this.isDispatching=!1}return n&&this.listeners.forEach(e=>{const n=this.getState();e(t,n,o)}),this.pluginListeners[e]&&this.pluginListeners[e].forEach(n=>{const o=this.getState().plugins[e];n(t,o,r)}),this.getState().plugins[e]}dispatch(e){if(this.isDispatching)throw new Error("Reducers may not dispatch actions. To trigger cascading actions, dispatch from a listener callback instead.");const t=this.getState();try{this.isDispatching=!0,this.isCoreAction(e)&&(this.state.core=this.coreReducer(this.state.core,e));for(const n in this.pluginReducers){const o=this.pluginReducers[n],i=t.plugins[n];o&&(this.state.plugins[n]=o(i,e))}}finally{this.isDispatching=!1}return this.listeners.forEach(n=>{const o=this.getState();n(e,o,t)}),this.getState()}getState(){if(this.isDispatching)throw new Error("You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.");return{core:{...this.state.core},plugins:{...this.state.plugins}}}subscribe(e){if(this.isDispatching)throw new Error("You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state.");return this.listeners.push(e),()=>{if(this.isDispatching)throw new Error("You may not unsubscribe from a store listener while the reducer is executing.");this.listeners=this.listeners.filter(t=>t!==e)}}subscribeToPlugin(e,t){if(!(e in this.state.plugins))throw new Error(`Plugin state not found for plugin "${e}". Did you forget to call addPluginReducer?`);if(this.isDispatching)throw new Error("You may not call store.subscribeToPlugin() while the reducer is executing.");return this.pluginListeners[e]||(this.pluginListeners[e]=[]),this.pluginListeners[e].push(t),()=>{if(this.isDispatching)throw new Error("You may not unsubscribe from a store listener while the reducer is executing.");this.pluginListeners[e]=this.pluginListeners[e].filter(e=>e!==t),0===this.pluginListeners[e].length&&delete this.pluginListeners[e]}}onAction(e,t){return this.subscribe((n,o,i)=>{n.type===e&&t(n,o,i)})}getPluginStore(e){if(!(e in this.state.plugins))throw new Error(`Plugin state not found for plugin "${e}". Did you forget to call addPluginReducer?`);return new Hn(this,e)}isCoreAction(e){return no.includes(e.type)}destroy(){var e,t;this.listeners.length=0;for(const n in this.pluginListeners)null==(t=null==(e=this.pluginListeners[n])?void 0:e.splice)||t.call(e,0);this.pluginListeners={},this.pluginReducers={},this.state.plugins={},this.state.core={...this.initialCoreState}}}Qt.Print,Qt.ModifyContents,Qt.CopyContents,Qt.ModifyAnnotations,Qt.FillForms,Qt.ExtractForAccessibility,Qt.AssembleDocument,Qt.PrintHighQuality;const lo=[Qt.Print,Qt.ModifyContents,Qt.CopyContents,Qt.ModifyAnnotations,Qt.FillForms,Qt.ExtractForAccessibility,Qt.AssembleDocument,Qt.PrintHighQuality],co={[Qt.Print]:"print",[Qt.ModifyContents]:"modifyContents",[Qt.CopyContents]:"copyContents",[Qt.ModifyAnnotations]:"modifyAnnotations",[Qt.FillForms]:"fillForms",[Qt.ExtractForAccessibility]:"extractForAccessibility",[Qt.AssembleDocument]:"assembleDocument",[Qt.PrintHighQuality]:"printHighQuality"};function uo(e,t){if(!e)return;if(t in e)return e[t];const n=co[t];return n&&n in e?e[n]:void 0}function ho(e,t,n){var o;const i=e.documents[t],r=null==i?void 0:i.permissions,a=e.globalPermissions,s=(null==(o=null==i?void 0:i.document)?void 0:o.permissions)??Qt.AllowAll,l=uo(null==r?void 0:r.overrides,n);if(void 0!==l)return l;const c=uo(null==a?void 0:a.overrides,n);if(void 0!==c)return c;return!((null==r?void 0:r.enforceDocumentPermissions)??(null==a?void 0:a.enforceDocumentPermissions)??!0)||0!==(s&n)}function mo(e,t){return lo.reduce((n,o)=>ho(e,t,o)?n|o:n,0)}function go(e,t,n){const o=e.activeDocumentId;if(o!==t)return o;if(void 0!==n)return n&&e.documents[n]?n:null;const i=e.documentOrder.indexOf(t);return-1===i?null:i>0?e.documentOrder[i-1]:i{switch(t.type){case Wn:{const{documentId:n,name:o,scale:i,rotation:r,passwordProvided:a,autoActivate:s=!0,permissions:l}=t.payload,c={id:n,name:o,status:"loading",loadingProgress:0,error:null,document:null,scale:i??e.defaultScale,rotation:r??e.defaultRotation,passwordProvided:a??!1,pageRefreshVersions:{},permissions:l,loadStartedAt:Date.now()};return{...e,documents:{...e.documents,[n]:c},documentOrder:[...e.documentOrder,n],activeDocumentId:s||!e.activeDocumentId?n:e.activeDocumentId}}case Bn:{const{documentId:n,progress:o}=t.payload,i=e.documents[n];return i&&"loading"===i.status?{...e,documents:{...e.documents,[n]:{...i,loadingProgress:o}}}:e}case qn:{const{documentId:n,document:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,status:"loaded",document:o,error:null,errorCode:void 0,errorDetails:void 0,passwordProvided:void 0,loadedAt:Date.now()}}}:e}case Gn:{const{documentId:n,error:o,errorCode:i,errorDetails:r}=t.payload,a=e.documents[n];return a?{...e,documents:{...e.documents,[n]:{...a,status:"error",error:o,errorCode:i,errorDetails:r}}}:e}case Vn:{const{documentId:n,passwordProvided:o}=t.payload,i=e.documents[n];return i&&"error"===i.status?{...e,documents:{...e.documents,[n]:{...i,status:"loading",loadingProgress:0,error:null,errorCode:void 0,errorDetails:void 0,passwordProvided:o??!1,loadStartedAt:Date.now()}}}:e}case Kn:{const{documentId:n,nextActiveDocumentId:o}=t.payload,{[n]:i,...r}=e.documents;return{...e,documents:r,documentOrder:e.documentOrder.filter(e=>e!==n),activeDocumentId:go(e,n,o)}}case Xn:{const{documentId:n,toIndex:o}=t.payload,i=function(e,t,n){const o=e.indexOf(t);if(-1===o)return null;if(n<0||n>=e.length)return null;if(o===n)return null;const i=[...e];return i.splice(o,1),i.splice(n,0,t),i}(e.documentOrder,n,o);return i?{...e,documentOrder:i}:e}case Yn:return{...e,documentOrder:t.payload};case Zn:return{...e,activeDocumentId:t.payload};case eo:{const{scale:n,documentId:o}=t.payload,i=o??e.activeDocumentId;if(!i)return e;const r=e.documents[i];return r?{...e,documents:{...e.documents,[i]:{...r,scale:n}}}:e}case to:{const{rotation:n,documentId:o}=t.payload,i=o??e.activeDocumentId;if(!i)return e;const r=e.documents[i];return r?{...e,documents:{...e.documents,[i]:{...r,rotation:n}}}:e}case Jn:{const{documentId:n,pageIndexes:o}=t.payload,i=e.documents[n];if(!i)return e;const r={...i.pageRefreshVersions};for(const e of o)r[e]=(r[e]||0)+1;return{...e,documents:{...e.documents,[n]:{...i,pageRefreshVersions:r}}}}case Qn:{const{documentId:n,permissions:o,isOwnerUnlocked:i}=t.payload,r=e.documents[n];return(null==r?void 0:r.document)?{...e,documents:{...e.documents,[n]:{...r,document:{...r.document,permissions:o,isOwnerUnlocked:i}}}}:e}default:return e}};class fo{constructor(e,t){this.plugins=new Map,this.manifests=new Map,this.capabilities=new Map,this.status=new Map,this.configurations=new Map,this.initPromise=null,this.pendingRegistrations=[],this.processingRegistrations=[],this.initialized=!1,this.isInitializing=!1,this.pluginsReadyPromise=null,this.destroyed=!1,this.resolver=new On,this.engine=e,this.initialCoreState=(e=>({documents:{},documentOrder:[],activeDocumentId:null,defaultScale:(null==e?void 0:e.defaultScale)??1,defaultRotation:(null==e?void 0:e.defaultRotation)??We.Degree0,globalPermissions:null==e?void 0:e.permissions}))(t),this.store=new so(po,this.initialCoreState),this.logger=(null==t?void 0:t.logger)??new gt}getLogger(){return this.logger}registerPlugin(e,t){if(this.initialized&&!this.isInitializing)throw new $n("Cannot register plugins after initialization");this.validateManifest(e.manifest),this.store.addPluginReducer(e.manifest.id,e.reducer,"function"==typeof e.initialState?e.initialState(this.initialCoreState,{...e.manifest.defaultConfig,...t}):e.initialState),this.pendingRegistrations.push({package:e,config:t})}getStore(){return this.store}getEngine(){return this.engine}pluginsReady(){return this.pluginsReadyPromise||(this.pluginsReadyPromise=(async()=>{this.initialized||await this.initialize();const e=Array.from(this.plugins.values()).map(e=>"function"==typeof e.ready?e.ready():Promise.resolve());await Promise.all(e)})()),this.pluginsReadyPromise}async initialize(){if(this.destroyed)throw new $n("Registry has been destroyed");return this.initPromise||(this.initPromise=(async()=>{if(this.initialized)throw new $n("Registry is already initialized");this.isInitializing=!0;try{if(this.destroyed)return;for(;this.pendingRegistrations.length>0;){if(this.destroyed)return;this.processingRegistrations=[...this.pendingRegistrations],this.pendingRegistrations=[];for(const e of this.processingRegistrations){const t=new Set,n=[...e.package.manifest.requires,...e.package.manifest.optional];for(const e of n){const n=this.processingRegistrations.find(t=>t.package.manifest.provides.includes(e));n&&t.add(n.package.manifest.id)}this.resolver.addNode(e.package.manifest.id,[...t])}const e=this.resolver.resolveLoadOrder();for(const t of e){const e=this.processingRegistrations.find(e=>e.package.manifest.id===t);this.instantiatePlugin(e.package.manifest,e.package.create,e.config)}for(const t of e)await this.runPluginInitialization(t);this.processingRegistrations=[],this.resolver=new On}this.initialized=!0}catch(e){if(e instanceof Error)throw new Fn(`Failed to resolve plugin dependencies: ${e.message}`);throw e}finally{this.isInitializing=!1}})()),this.initPromise}instantiatePlugin(e,t,n){const o={...e.defaultConfig,...n};this.validateConfig(e.id,o,e.defaultConfig);const i=t(this,o);this.validatePlugin(i);for(const t of e.provides){if(this.capabilities.has(t))throw new $n(`Capability ${t} is already provided by plugin ${this.capabilities.get(t)}`);this.capabilities.set(t,e.id)}this.plugins.set(e.id,i),this.manifests.set(e.id,e),this.status.set(e.id,"registered"),this.configurations.set(e.id,o)}async runPluginInitialization(e){const t=this.plugins.get(e);if(!t)return;const n=this.manifests.get(e),o=this.configurations.get(e);for(const t of n.requires)if(!this.capabilities.has(t))throw new $n(`Missing required capability: ${t} for plugin ${e}`);this.logger.debug("PluginRegistry","InitializePlugin",`Initializing plugin ${e}`);try{t.initialize&&await t.initialize(o),this.status.set(e,"active"),this.logger.info("PluginRegistry","PluginInitialized",`Plugin ${e} initialized successfully`)}catch(t){throw this.status.set(e,"error"),this.logger.error("PluginRegistry","InitializationFailed",`Plugin ${e} initialization failed`,{error:t}),t}}getPluginConfig(e){const t=this.configurations.get(e);if(!t)throw new jn(`Configuration for plugin ${e} not found`);return t}validateConfig(e,t,n){const o=Object.keys(n).filter(e=>!t.hasOwnProperty(e));if(o.length>0)throw new Un(`Missing required configuration keys for plugin ${e}: ${o.join(", ")}`)}async updatePluginConfig(e,t){const n=this.getPlugin(e);if(!n)throw new jn(`Plugin ${e} not found`);const o=this.manifests.get(e),i=this.configurations.get(e);if(!o||!i)throw new jn(`Plugin ${e} not found`);const r={...i,...t};this.validateConfig(e,r,o.defaultConfig),this.configurations.set(e,r),n.initialize&&await n.initialize(r)}registerPluginBatch(e){for(const t of e)this.registerPlugin(t.package,t.config)}async unregisterPlugin(e){const t=this.plugins.get(e);if(!t)throw new jn(`Plugin ${e} is not registered`);const n=this.manifests.get(e);if(!n)throw new jn(`Manifest for plugin ${e} not found`);for(const[t,o]of this.manifests.entries()){if(t===e)continue;if([...o.requires,...o.optional].some(e=>n.provides.includes(e)))throw new $n(`Cannot unregister plugin ${e}: plugin ${t} depends on it`)}try{t.destroy&&await t.destroy();for(const e of n.provides)this.capabilities.delete(e);this.plugins.delete(e),this.manifests.delete(e),this.status.delete(e)}catch(t){if(t instanceof Error)throw new Error(`Failed to unregister plugin ${e}: ${t.message}`);throw t}}getPlugin(e){const t=this.plugins.get(e);return t||null}getCapabilityProvider(e){const t=this.capabilities.get(e);return t?this.getPlugin(t):null}hasCapability(e){return this.capabilities.has(e)}getAllPlugins(){return Array.from(this.plugins.values())}getPluginStatus(e){const t=this.status.get(e);if(!t)throw new jn(`Plugin ${e} not found`);return t}validatePlugin(e){if(!e.id)throw new $n("Plugin must have an id")}validateManifest(e){if(!e.id)throw new $n("Manifest must have an id");if(!e.name)throw new $n("Manifest must have a name");if(!e.version)throw new $n("Manifest must have a version");if(!Array.isArray(e.provides))throw new $n("Manifest must have a provides array");if(!Array.isArray(e.requires))throw new $n("Manifest must have a requires array");if(!Array.isArray(e.optional))throw new $n("Manifest must have an optional array")}isDestroyed(){return this.destroyed}async destroy(){var e;if(this.destroyed)throw new $n("Registry has already been destroyed");this.destroyed=!0;try{await this.initPromise}catch{}for(const t of Array.from(this.plugins.values()).reverse())await(null==(e=t.destroy)?void 0:e.call(t));this.store.destroy(),this.plugins.clear(),this.manifests.clear(),this.capabilities.clear(),this.status.clear(),this.pendingRegistrations.length=0,this.processingRegistrations.length=0}}function vo(e,t){return{package:e,config:t}}function yo(e){return"autoMountElements"in e&&"function"==typeof e.autoMountElements}class bo{constructor(e,t){if(this.id=e,this.registry=t,this.cooldownActions={},this.debouncedTimeouts={},this.unsubscribeFromState=null,this.unsubscribeFromCoreStore=null,this.unsubscribeFromStartLoadingDocument=null,this.unsubscribeFromSetDocumentLoaded=null,this.unsubscribeFromCloseDocument=null,this.unsubscribeFromSetScale=null,this.unsubscribeFromSetRotation=null,e!==this.constructor.id)throw new Error(`Plugin ID mismatch: ${e} !== ${this.constructor.id}`);this.engine=this.registry.getEngine(),this.logger=this.registry.getLogger(),this.coreStore=this.registry.getStore(),this.pluginStore=this.coreStore.getPluginStore(this.id),this.unsubscribeFromState=this.pluginStore.subscribeToState((e,t,n)=>{this.onStoreUpdated(n,t)}),this.unsubscribeFromCoreStore=this.coreStore.subscribe((e,t,n)=>{this.onCoreStoreUpdated(n,t),t.core.activeDocumentId!==n.core.activeDocumentId&&this.onActiveDocumentChanged(n.core.activeDocumentId,t.core.activeDocumentId)}),this.unsubscribeFromStartLoadingDocument=this.coreStore.onAction(Wn,e=>{this.onDocumentLoadingStarted(e.payload.documentId)}),this.unsubscribeFromSetDocumentLoaded=this.coreStore.onAction(qn,e=>{this.onDocumentLoaded(e.payload.documentId)}),this.unsubscribeFromCloseDocument=this.coreStore.onAction(Kn,e=>{this.onDocumentClosed(e.payload.documentId)}),this.unsubscribeFromSetScale=this.coreStore.onAction(eo,(e,t)=>{const n=e.payload.documentId??t.core.activeDocumentId;n&&this.onScaleChanged(n,e.payload.scale)}),this.unsubscribeFromSetRotation=this.coreStore.onAction(to,(e,t)=>{const n=e.payload.documentId??t.core.activeDocumentId;n&&this.onRotationChanged(n,e.payload.rotation)}),this.readyPromise=new Promise(e=>{this.readyResolve=e}),this.readyResolve()}provides(){if(!this._capability){const e=this.buildCapability();this._capability=Object.freeze(e)}return this._capability}get state(){return this.pluginStore.getState()}get coreState(){return this.coreStore.getState()}getState(){return this.pluginStore.getState()}getCoreState(){return this.coreStore.getState()}dispatchCoreAction(e){return this.coreStore.dispatchToCore(e)}dispatchToAllPlugins(e){return this.coreStore.dispatch(e)}dispatch(e){return this.pluginStore.dispatch(e)}cooldownDispatch(e,t=100){const n=Date.now();return n-(this.cooldownActions[e.type]||0)>=t&&(this.cooldownActions[e.type]=n,this.dispatch(e),!0)}debouncedDispatch(e,t=100){const n=e.type;this.debouncedTimeouts[n]&&clearTimeout(this.debouncedTimeouts[n]),this.debouncedTimeouts[n]=setTimeout(()=>{this.dispatch(e),delete this.debouncedTimeouts[n]},t)}cancelDebouncedDispatch(e){this.debouncedTimeouts[e]&&(clearTimeout(this.debouncedTimeouts[e]),delete this.debouncedTimeouts[e])}subscribe(e){return this.pluginStore.subscribeToState(e)}subscribeToCoreStore(e){return this.coreStore.subscribe(e)}onStoreUpdated(e,t){}onCoreStoreUpdated(e,t){}onDocumentLoadingStarted(e){}onDocumentLoaded(e){}onDocumentClosed(e){}onActiveDocumentChanged(e,t){}onScaleChanged(e,t){}onRotationChanged(e,t){}destroy(){Object.values(this.debouncedTimeouts).forEach(e=>{clearTimeout(e)}),this.debouncedTimeouts={},this.unsubscribeFromState&&(this.unsubscribeFromState(),this.unsubscribeFromState=null),this.unsubscribeFromCoreStore&&(this.unsubscribeFromCoreStore(),this.unsubscribeFromCoreStore=null),this.unsubscribeFromStartLoadingDocument&&(this.unsubscribeFromStartLoadingDocument(),this.unsubscribeFromStartLoadingDocument=null),this.unsubscribeFromSetDocumentLoaded&&(this.unsubscribeFromSetDocumentLoaded(),this.unsubscribeFromSetDocumentLoaded=null),this.unsubscribeFromCloseDocument&&(this.unsubscribeFromCloseDocument(),this.unsubscribeFromCloseDocument=null),this.unsubscribeFromSetScale&&(this.unsubscribeFromSetScale(),this.unsubscribeFromSetScale=null),this.unsubscribeFromSetRotation&&(this.unsubscribeFromSetRotation(),this.unsubscribeFromSetRotation=null)}ready(){return this.readyPromise}markReady(){this.readyResolve()}resetReady(){this.readyPromise=new Promise(e=>{this.readyResolve=e})}getActiveDocumentId(){const e=this.coreState.core.activeDocumentId;if(!e)throw new Error("No active document");return e}getActiveDocumentIdOrNull(){return this.coreState.core.activeDocumentId}getCoreDocument(e){const t=e??this.getActiveDocumentIdOrNull();return t?this.coreState.core.documents[t]??null:null}getCoreDocumentOrThrow(e){const t=this.getCoreDocument(e);if(!t)throw new Error(`Document not found: ${e??"active"}`);return t}getDocumentPermissions(e){const t=e??this.coreState.core.activeDocumentId;return t?mo(this.coreState.core,t):Qt.AllowAll}checkPermission(e,...t){const n=e??this.coreState.core.activeDocumentId;return!n||t.every(e=>ho(this.coreState.core,n,e))}requirePermission(e,...t){const n=e??this.coreState.core.activeDocumentId;if(!n)return;const o=[];for(const e of t)ho(this.coreState.core,n,e)||o.push(e);if(o.length>0){const e=mo(this.coreState.core,n);throw new Jt(o,e)}}}class wo{constructor(e,t){this.handler=e,this.options=t,this.lastRun=0,this.handle=e=>{"debounce"===this.options.mode?this.debounce(e):this.throttle(e)}}debounce(e){this.timeoutId&&window.clearTimeout(this.timeoutId),this.timeoutId=window.setTimeout(()=>{this.handler(e),this.timeoutId=void 0},this.options.wait)}throttle(e){if("debounce"===this.options.mode)return;const t=Date.now(),n=this.options.throttleMode||"leading-trailing";t-this.lastRun>=this.options.wait&&("leading-trailing"===n&&this.handler(e),this.lastRun=t),this.timeoutId&&window.clearTimeout(this.timeoutId),this.timeoutId=window.setTimeout(()=>{this.handler(e),this.lastRun=Date.now(),this.timeoutId=void 0},this.options.wait-(t-this.lastRun))}destroy(){this.timeoutId&&window.clearTimeout(this.timeoutId)}}class xo{constructor(e,t){this.handler=e,this.options=t,this.controls=new Map,this.handle=e=>{const t=String(this.options.keyExtractor(e));let n=this.controls.get(t);n||(n=new wo(this.handler,this.baseOptions),this.controls.set(t,n)),n.handle(e)},this.baseOptions={mode:t.mode,wait:t.wait,..."throttle"===t.mode&&"throttleMode"in t?{throttleMode:t.throttleMode}:{}}}destroy(){for(const e of this.controls.values())e.destroy();this.controls.clear()}}function Co(e){return"keyExtractor"in e}function ko(e,t,n){return en?n:e}function Io(e,t,n){if(e===t)return!0;if(null==e||null==t)return e===t;const o=typeof e;if(o!==typeof t)return!1;if("object"===o){n||(n=new Set);const o=function(e,t){return`${Mo(e)}__${Mo(t)}`}(e,t);if(n.has(o))return!0;n.add(o);const i=Array.isArray(e),r=Array.isArray(t);return i&&r?function(e,t,n){if(e.length!==t.length)return!1;const o=new Array(t.length).fill(!1);e:for(let i=0;ie.forEach(e=>e(t)),on:t=>(e.add(t),()=>e.delete(t)),off:t=>e.delete(t),clear:()=>e.clear()}}function Do(e,t=Io){const n=new Set,o=new Map;let i=e;const r=(e,t)=>{let r=e,a=()=>{};if(t){if(Co(t)){const n=new xo(e,t);r=n.handle,a=()=>n.destroy()}else{const n=new wo(e,t);r=n.handle,a=()=>n.destroy()}o.set(e,{wrapped:r,destroy:a})}return void 0!==i&&r(i),n.add(r),()=>{n.delete(r),a(),o.delete(e)}};return{get value(){return i},emit(e=void 0){void 0!==i&&t(i,e)||(i=e,(e=>{n.forEach(t=>t(e))})(e))},on:r,off(e){const t=o.get(e);t?(n.delete(t.wrapped),t.destroy(),o.delete(e)):n.delete(e)},clear(){n.clear(),o.forEach(e=>e.destroy()),o.clear()},select:(e,t=Io)=>(n,o)=>{let a;if(void 0!==i){const t=e(i);a=t,n(t)}return r(o=>{const i=e(o);void 0!==a&&t(a,i)||(a=i,n(i))},o)}}}function Ro(e,t){const n=(null==t?void 0:t.cache)??!0,o=(null==t?void 0:t.equality)??Io,i=new Map,r=new Map,a=new Map,s=new Set,l=new Map,c=e=>String(e);return{emit(t,a){const l=c(t);if(n){const e=i.get(l);if(void 0!==e&&o(e,a))return;i.set(l,a)}const d=r.get(l);d&&d.forEach(e=>e(a));const u=e(t,a);s.forEach(e=>e(u))},forScope(e){const t=c(e);return(e,o)=>{const s=(e=>{let t=r.get(e);return t||(t=new Set,r.set(e,t)),t})(t),l=(e=>{let t=a.get(e);return t||(t=new Map,a.set(e,t)),t})(t);let c=e,d=()=>{};if(o){if(Co(o)){const t=new xo(e,o);c=t.handle,d=()=>t.destroy()}else{const t=new wo(e,o);c=t.handle,d=()=>t.destroy()}l.set(e,{wrapped:c,destroy:d})}if(n){const e=i.get(t);void 0!==e&&c(e)}return s.add(c),()=>{s.delete(c),d(),l.delete(e),0===s.size&&r.delete(t),0===l.size&&a.delete(t)}}},onGlobal:(e,t)=>{let n=e,o=()=>{};if(t){if(Co(t)){const i=new xo(e,t);n=i.handle,o=()=>i.destroy()}else{const i=new wo(e,t);n=i.handle,o=()=>i.destroy()}l.set(e,{wrapped:n,destroy:o})}return s.add(n),()=>{s.delete(n),o(),l.delete(e)}},getValue:e=>n?i.get(c(e)):void 0,getScopes:()=>n?Array.from(i.keys()):Array.from(r.keys()),clearScope(e){const t=c(e);n&&i.delete(t);const o=r.get(t);o&&(o.clear(),r.delete(t));const s=a.get(t);s&&(s.forEach(e=>e.destroy()),s.clear(),a.delete(t))},clear(){n&&i.clear(),r.forEach(e=>e.clear()),r.clear(),a.forEach(e=>{e.forEach(e=>e.destroy()),e.clear()}),a.clear(),s.clear(),l.forEach(e=>e.destroy()),l.clear()}}}class zo{constructor(e){this.autoMountElements=[],this.package=e}addUtility(e){return this.autoMountElements.push({component:e,type:"utility"}),this}addWrapper(e){return this.autoMountElements.push({component:e,type:"wrapper"}),this}build(){return{...this.package,autoMountElements:()=>this.autoMountElements}}}function To(e){return new zo(e)}const Eo=de({registry:null,coreState:null,isInitializing:!0,pluginsReady:!1,activeDocumentId:null,activeDocument:null,documents:{},documentStates:[]});function _o({plugins:e,children:t}){const{utilities:n,wrappers:o}=Re(()=>{const t=[],n=[];for(const o of e){const e=o.package;if(yo(e)){const o=e.autoMountElements()||[];for(const e of o)"utility"===e.type?t.push(e.component):"wrapper"===e.type&&n.push(e.component)}}return{utilities:t,wrappers:n}},[e]),i=He(H,{children:[t,n.map((e,t)=>He(e,{},`utility-${t}`))]});return He(H,{children:o.reduce((e,t)=>He(t,{children:e}),i)})}function No({engine:e,config:t,logger:n,onInitialized:o,plugins:i,children:r,autoMountDomElements:a=!0}){const[s,l]=Se(null),[c,d]=Se(null),[u,h]=Se(!0),[m,g]=Se(!1),p=De(o);Me(()=>{p.current=o},[o]),Me(()=>{const o={...t,logger:(null==t?void 0:t.logger)??n},r=new fo(e,o);r.registerPluginBatch(i);let a;return(async()=>{var e;if(await r.initialize(),r.isDestroyed())return;const t=r.getStore();d(t.getState().core);const n=t.subscribe((e,n,o)=>{t.isCoreAction(e)&&n.core!==o.core&&d(n.core)});if(await(null==(e=p.current)?void 0:e.call(p,r)),!r.isDestroyed())return r.pluginsReady().then(()=>{r.isDestroyed()||g(!0)}),l(r),h(!1),n;n()})().then(e=>{a=e}).catch(console.error),()=>{null==a||a(),r.destroy(),l(null),d(null),h(!0),g(!1)}},[e,i]);const f=Re(()=>{const e=(null==c?void 0:c.activeDocumentId)??null,t=(null==c?void 0:c.documents)??{},n=(null==c?void 0:c.documentOrder)??[],o=e&&t[e]?t[e]:null,i=n.map(e=>t[e]).filter(e=>null!=e);return{registry:s,coreState:c,isInitializing:u,pluginsReady:m,activeDocumentId:e,activeDocument:o,documents:t,documentStates:i}},[s,c,u,m]),v="function"==typeof r?r(f):r;return He(Eo.Provider,{value:f,children:m&&a?He(_o,{plugins:i,children:v}):v})}function Lo(e){const{registry:t}=function(){const e=Te(Eo);if(void 0===e)throw new Error("useCapability must be used within a PDFContext.Provider");const{registry:t,isInitializing:n}=e;if(n)return e;if(null===t)throw new Error("PDF registry failed to initialize properly");return e}();if(null===t)return{plugin:null,isLoading:!0,ready:new Promise(()=>{})};const n=t.getPlugin(e);if(!n)throw new Error(`Plugin ${e} not found`);return{plugin:n,isLoading:!1,ready:n.ready()}}function Oo(e){const{plugin:t,isLoading:n,ready:o}=Lo(e);if(!t)return{provides:null,isLoading:n,ready:o};if(!t.provides)throw new Error(`Plugin ${e} does not provide a capability`);return{provides:t.provides(),isLoading:n,ready:o}}function $o(){const{coreState:e}=Te(Eo);return e}function jo(e){const t=$o();return Re(()=>t&&e?t.documents[e]??null:null,[t,e])}Qt.Print,Qt.ModifyContents,Qt.CopyContents,Qt.ModifyAnnotations,Qt.FillForms,Qt.ExtractForAccessibility,Qt.AssembleDocument,Qt.PrintHighQuality;const Fo=[Qt.Print,Qt.ModifyContents,Qt.CopyContents,Qt.ModifyAnnotations,Qt.FillForms,Qt.ExtractForAccessibility,Qt.AssembleDocument,Qt.PrintHighQuality],Uo={[Qt.Print]:"print",[Qt.ModifyContents]:"modifyContents",[Qt.CopyContents]:"copyContents",[Qt.ModifyAnnotations]:"modifyAnnotations",[Qt.FillForms]:"fillForms",[Qt.ExtractForAccessibility]:"extractForAccessibility",[Qt.AssembleDocument]:"assembleDocument",[Qt.PrintHighQuality]:"printHighQuality"};function Ho(e,t){if(!e)return;if(t in e)return e[t];const n=Uo[t];return n&&n in e?e[n]:void 0}function Wo(e,t,n){var o;const i=e.documents[t],r=null==i?void 0:i.permissions,a=e.globalPermissions,s=(null==(o=null==i?void 0:i.document)?void 0:o.permissions)??Qt.AllowAll,l=Ho(null==r?void 0:r.overrides,n);if(void 0!==l)return l;const c=Ho(null==a?void 0:a.overrides,n);if(void 0!==c)return c;return!((null==r?void 0:r.enforceDocumentPermissions)??(null==a?void 0:a.enforceDocumentPermissions)??!0)||0!==(s&n)}function Bo(e){const t=$o();return Re(()=>{var n,o;if(!t)return{permissions:Qt.AllowAll,pdfPermissions:Qt.AllowAll,hasPermission:()=>!0,hasAllPermissions:()=>!0,canPrint:!0,canModifyContents:!0,canCopyContents:!0,canModifyAnnotations:!0,canFillForms:!0,canExtractForAccessibility:!0,canAssembleDocument:!0,canPrintHighQuality:!0};const i=function(e,t){return Fo.reduce((n,o)=>Wo(e,t,o)?n|o:n,0)}(t,e),r=n=>Wo(t,e,n);return{permissions:i,pdfPermissions:(null==(o=null==(n=t.documents[e])?void 0:n.document)?void 0:o.permissions)??Qt.AllowAll,hasPermission:r,hasAllPermissions:(...n)=>n.every(n=>Wo(t,e,n)),canPrint:r(Qt.Print),canModifyContents:r(Qt.ModifyContents),canCopyContents:r(Qt.CopyContents),canModifyAnnotations:r(Qt.ModifyAnnotations),canFillForms:r(Qt.FillForms),canExtractForAccessibility:r(Qt.ExtractForAccessibility),canAssembleDocument:r(Qt.AssembleDocument),canPrintHighQuality:r(Qt.PrintHighQuality)}},[t,e])}const qo="https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@2.8.0/dist/pdfium.wasm";de(void 0);const Go="viewport",Vo={id:Go,name:"Viewport Plugin",version:"1.0.0",provides:["viewport"],requires:[],optional:[],defaultConfig:{viewportGap:10,scrollEndDelay:300}},Ko="INIT_VIEWPORT_STATE",Zo="CLEANUP_VIEWPORT_STATE",Yo="REGISTER_VIEWPORT",Xo="UNREGISTER_VIEWPORT",Qo="SET_VIEWPORT_METRICS",Jo="SET_VIEWPORT_SCROLL_METRICS",ei="SET_VIEWPORT_GAP",ti="SET_SCROLL_ACTIVITY",ni="SET_SMOOTH_SCROLL_ACTIVITY",oi="ADD_VIEWPORT_GATE",ii="REMOVE_VIEWPORT_GATE";function ri(e,t){return{type:ni,payload:{documentId:e,isSmoothScrolling:t}}}const ai={viewportMetrics:{width:0,height:0,scrollTop:0,scrollLeft:0,clientWidth:0,clientHeight:0,scrollWidth:0,scrollHeight:0,clientLeft:0,clientTop:0,relativePosition:{x:0,y:0}},isScrolling:!1,isSmoothScrolling:!1,gates:new Set},si={viewportGap:0,documents:{},activeViewports:new Set,activeDocumentId:null},li=class extends bo{constructor(e,t,n){var o;super(e,t),this.id=e,this.viewportResize$=Do(),this.viewportMetrics$=Do(),this.scrollMetrics$=Do(),this.scrollActivity$=Do(),this.gateState$=Do(),this.scrollRequests$=new Map,n.viewportGap&&this.dispatch((o=n.viewportGap,{type:ei,payload:o})),this.scrollEndDelay=n.scrollEndDelay||100}onDocumentLoadingStarted(e){this.dispatch(function(e){return{type:Ko,payload:{documentId:e}}}(e)),this.scrollRequests$.set(e,Po()),this.logger.debug("ViewportPlugin","DocumentOpened",`Initialized viewport state for document: ${e}`)}onDocumentClosed(e){var t;this.dispatch(function(e){return{type:Zo,payload:{documentId:e}}}(e)),null==(t=this.scrollRequests$.get(e))||t.clear(),this.scrollRequests$.delete(e),this.logger.debug("ViewportPlugin","DocumentClosed",`Cleaned up viewport state for document: ${e}`)}buildCapability(){return{getViewportGap:()=>this.state.viewportGap,getMetrics:()=>this.getMetrics(),scrollTo:e=>this.scrollTo(e),isScrolling:()=>this.isScrolling(),isSmoothScrolling:()=>this.isSmoothScrolling(),isGated:e=>this.isGated(e),hasGate:(e,t)=>this.hasGate(e,t),getGates:e=>this.getGates(e),forDocument:e=>this.createViewportScope(e),gate:(e,t)=>this.gate(e,t),releaseGate:(e,t)=>this.releaseGate(e,t),isViewportMounted:e=>this.state.activeViewports.has(e),onViewportChange:this.viewportMetrics$.on,onViewportResize:this.viewportResize$.on,onScrollChange:this.scrollMetrics$.on,onScrollActivity:this.scrollActivity$.on,onGateChange:this.gateState$.on}}createViewportScope(e){return{getMetrics:()=>this.getMetrics(e),scrollTo:t=>this.scrollTo(t,e),isScrolling:()=>this.isScrolling(e),isSmoothScrolling:()=>this.isSmoothScrolling(e),isGated:()=>this.isGated(e),hasGate:t=>this.hasGate(t,e),getGates:()=>this.getGates(e),gate:t=>this.gate(t,e),releaseGate:t=>this.releaseGate(t,e),onViewportChange:t=>this.viewportMetrics$.on(n=>{n.documentId===e&&t(n.metrics)}),onScrollChange:t=>this.scrollMetrics$.on(n=>{n.documentId===e&&t(n.scrollMetrics)}),onScrollActivity:t=>this.scrollActivity$.on(n=>{n.documentId===e&&t(n.activity)}),onGateChange:t=>this.gateState$.on(n=>{(null==n?void 0:n.documentId)===e&&t(n)})}}registerViewport(e){if(!this.state.documents[e])throw new Error(`Cannot register viewport for ${e}: document state not found. Document must be opened before registering viewport.`);this.state.activeViewports.has(e)||(this.dispatch(function(e){return{type:Yo,payload:{documentId:e}}}(e)),this.logger.debug("ViewportPlugin","RegisterViewport",`Registered viewport (DOM mounted) for document: ${e}`))}unregisterViewport(e){this.registry.isDestroyed()||this.state.activeViewports.has(e)&&(this.dispatch(function(e){return{type:Xo,payload:{documentId:e}}}(e)),this.logger.debug("ViewportPlugin","UnregisterViewport",`Unregistered viewport (DOM unmounted) for document: ${e}. State preserved.`))}setViewportResizeMetrics(e,t){if(this.registry.isDestroyed())return;this.dispatch(function(e,t){return{type:Qo,payload:{documentId:e,metrics:t}}}(e,t));const n=this.state.documents[e];n&&this.viewportResize$.emit({documentId:e,metrics:n.viewportMetrics})}setViewportScrollMetrics(e,t){if(this.registry.isDestroyed())return;const n=this.state.documents[e];n&&(t.scrollTop===n.viewportMetrics.scrollTop&&t.scrollLeft===n.viewportMetrics.scrollLeft||(this.dispatch(function(e,t){return{type:Jo,payload:{documentId:e,scrollMetrics:t}}}(e,t)),this.bumpScrollActivity(e),this.scrollMetrics$.emit({documentId:e,scrollMetrics:t})))}onScrollRequest(e,t){const n=this.scrollRequests$.get(e);if(!n)throw new Error(`Cannot subscribe to scroll requests for ${e}: document state not initialized`);return n.on(t)}gate(e,t){const n=this.state.documents[t];n?n.gates.has(e)||(this.dispatch(function(e,t){return{type:oi,payload:{documentId:e,key:t}}}(t,e)),this.logger.debug("ViewportPlugin","GateAdded",`Added gate '${e}' for document: ${t}. Total gates: ${n.gates.size+1}`)):this.logger.warn("ViewportPlugin","GateViewport",`Cannot gate viewport for ${t}: document not found`)}releaseGate(e,t){const n=this.state.documents[t];n?n.gates.has(e)&&(this.dispatch(function(e,t){return{type:ii,payload:{documentId:e,key:t}}}(t,e)),this.logger.debug("ViewportPlugin","GateReleased",`Released gate '${e}' for document: ${t}. Remaining gates: ${n.gates.size-1}`)):this.logger.warn("ViewportPlugin","ReleaseGate",`Cannot release gate for ${t}: document not found`)}getViewportState(e){const t=e??this.getActiveDocumentId(),n=this.state.documents[t];if(!n)throw new Error(`Viewport state not found for document: ${t}`);return n}getMetrics(e){return this.getViewportState(e).viewportMetrics}isScrolling(e){return this.getViewportState(e).isScrolling}isSmoothScrolling(e){return this.getViewportState(e).isSmoothScrolling}isGated(e){return this.getViewportState(e).gates.size>0}hasGate(e,t){return this.getViewportState(t).gates.has(e)}getGates(e){const t=this.getViewportState(e);return Array.from(t.gates)}scrollTo(e,t){const n=t??this.getActiveDocumentId(),o=this.getViewportState(n),{x:i,y:r,alignX:a,alignY:s,behavior:l="auto"}=e;"smooth"===l&&this.dispatch(ri(n,!0));const c=o.viewportMetrics;let d=i,u=r;void 0!==a&&(d=i-c.clientWidth*(a/100)),void 0!==s&&(u=r-c.clientHeight*(s/100));const h=this.scrollRequests$.get(n);h&&h.emit({x:d,y:u,behavior:l})}bumpScrollActivity(e){this.debouncedDispatch(function(e,t){return{type:ti,payload:{documentId:e,isScrolling:t}}}(e,!1),this.scrollEndDelay),this.debouncedDispatch(ri(e,!1),this.scrollEndDelay)}onStoreUpdated(e,t){for(const n in t.documents){const o=e.documents[n],i=t.documents[n];if(o!==i&&(this.viewportMetrics$.emit({documentId:n,metrics:i.viewportMetrics}),!o||o.isScrolling===i.isScrolling&&o.isSmoothScrolling===i.isSmoothScrolling||this.scrollActivity$.emit({documentId:n,activity:{isScrolling:i.isScrolling,isSmoothScrolling:i.isSmoothScrolling}}),o&&o.gates!==i.gates)){const e=Array.from(o.gates),t=Array.from(i.gates),r=t.find(t=>!e.includes(t)),a=e.find(e=>!t.includes(e));this.gateState$.emit({documentId:n,isGated:i.gates.size>0,gates:t,addedGate:r,removedGate:a}),this.logger.debug("ViewportPlugin","GateStateChanged",`Gate state changed for document ${n}. Gates: [${t.join(", ")}], Gated: ${i.gates.size>0}`)}}}async initialize(e){this.logger.info("ViewportPlugin","Initialize","Viewport plugin initialized")}async destroy(){this.viewportMetrics$.clear(),this.viewportResize$.clear(),this.scrollMetrics$.clear(),this.scrollActivity$.clear(),this.gateState$.clear(),this.scrollRequests$.forEach(e=>e.clear()),this.scrollRequests$.clear(),super.destroy()}};li.id="viewport";let ci=li;const di={manifest:Vo,create:(e,t)=>new ci(Go,e,t),reducer:(e=si,t)=>{switch(t.type){case Ko:{const{documentId:n}=t.payload;return{...e,documents:{...e.documents,[n]:{...ai,gates:new Set}}}}case Zo:{const{documentId:n}=t.payload,{[n]:o,...i}=e.documents,r=new Set(e.activeViewports);return r.delete(n),{...e,documents:i,activeViewports:r,activeDocumentId:e.activeDocumentId===n?null:e.activeDocumentId}}case Yo:{const{documentId:n}=t.payload,o=new Set(e.activeViewports);return o.add(n),{...e,activeViewports:o,activeDocumentId:e.activeDocumentId??n}}case Xo:{const{documentId:n}=t.payload,o=new Set(e.activeViewports);return o.delete(n),{...e,activeViewports:o}}case"SET_ACTIVE_VIEWPORT_DOCUMENT":return{...e,activeDocumentId:t.payload};case ei:return{...e,viewportGap:t.payload};case Qo:{const{documentId:n,metrics:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,viewportMetrics:{width:o.width,height:o.height,scrollTop:o.scrollTop,scrollLeft:o.scrollLeft,clientWidth:o.clientWidth,clientHeight:o.clientHeight,scrollWidth:o.scrollWidth,scrollHeight:o.scrollHeight,clientLeft:o.clientLeft,clientTop:o.clientTop,relativePosition:{x:o.scrollWidth<=o.clientWidth?0:o.scrollLeft/(o.scrollWidth-o.clientWidth),y:o.scrollHeight<=o.clientHeight?0:o.scrollTop/(o.scrollHeight-o.clientHeight)}}}}}:e}case Jo:{const{documentId:n,scrollMetrics:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,viewportMetrics:{...i.viewportMetrics,scrollTop:o.scrollTop,scrollLeft:o.scrollLeft},isScrolling:!0}}}:e}case ti:{const{documentId:n,isScrolling:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,isScrolling:o}}}:e}case ni:{const{documentId:n,isSmoothScrolling:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,isSmoothScrolling:o}}}:e}case oi:{const{documentId:n,key:o}=t.payload,i=e.documents[n];if(!i)return e;const r=new Set(i.gates);return r.add(o),{...e,documents:{...e.documents,[n]:{...i,gates:r}}}}case ii:{const{documentId:n,key:o}=t.payload,i=e.documents[n];if(!i)return e;const r=new Set(i.gates);return r.delete(o),{...e,documents:{...e.documents,[n]:{...i,gates:r}}}}default:return e}},initialState:si},ui=de(null),hi=()=>Oo(ci.id);function mi(e){const{plugin:t}=Lo(ci.id),n=De(null);return Pe(()=>{if(!t)return;const o=n.current;if(!o)return;try{t.registerViewport(e)}catch(t){return void console.error(`Failed to register viewport for document ${e}:`,t)}const i=()=>{t.setViewportScrollMetrics(e,{scrollTop:o.scrollTop,scrollLeft:o.scrollLeft})};o.addEventListener("scroll",i);const r=new ResizeObserver(()=>{t.setViewportResizeMetrics(e,{width:o.offsetWidth,height:o.offsetHeight,clientWidth:o.clientWidth,clientHeight:o.clientHeight,scrollTop:o.scrollTop,scrollLeft:o.scrollLeft,scrollWidth:o.scrollWidth,scrollHeight:o.scrollHeight,clientLeft:o.clientLeft,clientTop:o.clientTop})});r.observe(o);const a=t.onScrollRequest(e,({x:e,y:t,behavior:n="auto"})=>{requestAnimationFrame(()=>{o.scrollTo({left:e,top:t,behavior:n})})});return()=>{t.unregisterViewport(e),r.disconnect(),o.removeEventListener("scroll",i),a()}},[t,e]),n}function gi({children:e,documentId:t,...n}){const[o,i]=Se(0),r=mi(t),{provides:a}=hi(),s=(e=>{const{provides:t}=hi(),[n,o]=Se((null==t?void 0:t.isGated(e))??!1);return Me(()=>{if(t)return o(t.isGated(e)),t.onGateChange(t=>{t.documentId===e&&o(t.isGated)})},[t,e]),n})(t);Me(()=>{a&&i(a.getViewportGap())},[a]);const{style:l,...c}=n;return He(ui.Provider,{value:r,children:He("div",{...c,ref:r,style:{width:"100%",height:"100%",overflow:"auto",..."object"==typeof l?l:{},padding:`${o}px`},children:!s&&e})})}var pi=(e=>(e.Vertical="vertical",e.Horizontal="horizontal",e))(pi||{});class fi{constructor(e){this.pageGap=e.pageGap??20,this.viewportGap=e.viewportGap??20,this.bufferSize=e.bufferSize??2}getVisibleRange(e,t,n){const o=this.getScrollOffset(e),i=o,r=o+this.getClientSize(e);let a=0;for(;ae.pageNumber),l=t.slice(o.start,o.end+1).flatMap(e=>e.index),c=this.determineCurrentPage(a),d=t[o.start],u=t[o.end],h=d?d.offset*n:0,m=u?(t[t.length-1].offset+t[t.length-1].height)*n-(u.offset+u.height)*n:0;return{currentPage:c,visiblePages:s,pageVisibilityMetrics:a,renderedPageIndexes:l,scrollOffset:{x:e.scrollLeft,y:e.scrollTop},startSpacing:h,endSpacing:m}}calculatePageVisibility(e,t,n,o){const i=[],r=o??Math.max(...e.map(e=>e.width));return e.forEach(e=>{const o=e.width{const a=(e.x+o)*n,s=e.y*n,l=a+r.x*n,c=s+r.y*n,d=r.rotatedWidth*n,u=r.rotatedHeight*n,h=t.scrollLeft,m=t.scrollTop,g=h+t.clientWidth,p=m+t.clientHeight,f=Math.max(l,h),v=Math.max(c,m),y=Math.min(l+d,g),b=Math.min(c+u,p);if(fe.visiblePercentage)),n=e.filter(e=>e.visiblePercentage===t);return 1===n.length?n[0].pageNumber:n.sort((e,t)=>e.pageNumber-t.pageNumber)[0].pageNumber}getRectLocationForPage(e,t,n){const o=t.find(t=>t.pageNumbers.includes(e));if(!o)return null;const i=o.pageLayouts.find(t=>t.pageNumber===e);if(!i)return null;let r=0;if(n){const e=n.width;o.width{let o=0;const i=e.map(e=>{const t={pageNumber:e.index+1,pageIndex:e.index,x:o,y:0,width:e.size.width,height:e.size.height,rotatedWidth:e.rotatedSize.width,rotatedHeight:e.rotatedSize.height};return o+=e.rotatedSize.width+this.pageGap,t}),r=e.reduce((t,n,o)=>t+n.rotatedSize.width+(oe.rotatedSize.height)),s={id:`item-${n}`,x:0,y:t,offset:t,width:r,height:a,pageLayouts:i,pageNumbers:e.map(e=>e.index+1),index:n};return t+=a+this.pageGap,s})}getTotalContentSize(e){if(0===e.length)return{width:0,height:0};return{width:Math.max(...e.map(e=>e.width)),height:e[e.length-1].y+e[e.length-1].height}}getScrollOffset(e){return e.scrollTop}getClientSize(e){return e.clientHeight}}class yi extends fi{constructor(e){super(e)}createVirtualItems(e){let t=0;return e.map((e,n)=>{let o=0;const i=e.map(e=>{const t={pageNumber:e.index+1,pageIndex:e.index,x:o,y:0,width:e.size.width,height:e.size.height,rotatedWidth:e.rotatedSize.width,rotatedHeight:e.rotatedSize.height};return o+=e.rotatedSize.width+this.pageGap,t}),r=e.reduce((t,n,o)=>t+n.rotatedSize.width+(oe.rotatedSize.height)),s={id:`item-${n}`,x:t,y:0,offset:t,width:r,height:a,pageLayouts:i,pageNumbers:e.map(e=>e.index+1),index:n};return t+=r+this.pageGap,s})}getTotalContentSize(e){if(0===e.length)return{width:0,height:0};return{width:e[e.length-1].x+e[e.length-1].width,height:Math.max(...e.map(e=>e.height))}}getScrollOffset(e){return e.scrollLeft}getClientSize(e){return e.clientWidth}}const bi="INIT_SCROLL_STATE",wi="CLEANUP_SCROLL_STATE",xi="UPDATE_DOCUMENT_SCROLL_STATE",Ci="SET_SCROLL_STRATEGY";function ki(e,t){return{type:xi,payload:{documentId:e,state:t}}}const Ii={isChanging:!1,targetPage:1,fromPage:1,startTime:0},Si=class extends bo{constructor(e,t,n){var o,i,r;super(e,t),this.id=e,this.config=n,this.elevatedPages=new Map,this.strategies=new Map,this.layoutReady=new Set,this.initialLayoutFired=new Set,this.scrollerLayoutEmitters=new Map,this.pageChange$=Do(),this.scroll$=Do(),this.layoutChange$=Do(),this.pageChangeState$=Do(),this.layoutReady$=Do(),this.state$=Do(),this.viewport=this.registry.getPlugin("viewport").provides(),this.spread=(null==(o=this.registry.getPlugin("spread"))?void 0:o.provides())??null,this.viewport.onScrollActivity(e=>{const t=this.getDocumentState(e.documentId);(null==t?void 0:t.pageChangeState.isChanging)&&!e.activity.isSmoothScrolling&&this.completePageChange(e.documentId)}),null==(i=this.spread)||i.onSpreadChange(e=>{this.refreshDocumentLayout(e.documentId)});const a=null==(r=this.registry.getPlugin("interaction-manager"))?void 0:r.provides();a&&a.onPageActivityChange(e=>{let t=this.elevatedPages.get(e.documentId);e.hasActivity?(t||(t=new Set,this.elevatedPages.set(e.documentId,t)),t.add(e.pageIndex)):null==t||t.delete(e.pageIndex),this.pushScrollerLayout(e.documentId)}),this.viewport.onViewportChange(e=>{const t=this.getDocumentState(e.documentId);if(!t)return;const n=this.computeMetrics(e.documentId,e.metrics);this.layoutReady.has(e.documentId)?this.commitMetrics(e.documentId,n):this.commitMetrics(e.documentId,{...n,scrollOffset:t.scrollOffset})})}onDocumentLoadingStarted(e){const t=this.getCoreDocument(e);if(!t)return;const n=this.createDocumentState(t);this.dispatch(function(e,t){return{type:bi,payload:{documentId:e,state:t}}}(e,n));const o=this.createStrategy(n.strategy);this.strategies.set(e,o),this.scrollerLayoutEmitters.set(e,Do())}onDocumentLoaded(e){var t;const n=this.getCoreDocument(e);n&&(this.dispatch(ki(e,{totalPages:(null==(t=n.document)?void 0:t.pageCount)??0})),this.refreshDocumentLayout(e),this.logger.debug("ScrollPlugin","DocumentOpened",`Initialized scroll state for document: ${e}`))}onDocumentClosed(e){this.strategies.delete(e),this.layoutReady.delete(e),this.initialLayoutFired.delete(e),this.elevatedPages.delete(e);const t=this.scrollerLayoutEmitters.get(e);t&&(t.clear(),this.scrollerLayoutEmitters.delete(e)),this.dispatch(function(e){return{type:wi,payload:e}}(e)),this.logger.debug("ScrollPlugin","DocumentClosed",`Cleaned up scroll state for document: ${e}`)}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const n=this.viewport.forDocument(e),o=this.computeMetrics(e,n.getMetrics());this.commitMetrics(e,o)}onRotationChanged(e){this.refreshDocumentLayout(e)}onScrollerData(e,t){const n=this.scrollerLayoutEmitters.get(e);if(!n)throw new Error(`No scroller layout emitter found for document: ${e}`);return n.on(t)}getScrollerLayout(e){const t=this.getDocumentState(e),n=this.getCoreDocumentOrThrow(e);if(!t||!n)throw new Error(`Cannot get scroller layout for document: ${e}`);return o=t,i=n.scale,r=this.elevatedPages.get(e),{startSpacing:o.startSpacing,endSpacing:o.endSpacing,totalWidth:o.totalContentSize.width*i,totalHeight:o.totalContentSize.height*i,pageGap:o.pageGap*i,strategy:o.strategy,items:o.renderedPageIndexes.map(e=>({...o.virtualItems[e],pageLayouts:o.virtualItems[e].pageLayouts.map(e=>({...e,rotatedWidth:e.rotatedWidth*i,rotatedHeight:e.rotatedHeight*i,width:e.width*i,height:e.height*i,elevated:(null==r?void 0:r.has(e.pageIndex))??!1}))}))};var o,i,r}setLayoutReady(e){if(this.layoutReady.has(e))return;const t=this.getDocumentState(e);if(!t)return;this.layoutReady.add(e);const n=!this.initialLayoutFired.has(e);n&&this.initialLayoutFired.add(e);this.viewport.forDocument(e).scrollTo({...t.scrollOffset,behavior:"instant"}),this.layoutReady$.emit({documentId:e,isInitial:n,pageNumber:t.currentPage,totalPages:t.totalPages})}clearLayoutReady(e){this.layoutReady.delete(e)}buildCapability(){return{getCurrentPage:()=>this.getCurrentPage(),getTotalPages:()=>this.getTotalPages(),getPageChangeState:()=>this.getPageChangeState(),scrollToPage:e=>this.scrollToPage(e),scrollToNextPage:e=>this.scrollToNextPage(e),scrollToPreviousPage:e=>this.scrollToPreviousPage(e),getMetrics:e=>this.getMetrics(e),getLayout:()=>this.getLayout(),getRectPositionForPage:(e,t,n,o)=>this.getRectPositionForPage(e,t,n,o),forDocument:e=>this.createScrollScope(e),setScrollStrategy:(e,t)=>this.setScrollStrategyForDocument(e,t),getPageGap:()=>this.state.defaultPageGap,onPageChange:this.pageChange$.on,onScroll:this.scroll$.on,onLayoutChange:this.layoutChange$.on,onLayoutReady:this.layoutReady$.on,onPageChangeState:this.pageChangeState$.on,onStateChange:this.state$.on}}createScrollScope(e){return{getCurrentPage:()=>this.getCurrentPage(e),getTotalPages:()=>this.getTotalPages(e),getPageChangeState:()=>this.getPageChangeState(e),scrollToPage:t=>this.scrollToPage(t,e),scrollToNextPage:t=>this.scrollToNextPage(t,e),scrollToPreviousPage:t=>this.scrollToPreviousPage(t,e),getSpreadPagesWithRotatedSize:()=>this.getSpreadPagesWithRotatedSize(e),getMetrics:t=>this.getMetrics(t,e),getLayout:()=>this.getLayout(e),getRectPositionForPage:(t,n,o,i)=>this.getRectPositionForPage(t,n,o,i,e),setScrollStrategy:t=>this.setScrollStrategyForDocument(t,e),onPageChange:t=>this.pageChange$.on(n=>{n.documentId===e&&t(n)}),onScroll:t=>this.scroll$.on(n=>{n.documentId===e&&t(n.metrics)}),onLayoutChange:t=>this.layoutChange$.on(n=>{n.documentId===e&&t(n.layout)})}}getDocumentState(e){const t=e??this.getActiveDocumentId();return this.state.documents[t]??null}getDocumentStateOrThrow(e){const t=this.getDocumentState(e);if(!t)throw new Error(`Scroll state not found for document: ${e??"active"}`);return t}getStrategy(e){const t=e??this.getActiveDocumentId(),n=this.strategies.get(t);if(!n)throw new Error(`Strategy not found for document: ${t}`);return n}createStrategy(e){const t={pageGap:this.state.defaultPageGap,viewportGap:this.viewport.getViewportGap(),bufferSize:this.state.defaultBufferSize};return e===pi.Horizontal?new yi(t):new vi(t)}createDocumentState(e){var t;return{virtualItems:[],totalPages:(null==(t=e.document)?void 0:t.pageCount)??0,currentPage:1,totalContentSize:{width:0,height:0},strategy:this.state.defaultStrategy,pageGap:this.state.defaultPageGap,visiblePages:[],pageVisibilityMetrics:[],renderedPageIndexes:[],scrollOffset:{x:0,y:0},startSpacing:0,endSpacing:0,pageChangeState:Ii}}startPageChange(e,t,n="smooth"){const o=this.getDocumentState(e);if(!o)return;const i={isChanging:!0,targetPage:t,fromPage:o.currentPage,startTime:Date.now()};this.dispatch(ki(e,{pageChangeState:i})),"instant"===n&&this.completePageChange(e)}completePageChange(e){const t=this.getDocumentState(e);if(!t||!t.pageChangeState.isChanging)return;const n={isChanging:!1,targetPage:t.pageChangeState.targetPage,fromPage:t.pageChangeState.fromPage,startTime:t.pageChangeState.startTime};this.dispatch(ki(e,{pageChangeState:n}))}computeLayout(e,t){const n=this.getStrategy(e),o=n.createVirtualItems(t);return{virtualItems:o,totalContentSize:n.getTotalContentSize(o)}}computeMetrics(e,t,n){const o=this.getCoreDocumentOrThrow(e),i=this.getDocumentState(e),r=this.getStrategy(e);if(!i)throw new Error(`Document state not found: ${e}`);return r.handleScroll(t,n??i.virtualItems,o.scale)}commitMetrics(e,t){const n=this.getDocumentState(e);n&&(this.dispatch(ki(e,t)),this.scroll$.emit({documentId:e,metrics:t}),t.currentPage!==n.currentPage&&this.pageChange$.emit({documentId:e,pageNumber:t.currentPage,totalPages:n.totalPages}),this.pushScrollerLayout(e))}pushScrollerLayout(e){const t=this.scrollerLayoutEmitters.get(e);if(t)try{const n=this.getScrollerLayout(e);t.emit(n)}catch(e){}}refreshDocumentLayout(e){const t=this.coreState.core.documents[e],n=this.getDocumentState(e);if(!t||!n||"loaded"!==t.status)return;const o=this.getSpreadPagesWithRotatedSize(e),i=this.computeLayout(e,o),r=this.viewport.forDocument(e),a=this.computeMetrics(e,r.getMetrics(),i.virtualItems);this.dispatch(ki(e,{...i,...a})),this.layoutChange$.emit({documentId:e,layout:i}),this.pushScrollerLayout(e)}getSpreadPagesWithRotatedSize(e){var t,n;const o=e??this.getActiveDocumentId(),i=this.coreState.core.documents[o];if(!i)throw new Error(`Document ${o} not loaded`);return((null==(t=this.spread)?void 0:t.forDocument(o).getSpreadPages())||(null==(n=i.document)?void 0:n.pages.map(e=>[e]))||[]).map(e=>e.map(e=>{const t=((e.rotation??0)+i.rotation)%4;return{...e,rotatedSize:Ke(e.size,t,1)}}))}getCurrentPage(e){return this.getDocumentStateOrThrow(e).currentPage}getTotalPages(e){return this.getDocumentStateOrThrow(e).totalPages}getPageChangeState(e){return this.getDocumentStateOrThrow(e).pageChangeState}scrollToPage(e,t){var n;const o=t??this.getActiveDocumentId(),i=this.getDocumentStateOrThrow(o),r=this.getStrategy(o),a=this.getCoreDocumentOrThrow(o),{pageNumber:s,behavior:l="smooth",pageCoordinates:c,alignX:d,alignY:u}=e;this.startPageChange(o,s,l);const h=null==(n=a.document)?void 0:n.pages[s-1],m=(((null==h?void 0:h.rotation)??0)+a.rotation)%4,g=r.getScrollPositionForPage(s,i.virtualItems,a.scale,m,c);if(g){this.viewport.forDocument(o).scrollTo({...g,behavior:l,alignX:d,alignY:u})}else this.completePageChange(o)}scrollToNextPage(e="smooth",t){const n=t??this.getActiveDocumentId(),o=this.getDocumentStateOrThrow(n),i=this.getStrategy(n),r=this.getCoreDocumentOrThrow(n),a=o.virtualItems.findIndex(e=>e.pageNumbers.includes(o.currentPage));if(a>=0&&ae.pageNumbers.includes(o.currentPage));if(a>0){const t=o.virtualItems[a-1].pageNumbers[0];this.startPageChange(n,t,e);const s=i.getScrollPositionForPage(t,o.virtualItems,r.scale,r.rotation);if(s){this.viewport.forDocument(n).scrollTo({...s,behavior:e})}else this.completePageChange(n)}}getMetrics(e,t){const n=t??this.getActiveDocumentId();if(e)return this.computeMetrics(n,e);const o=this.viewport.forDocument(n);return this.computeMetrics(n,o.getMetrics())}getLayout(e){const t=this.getDocumentStateOrThrow(e);return{virtualItems:t.virtualItems,totalContentSize:t.totalContentSize}}getRectPositionForPage(e,t,n,o,i){var r;const a=i??this.getActiveDocumentId(),s=this.getDocumentStateOrThrow(a),l=this.getStrategy(a),c=this.getCoreDocumentOrThrow(a);let d=o;if(void 0===d){const t=null==(r=c.document)?void 0:r.pages[e];d=(((null==t?void 0:t.rotation)??0)+c.rotation)%4}return l.getRectPositionForPage(e+1,s.virtualItems,n??c.scale,d,t)}setScrollStrategyForDocument(e,t){const n=t??this.getActiveDocumentId(),o=this.getDocumentState(n);if(!o||o.strategy===e)return;const i=this.createStrategy(e);this.strategies.set(n,i),this.dispatch(function(e,t){return{type:Ci,payload:{documentId:e,strategy:t}}}(n,e)),this.refreshDocumentLayout(n)}onStoreUpdated(e,t){for(const n in t.documents){const o=e.documents[n],i=t.documents[n];o!==i&&(this.state$.emit(i),(null==o?void 0:o.pageChangeState)!==i.pageChangeState&&this.pageChangeState$.emit({documentId:n,state:i.pageChangeState}),this.pushScrollerLayout(n))}}async initialize(){this.logger.info("ScrollPlugin","Initialize","Scroll plugin initialized")}async destroy(){this.strategies.clear(),this.layoutReady.clear(),this.initialLayoutFired.clear(),this.elevatedPages.clear();for(const e of this.scrollerLayoutEmitters.values())e.clear();this.scrollerLayoutEmitters.clear(),this.pageChange$.clear(),this.scroll$.clear(),this.layoutChange$.clear(),this.pageChangeState$.clear(),this.layoutReady$.clear(),this.state$.clear(),super.destroy()}};Si.id="scroll";let Ai=Si;const Mi="scroll",Pi={manifest:{id:Mi,name:"Scroll Plugin",version:"1.0.0",provides:["scroll"],requires:["viewport"],optional:["spread","interaction-manager"],defaultConfig:{defaultPageGap:10,defaultBufferSize:4,defaultStrategy:pi.Vertical}},create:(e,t)=>new Ai(Mi,e,t),reducer:(e,t)=>{switch(t.type){case bi:{const{documentId:n,state:o}=t.payload;return{...e,documents:{...e.documents,[n]:o}}}case wi:{const{[t.payload]:n,...o}=e.documents;return{...e,documents:o}}case xi:{const{documentId:n,state:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,...o}}}:e}case Ci:{const{documentId:n,strategy:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,strategy:o}}}:e}default:return e}},initialState:(e,t)=>((e,t)=>({defaultStrategy:t.defaultStrategy??pi.Vertical,defaultPageGap:t.defaultPageGap??10,defaultBufferSize:t.defaultBufferSize??2,documents:{}}))(0,t)},Di=()=>Oo(Ai.id),Ri=e=>{const{provides:t}=Di(),[n,o]=Se(1),[i,r]=Se(1);return Me(()=>{if(!t||!e)return;const n=t.forDocument(e);return o(n.getCurrentPage()),r(n.getTotalPages()),t.onPageChange(t=>{t.documentId===e&&(o(t.pageNumber),r(t.totalPages))})},[t,e]),{provides:(null==t?void 0:t.forDocument(e))??null,state:{currentPage:n,totalPages:i}}};function zi({documentId:e,renderPage:t,...n}){const{plugin:o}=Lo(Ai.id),[i,r]=Se({layout:null,docId:null});Me(()=>{if(!o||!e)return;const t=o.onScrollerData(e,t=>{r({layout:t,docId:e})});return()=>{t(),r({layout:null,docId:null}),o.clearLayoutReady(e)}},[o,e]);const a=i.docId===e?i.layout:null;return Pe(()=>{o&&e&&a&&o.setLayoutReady(e)},[o,e,a]),a?He("div",{...n,style:{width:`${a.totalWidth}px`,height:`${a.totalHeight}px`,position:"relative",boxSizing:"border-box",margin:"0 auto",...a.strategy===pi.Horizontal&&{display:"flex",flexDirection:"row"}},children:[He("div",{style:{...a.strategy===pi.Horizontal?{width:a.startSpacing,height:"100%",flexShrink:0}:{height:a.startSpacing,width:"100%"}}}),He("div",{style:{gap:a.pageGap,display:"flex",alignItems:"center",position:"relative",boxSizing:"border-box",...a.strategy===pi.Horizontal?{flexDirection:"row",minHeight:"100%"}:{flexDirection:"column",minWidth:"fit-content"}},children:a.items.map(e=>He("div",{style:{display:"flex",justifyContent:"center",gap:a.pageGap},children:e.pageLayouts.map(e=>He("div",{style:{width:`${e.rotatedWidth}px`,height:`${e.rotatedHeight}px`,position:"relative",zIndex:e.elevated?1:void 0},children:t({...e})},e.pageNumber))},e.pageNumbers[0]))}),He("div",{style:{...a.strategy===pi.Horizontal?{width:a.endSpacing,height:"100%",flexShrink:0}:{height:a.endSpacing,width:"100%"}}})]}):null}var Ti=(e=>(e.None="none",e.Odd="odd",e.Even="even",e))(Ti||{});const Ei="SPREAD/INIT_STATE",_i="SPREAD/CLEANUP_STATE",Ni="SPREAD/SET_SPREAD_MODE",Li="SPREAD/SET_PAGE_GROUPING";function Oi(e,t){return{type:Li,payload:{documentId:e,grouping:t}}}const $i=class extends bo{constructor(e,t,n){var o;super(e,t),this.spreadEmitter$=Do(),this.defaultSpreadMode=n.defaultSpreadMode??Ti.None,this.viewport=(null==(o=t.getPlugin("viewport"))?void 0:o.provides())??null}onDocumentLoadingStarted(e){var t;const n={spreadMode:this.defaultSpreadMode};this.dispatch(function(e,t){return{type:Ei,payload:{documentId:e,state:t}}}(e,n)),null==(t=this.viewport)||t.gate("spread",e),this.logger.debug("SpreadPlugin","DocumentOpened",`Initialized spread state for document: ${e}`)}onDocumentLoaded(e){var t;const n=this.coreState.core.documents[e];if(null==n?void 0:n.document){const t=this.calculatePageGrouping(e,n.document.pages.length);this.dispatch(Oi(e,t))}null==(t=this.viewport)||t.releaseGate("spread",e)}onDocumentClosed(e){this.dispatch(function(e){return{type:_i,payload:e}}(e)),this.logger.debug("SpreadPlugin","DocumentClosed",`Cleaned up spread state for document: ${e}`)}buildCapability(){return{setSpreadMode:e=>this.setSpreadModeForDocument(e),getSpreadMode:()=>this.getSpreadModeForDocument(),getSpreadPages:()=>this.getSpreadPages(),forDocument:e=>this.createSpreadScope(e),onSpreadChange:this.spreadEmitter$.on}}createSpreadScope(e){return{setSpreadMode:t=>this.setSpreadModeForDocument(t,e),getSpreadMode:()=>this.getSpreadModeForDocument(e),getSpreadPages:()=>this.getSpreadPages(e),onSpreadChange:t=>this.spreadEmitter$.on(n=>{n.documentId===e&&t(n.spreadMode)})}}getDocumentState(e){const t=e??this.getActiveDocumentId();return this.state.documents[t]??null}getDocumentStateOrThrow(e){const t=this.getDocumentState(e);if(!t)throw new Error(`Spread state not found for document: ${e??"active"}`);return t}setSpreadModeForDocument(e,t){const n=t??this.getActiveDocumentId(),o=this.getDocumentStateOrThrow(n),i=this.coreState.core.documents[n];if(!(null==i?void 0:i.document))throw new Error(`Document ${n} not loaded`);if(o.spreadMode!==e){this.dispatch(function(e,t){return{type:Ni,payload:{documentId:e,spreadMode:t}}}(n,e));const t=this.calculatePageGrouping(n,i.document.pages.length);this.dispatch(Oi(n,t)),this.spreadEmitter$.emit({documentId:n,spreadMode:e})}}getSpreadModeForDocument(e){return this.getDocumentStateOrThrow(e).spreadMode}calculatePageGrouping(e,t){switch(this.getDocumentStateOrThrow(e).spreadMode){case Ti.None:return Array.from({length:t},(e,t)=>[t]);case Ti.Odd:return Array.from({length:Math.ceil(t/2)},(e,n)=>{const o=[2*n];return 2*n+1{const o=[1+2*n];return 1+2*n+1[t])}}getSpreadPages(e){const t=e??this.getActiveDocumentId(),n=this.coreState.core.documents[t],o=this.getDocumentStateOrThrow(t);if(!(null==n?void 0:n.document))throw new Error(`Document ${t} not loaded`);const i=o.pageGrouping??[],r=n.document.pages;return i.map(e=>e.map(e=>r[e]).filter(Boolean))}onStoreUpdated(e,t){for(const n in t.documents){const o=e.documents[n],i=t.documents[n];(null==o?void 0:o.spreadMode)!==i.spreadMode&&this.logger.debug("SpreadPlugin","SpreadModeChanged",`Spread mode changed for document ${n}: ${(null==o?void 0:o.spreadMode)??Ti.None} -> ${i.spreadMode}`)}}async initialize(e){this.logger.info("SpreadPlugin","Initialize","Spread plugin initialized")}async destroy(){this.spreadEmitter$.clear(),super.destroy()}};$i.id="spread";let ji=$i;const Fi="spread",Ui={id:Fi,name:"Spread Plugin",version:"1.0.0",provides:["spread"],requires:[],optional:["viewport"],defaultConfig:{}};Ti.None;const Hi={documents:{},activeDocumentId:null},Wi={manifest:Ui,create:(e,t)=>new ji(Fi,e,t),reducer:(e=Hi,t)=>{switch(t.type){case Ei:{const{documentId:n,state:o}=t.payload;return{...e,documents:{...e.documents,[n]:o},activeDocumentId:e.activeDocumentId??n}}case _i:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i,activeDocumentId:e.activeDocumentId===n?null:e.activeDocumentId}}case"SPREAD/SET_ACTIVE_DOCUMENT":return{...e,activeDocumentId:t.payload};case Ni:{const{documentId:n,spreadMode:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,spreadMode:o}}}:e}case Li:{const{documentId:n,grouping:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,pageGrouping:o}}}:e}default:return e}},initialState:Hi},Bi="ui",qi={id:Bi,name:"UI Plugin",version:"1.0.0",provides:["ui"],requires:[],optional:["i18n"],defaultConfig:{schema:{id:"empty",version:"1.0.0",toolbars:{},menus:{},sidebars:{},modals:{},selectionMenus:{}}}},Gi="UI/INIT_STATE",Vi="UI/CLEANUP_STATE",Ki="UI/SET_ACTIVE_TOOLBAR",Zi="UI/CLOSE_TOOLBAR_SLOT",Yi="UI/SET_ACTIVE_SIDEBAR",Xi="UI/CLOSE_SIDEBAR_SLOT",Qi="UI/SET_SIDEBAR_TAB",Ji="UI/OPEN_MODAL",er="UI/CLOSE_MODAL",tr="UI/CLEAR_MODAL",nr="UI/OPEN_MENU",or="UI/CLOSE_MENU",ir="UI/CLOSE_ALL_MENUS",rr="UI/SET_OVERLAY_ENABLED",ar="UI/SET_DISABLED_CATEGORIES",sr="UI/SET_HIDDEN_ITEMS",lr=(e,t,n,o,i)=>({type:Yi,payload:{documentId:e,placement:t,slot:n,sidebarId:o,activeTab:i}}),cr=(e,t,n)=>({type:Xi,payload:{documentId:e,placement:t,slot:n}}),dr=(e,t)=>({type:nr,payload:{documentId:e,menuState:t}}),ur=(e,t)=>({type:or,payload:{documentId:e,menuId:t}}),hr=(e,t,n)=>({type:rr,payload:{documentId:e,overlayId:t,enabled:n}}),mr=e=>({type:ar,payload:{categories:e}}),gr=e=>({type:sr,payload:{hiddenItems:e}});function pr(e,t){if(!t)return e;const n={...e};for(const[e,o]of Object.entries(t))n[e]?n[e]={...n[e],...o,items:o.items??n[e].items,responsive:o.responsive??n[e].responsive}:n[e]=o;return n}function fr(e,t){if(!t)return e;const n={...e};for(const[e,o]of Object.entries(t))n[e]?n[e]={...n[e],...o,items:o.items??n[e].items}:n[e]=o;return n}function vr(e,t){if(!t)return e;const n={...e};for(const[e,o]of Object.entries(t))n[e]?n[e]={...n[e],...o,content:o.content??n[e].content}:n[e]=o;return n}function yr(e,t){var n;if(!(null==(n=e.responsive)?void 0:n.breakpoints))return null;const o=function(e,t,n){if(!n||!(null==t?void 0:t.groups))return e;const o=t.groups.find(e=>e.locales.includes(n));if(!o)return e;const i={};for(const[t,n]of Object.entries(e)){const e=o.breakpoints[t];e?i[t]={minWidth:n.minWidth,maxWidth:n.maxWidth,hide:e.replaceHide?e.replaceHide:[...n.hide||[],...e.hide||[]],show:e.replaceShow?e.replaceShow:[...n.show||[],...e.show||[]]}:i[t]=n}return i}(e.responsive.breakpoints,e.responsive.localeOverrides,t),i=new Map,r=new Map;for(const[e,t]of Object.entries(o))r.set(e,{minWidth:t.minWidth,maxWidth:t.maxWidth});const a=new Set,s=e=>{e.forEach(e=>{a.add(e.id),"group"===e.type&&e.items&&s(e.items),"tab-group"===e.type&&e.tabs&&s(e.tabs),"section"===e.type&&e.items&&s(e.items)})};s(e.items);for(const e of a){const t=[];let n=!0;const r=Array.from(Object.entries(o)).sort((e,t)=>(e[1].minWidth??0)-(t[1].minWidth??0));r.forEach(([o,i],r)=>{var a,s;const l=null==(a=i.hide)?void 0:a.includes(e),c=null==(s=i.show)?void 0:s.includes(e);(l||c)&&(t.push({breakpointId:o,minWidth:i.minWidth,maxWidth:i.maxWidth,visible:c||!l,priority:r}),0===r&&(n=c||!l))}),t.length>0&&i.set(e,{itemId:e,shouldRender:!0,visibilityRules:t,defaultVisible:n})}return{items:i,breakpoints:r}}const br="data-epdf",wr="data-epdf-s",xr="data-epdf-i",Cr="data-epdf-cat",kr="data-epdf-dis",Ir="data-epdf-hid",Sr={ROOT:`[${br}]`,STYLES:`[${wr}]`,ITEM:e=>`[${xr}="${e}"]`,CATEGORIES:e=>`[${Cr}~="${e}"]`,DISABLED_CATEGORY:e=>`[${kr}~="${e}"]`,HIDDEN_ITEM:e=>`[${Ir}~="${e}"]`},Ar={useContainerQueries:!0};function Mr(e,t={}){const n={...Ar,...t.config},o=t.locale,i=Dr(e,o),r=[];r.push(function(e){const t=e?` (locale: ${e})`:"";return`/* ═══════════════════════════════════════════════════════════════════════════ */\n/* EmbedPDF UI Stylesheet - Auto-generated${t} */\n/* DO NOT EDIT MANUALLY - This file is generated from your UI schema */\n/* ═══════════════════════════════════════════════════════════════════════════ */`}(o));const a=function(e,t){const n=[],o=t.useContainerQueries?"@container":"@media",i=new Set;return e.responsiveItems.forEach((e,t)=>{if(i.has(t))return;i.add(t);const r=function(e,t,n){if(0===t.visibilityRules.length)return null;const o=[],i=Sr.ITEM(e);t.defaultVisible||o.push(`${i} { display: none; }`);for(const e of t.visibilityRules){const t=[];if(void 0!==e.minWidth&&t.push(`(min-width: ${e.minWidth}px)`),void 0!==e.maxWidth&&t.push(`(max-width: ${e.maxWidth}px)`),t.length>0){const r=e.visible?"flex":"none";o.push(`${n} ${t.join(" and ")} {\n ${i} { display: ${r}; }\n}`)}}return o.length>0?o.join("\n"):null}(t,e,o);r&&n.push(r)}),0===n.length?"":`/* ─── Responsive Visibility Rules ─── */\n/* Items show/hide based on container width */\n\n${n.join("\n\n")}`}(i,n);a&&r.push(a);const s=function(e){if(0===e.categories.size)return"";const t=[],n=Array.from(e.categories).sort();for(const e of n)t.push(`${Sr.ROOT}[${kr}~="${e}"] [${Cr}~="${e}"] {\n display: none !important;\n}`);return`/* ─── Category Visibility Rules ─── */\n/* Items hide when ANY of their categories is disabled */\n/* Use: data-disabled-categories="category1 category2" on root element */\n\n${t.join("\n\n")}`}(i);s&&r.push(s);const l=function(e,t){if(0===e.dependencies.length)return"";const n=[],o=t.useContainerQueries?"@container":"@media";for(const t of e.dependencies){const i=Ur(t,e,o);i.length>0&&n.push(...i)}return 0===n.length?"":`/* ─── Dependency Visibility Rules ─── */\n/* Container elements hide when all their dependencies are hidden */\n\n${n.join("\n\n")}`}(i,n);return l&&r.push(l),r.filter(e=>e.trim()).join("\n\n")}function Pr(e,t){const n=new Set(t),o=[];return e.forEach((e,t)=>{e.some(e=>n.has(e))&&o.push(t)}),o}function Dr(e,t){const n=new Set,o=new Map,i=[],r=new Map,a=new Map;for(const[s,l]of Object.entries(e.menus))Rr(s,l,n,o,i,r,a,t);for(const[r,s]of Object.entries(e.toolbars))_r(r,s,n,o,i,a,t);for(const[t,r]of Object.entries(e.sidebars))Or(t,r,n,o,i);for(const[r,s]of Object.entries(e.selectionMenus||{}))$r(r,s,n,o,i,a,t);return{categories:n,itemCategories:o,dependencies:i,menuBreakpoints:r,responsiveItems:a}}function Rr(e,t,n,o,i,r,a,s){Fr(e,t.categories,t.visibilityDependsOn,n,o,i),zr(t.items,n,o,i);const l=yr(t,s);l&&l.items.forEach((e,t)=>{a.set(t,e)});const c=function(e,t,n){var o;const i=[],r=yr(e,n);if((null==(o=e.responsive)?void 0:o.breakpoints)&&r){const e=Array.from(r.breakpoints.entries()).sort((e,t)=>(e[1].minWidth??0)-(t[1].minWidth??0));for(const[n,o]of e){const e=Er(r,o),n=new Set;for(const o of e){const e=t.get(o);e&&e.forEach(e=>n.add(e))}i.push({minWidth:o.minWidth,maxWidth:o.maxWidth,visibleItemIds:e,visibleCategories:n})}}else{const n=[],o=new Set;Tr(e.items,t,n,o),i.push({visibleItemIds:n,visibleCategories:o})}return i}(t,o,s);r.set(e,c)}function zr(e,t,n,o){for(const i of e)Fr(i.id,i.categories,i.visibilityDependsOn,t,n,o),"section"===i.type&&zr(i.items,t,n,o)}function Tr(e,t,n,o){for(const i of e){n.push(i.id);const e=t.get(i.id);e&&e.forEach(e=>o.add(e)),"section"===i.type&&Tr(i.items,t,n,o)}}function Er(e,t){const n=[];return e.items.forEach((e,o)=>{let i=e.defaultVisible;for(const n of e.visibilityRules){(void 0===n.minWidth||void 0!==t.minWidth&&t.minWidth>=n.minWidth)&&(void 0===n.maxWidth||void 0!==t.maxWidth&&t.maxWidth<=n.maxWidth)&&(i=n.visible)}i&&n.push(o)}),n}function _r(e,t,n,o,i,r,a){Fr(e,t.categories,t.visibilityDependsOn,n,o,i);const s=yr(t,a);s&&s.items.forEach((e,t)=>{r.set(t,e)}),Nr(t.items,n,o,i)}function Nr(e,t,n,o){for(const i of e)Fr(i.id,i.categories,i.visibilityDependsOn,t,n,o),"group"===i.type&&i.items&&Nr(i.items,t,n,o),"tab-group"===i.type&&i.tabs&&Lr(i.tabs,t,n,o)}function Lr(e,t,n,o){for(const i of e)Fr(i.id,i.categories,i.visibilityDependsOn,t,n,o)}function Or(e,t,n,o,i){if(Fr(e,t.categories,t.visibilityDependsOn,n,o,i),"tabs"===t.content.type)for(const e of t.content.tabs)Fr(e.id,e.categories,e.visibilityDependsOn,n,o,i)}function $r(e,t,n,o,i,r,a){if(Fr(e,t.categories,t.visibilityDependsOn,n,o,i),t.responsive){const e=yr(t,a);e&&e.items.forEach((e,t)=>{r.set(t,e)})}jr(t.items,n,o,i)}function jr(e,t,n,o){for(const i of e)Fr(i.id,i.categories,i.visibilityDependsOn,t,n,o),"group"===i.type&&i.items&&jr(i.items,t,n,o)}function Fr(e,t,n,o,i,r){var a;(null==t?void 0:t.length)&&(t.forEach(e=>o.add(e)),i.set(e,t)),n&&(n.menuId||(null==(a=n.itemIds)?void 0:a.length))&&r.push({itemId:e,dependsOnMenuId:n.menuId,dependsOnItemIds:n.itemIds})}function Ur(e,t,n,o){var i;const r=[];if(e.dependsOnMenuId){const o=t.menuBreakpoints.get(e.dependsOnMenuId);if(o&&o.length>0){r.push(`/* "${e.itemId}" depends on menu "${e.dependsOnMenuId}" */`);for(const t of o){if(0===t.visibleItemIds.length)continue;const o=t.visibleItemIds.sort().map(e=>Sr.HIDDEN_ITEM(e)).join(""),i=`${Sr.ROOT}${o} ${Sr.ITEM(e.itemId)} {\n display: none !important;\n}`,a=[];void 0!==t.minWidth&&a.push(`(min-width: ${t.minWidth}px)`),void 0!==t.maxWidth&&a.push(`(max-width: ${t.maxWidth}px)`),a.length>0?r.push(`${n} ${a.join(" and ")} {\n ${i}\n}`):r.push(i)}}}if(null==(i=e.dependsOnItemIds)?void 0:i.length){r.push(`/* "${e.itemId}" depends on items: ${e.dependsOnItemIds.join(", ")} */`);const t=e.dependsOnItemIds.sort().map(e=>Sr.HIDDEN_ITEM(e)).join("");r.push(`${Sr.ROOT}${t} ${Sr.ITEM(e.itemId)} {\n display: none !important;\n}`)}return r}function Hr(e,t){var n;return{[xr]:e.id,[Cr]:(null==(n=e.categories)?void 0:n.join(" "))||void 0,...t}}const Wr=class extends bo{constructor(e,t,n){var o,i;if(super(e,t),this.cachedStylesheet=null,this.cachedLocale=null,this.i18n=null,this.i18nCleanup=null,this.categoryChanged$=Do(),this.stylesheetInvalidated$=Po(),this.toolbarChanged$=Ro((e,t)=>({documentId:e,...t}),{cache:!1}),this.sidebarChanged$=Ro((e,t)=>({documentId:e,...t}),{cache:!1}),this.modalChanged$=Ro((e,t)=>({documentId:e,...t}),{cache:!1}),this.menuChanged$=Ro((e,t)=>({documentId:e,...t}),{cache:!1}),this.overlayChanged$=Ro((e,t)=>({documentId:e,...t}),{cache:!1}),this.schema=n.schema,this.stylesheetConfig=n.stylesheetConfig||{},this.itemCategories=Dr(this.schema).itemCategories,null==(o=n.disabledCategories)?void 0:o.length){this.dispatch(mr(n.disabledCategories));const e=Pr(this.itemCategories,n.disabledCategories);this.dispatch(gr(e))}this.i18n=(null==(i=t.getPlugin("i18n"))?void 0:i.provides())??null,this.i18n&&(this.i18nCleanup=this.i18n.onLocaleChange(({currentLocale:e})=>{this.handleLocaleChange(e)}),this.cachedLocale=this.i18n.getLocale())}async initialize(){this.logger.info("UIPlugin","Initialize","UI plugin initialized")}async destroy(){this.i18nCleanup&&(this.i18nCleanup(),this.i18nCleanup=null),this.toolbarChanged$.clear(),this.sidebarChanged$.clear(),this.modalChanged$.clear(),this.menuChanged$.clear(),this.overlayChanged$.clear(),this.stylesheetInvalidated$.clear(),super.destroy()}onDocumentLoadingStarted(e){this.dispatch(((e,t)=>({type:Gi,payload:{documentId:e,schema:t}}))(e,this.schema))}onDocumentClosed(e){this.dispatch((e=>({type:Vi,payload:{documentId:e}}))(e)),this.toolbarChanged$.clearScope(e),this.sidebarChanged$.clearScope(e),this.modalChanged$.clearScope(e),this.menuChanged$.clearScope(e),this.overlayChanged$.clearScope(e)}handleLocaleChange(e){this.cachedLocale!==e&&(this.logger.debug("UIPlugin","LocaleChange",`Locale changed: ${this.cachedLocale} -> ${e}`),this.cachedLocale=e,this.invalidateStylesheet(),this.stylesheetInvalidated$.emit())}getStylesheet(){var e;const t=(null==(e=this.i18n)?void 0:e.getLocale())??null;return this.cachedStylesheet&&this.cachedLocale===t||(this.cachedStylesheet=Mr(this.schema,{config:this.stylesheetConfig,locale:t??void 0}),this.cachedLocale=t),this.cachedStylesheet}getLocale(){var e;return(null==(e=this.i18n)?void 0:e.getLocale())??null}invalidateStylesheet(){this.cachedStylesheet=null}onStylesheetInvalidated(e){return this.stylesheetInvalidated$.on(e)}disableCategoryImpl(e){const t=new Set(this.state.disabledCategories);if(!t.has(e)){t.add(e);const n=Array.from(t);this.dispatch(mr(n));const o=Pr(this.itemCategories,n);this.dispatch(gr(o)),this.categoryChanged$.emit({disabledCategories:n,hiddenItems:o})}}enableCategoryImpl(e){const t=new Set(this.state.disabledCategories);if(t.has(e)){t.delete(e);const n=Array.from(t);this.dispatch(mr(n));const o=Pr(this.itemCategories,n);this.dispatch(gr(o)),this.categoryChanged$.emit({disabledCategories:n,hiddenItems:o})}}toggleCategoryImpl(e){this.state.disabledCategories.includes(e)?this.enableCategoryImpl(e):this.disableCategoryImpl(e)}setDisabledCategoriesImpl(e){this.dispatch(mr(e));const t=Pr(this.itemCategories,e);this.dispatch(gr(t)),this.categoryChanged$.emit({disabledCategories:e,hiddenItems:t})}buildCapability(){return{setActiveToolbar:(e,t,n,o)=>this.setToolbarForDocument(e,t,n,o),setActiveSidebar:(e,t,n,o,i)=>this.setSidebarForDocument(e,t,n,o,i),toggleSidebar:(e,t,n,o,i)=>this.toggleSidebarForDocument(e,t,n,o,i),openModal:(e,t,n)=>this.openModalForDocument(e,t,n),openMenu:(e,t,n,o)=>this.openMenuForDocument(e,t,n,o),toggleMenu:(e,t,n,o)=>this.toggleMenuForDocument(e,t,n,o),enableOverlay:(e,t)=>this.enableOverlayForDocument(e,t),disableOverlay:(e,t)=>this.disableOverlayForDocument(e,t),toggleOverlay:(e,t)=>this.toggleOverlayForDocument(e,t),forDocument:e=>this.createUIScope(e),getSchema:()=>this.schema,mergeSchema:e=>{var t,n;this.schema=(t=this.schema,n=e,{...t,...n,toolbars:pr(t.toolbars,n.toolbars),menus:fr(t.menus,n.menus),sidebars:vr(t.sidebars,n.sidebars)})},disableCategory:e=>this.disableCategoryImpl(e),enableCategory:e=>this.enableCategoryImpl(e),toggleCategory:e=>this.toggleCategoryImpl(e),setDisabledCategories:e=>this.setDisabledCategoriesImpl(e),getDisabledCategories:()=>this.state.disabledCategories,isCategoryDisabled:e=>this.state.disabledCategories.includes(e),getHiddenItems:()=>this.state.hiddenItems,onToolbarChanged:this.toolbarChanged$.onGlobal,onSidebarChanged:this.sidebarChanged$.onGlobal,onModalChanged:this.modalChanged$.onGlobal,onMenuChanged:this.menuChanged$.onGlobal,onOverlayChanged:this.overlayChanged$.onGlobal,onCategoryChanged:this.categoryChanged$.on}}createUIScope(e){return{setActiveToolbar:(t,n,o)=>this.setToolbarForDocument(t,n,o,e),getActiveToolbar:(t,n)=>this.getToolbarForDocument(t,n,e),closeToolbarSlot:(t,n)=>this.closeToolbarForDocument(t,n,e),isToolbarOpen:(t,n,o)=>this.isToolbarOpenForDocument(t,n,o,e),setActiveSidebar:(t,n,o,i)=>this.setSidebarForDocument(t,n,o,e,i),getActiveSidebar:(t,n)=>this.getSidebarForDocument(t,n,e),closeSidebarSlot:(t,n)=>this.closeSidebarForDocument(t,n,e),toggleSidebar:(t,n,o,i)=>this.toggleSidebarForDocument(t,n,o,e,i),isSidebarOpen:(t,n,o)=>this.isSidebarOpenForDocument(t,n,o,e),setSidebarTab:(t,n)=>this.setSidebarTabForDocument(t,n,e),getSidebarTab:t=>this.getSidebarTabForDocument(t,e),openModal:(t,n)=>this.openModalForDocument(t,n,e),closeModal:()=>this.closeModalForDocument(e),clearModal:()=>this.clearModalForDocument(e),getActiveModal:()=>this.getActiveModalForDocument(e),isModalOpen:()=>this.isModalOpenForDocument(e),openMenu:(t,n,o)=>this.openMenuForDocument(t,n,o,e),closeMenu:t=>this.closeMenuForDocument(t,e),toggleMenu:(t,n,o)=>this.toggleMenuForDocument(t,n,o,e),closeAllMenus:()=>this.closeAllMenusForDocument(e),isMenuOpen:t=>this.isMenuOpenForDocument(t,e),getOpenMenus:()=>this.getOpenMenusForDocument(e),enableOverlay:t=>this.enableOverlayForDocument(t,e),disableOverlay:t=>this.disableOverlayForDocument(t,e),toggleOverlay:t=>this.toggleOverlayForDocument(t,e),isOverlayEnabled:t=>this.isOverlayEnabledForDocument(t,e),getEnabledOverlays:()=>this.getEnabledOverlaysForDocument(e),getSchema:()=>this.schema,getState:()=>this.getDocumentStateOrThrow(e),onToolbarChanged:this.toolbarChanged$.forScope(e),onSidebarChanged:this.sidebarChanged$.forScope(e),onModalChanged:this.modalChanged$.forScope(e),onMenuChanged:this.menuChanged$.forScope(e),onOverlayChanged:this.overlayChanged$.forScope(e)}}getDocumentState(e){const t=e??this.getActiveDocumentId();return this.state.documents[t]??null}getDocumentStateOrThrow(e){const t=this.getDocumentState(e);if(!t)throw new Error(`UI state not found for document: ${e??"active"}`);return t}setToolbarForDocument(e,t,n,o){const i=o??this.getActiveDocumentId();this.dispatch(((e,t,n,o)=>({type:Ki,payload:{documentId:e,placement:t,slot:n,toolbarId:o}}))(i,e,t,n)),this.toolbarChanged$.emit(i,{placement:e,slot:t,toolbarId:n})}getToolbarForDocument(e,t,n){const o=`${e}-${t}`,i=this.getDocumentStateOrThrow(n).activeToolbars[o];return(null==i?void 0:i.isOpen)?i.toolbarId:null}closeToolbarForDocument(e,t,n){const o=n??this.getActiveDocumentId();this.dispatch(((e,t,n)=>({type:Zi,payload:{documentId:e,placement:t,slot:n}}))(o,e,t)),this.toolbarChanged$.emit(o,{placement:e,slot:t,toolbarId:""})}isToolbarOpenForDocument(e,t,n,o){const i=`${e}-${t}`,r=this.getDocumentStateOrThrow(o).activeToolbars[i];return!(!r||!r.isOpen)&&(!n||r.toolbarId===n)}setSidebarForDocument(e,t,n,o,i){const r=o??this.getActiveDocumentId();this.dispatch(lr(r,e,t,n,i)),this.sidebarChanged$.emit(r,{placement:e,slot:t,sidebarId:n})}getSidebarForDocument(e,t,n){const o=`${e}-${t}`,i=this.getDocumentStateOrThrow(n).activeSidebars[o];return(null==i?void 0:i.isOpen)?i.sidebarId:null}closeSidebarForDocument(e,t,n){const o=n??this.getActiveDocumentId();this.dispatch(cr(o,e,t)),this.sidebarChanged$.emit(o,{placement:e,slot:t,sidebarId:""})}toggleSidebarForDocument(e,t,n,o,i){const r=o??this.getActiveDocumentId(),a=`${e}-${t}`,s=this.getDocumentStateOrThrow(r).activeSidebars[a];(null==s?void 0:s.sidebarId)===n&&(null==s?void 0:s.isOpen)?(this.dispatch(cr(r,e,t)),this.sidebarChanged$.emit(r,{placement:e,slot:t,sidebarId:""})):(this.dispatch(lr(r,e,t,n,i)),this.sidebarChanged$.emit(r,{placement:e,slot:t,sidebarId:n}))}isSidebarOpenForDocument(e,t,n,o){const i=`${e}-${t}`,r=this.getDocumentStateOrThrow(o).activeSidebars[i];return!(!r||!r.isOpen)&&(!n||r.sidebarId===n)}setSidebarTabForDocument(e,t,n){const o=n??this.getActiveDocumentId();this.dispatch(((e,t,n)=>({type:Qi,payload:{documentId:e,sidebarId:t,tabId:n}}))(o,e,t))}getSidebarTabForDocument(e,t){return this.getDocumentStateOrThrow(t).sidebarTabs[e]??null}openModalForDocument(e,t,n){const o=n??this.getActiveDocumentId();this.dispatch(((e,t,n)=>({type:Ji,payload:{documentId:e,modalId:t,props:n}}))(o,e,t)),this.modalChanged$.emit(o,{modalId:e,isOpen:!0})}closeModalForDocument(e){const t=e??this.getActiveDocumentId(),n=this.getDocumentStateOrThrow(t).activeModal;this.dispatch((e=>({type:er,payload:{documentId:e}}))(t)),this.modalChanged$.emit(t,{modalId:(null==n?void 0:n.modalId)??null,isOpen:!1})}clearModalForDocument(e){const t=e??this.getActiveDocumentId();this.dispatch((e=>({type:tr,payload:{documentId:e}}))(t))}getActiveModalForDocument(e){return this.getDocumentStateOrThrow(e).activeModal}isModalOpenForDocument(e){const t=this.getDocumentStateOrThrow(e).activeModal;return(null==t?void 0:t.isOpen)??!1}openMenuForDocument(e,t,n,o){const i=o??this.getActiveDocumentId();this.dispatch(dr(i,{menuId:e,triggeredByCommandId:t,triggeredByItemId:n})),this.menuChanged$.emit(i,{menuId:e,isOpen:!0})}closeMenuForDocument(e,t){const n=t??this.getActiveDocumentId();this.dispatch(ur(n,e)),this.menuChanged$.emit(n,{menuId:e,isOpen:!1})}toggleMenuForDocument(e,t,n,o){const i=o??this.getActiveDocumentId();!!this.getDocumentStateOrThrow(i).openMenus[e]?(this.dispatch(ur(i,e)),this.menuChanged$.emit(i,{menuId:e,isOpen:!1})):(this.dispatch(dr(i,{menuId:e,triggeredByCommandId:t,triggeredByItemId:n})),this.menuChanged$.emit(i,{menuId:e,isOpen:!0}))}closeAllMenusForDocument(e){const t=e??this.getActiveDocumentId();this.dispatch((e=>({type:ir,payload:{documentId:e}}))(t))}isMenuOpenForDocument(e,t){return!!this.getDocumentStateOrThrow(t).openMenus[e]}getOpenMenusForDocument(e){return Object.values(this.getDocumentStateOrThrow(e).openMenus)}enableOverlayForDocument(e,t){const n=t??this.getActiveDocumentId();this.dispatch(hr(n,e,!0)),this.overlayChanged$.emit(n,{overlayId:e,isEnabled:!0})}disableOverlayForDocument(e,t){const n=t??this.getActiveDocumentId();this.dispatch(hr(n,e,!1)),this.overlayChanged$.emit(n,{overlayId:e,isEnabled:!1})}toggleOverlayForDocument(e,t){const n=t??this.getActiveDocumentId();this.isOverlayEnabledForDocument(e,n)?this.disableOverlayForDocument(e,n):this.enableOverlayForDocument(e,n)}isOverlayEnabledForDocument(e,t){return this.getDocumentStateOrThrow(t).enabledOverlays[e]??!0}getEnabledOverlaysForDocument(e){const t=this.getDocumentStateOrThrow(e).enabledOverlays;return Object.entries(t).filter(([,e])=>e).map(([e])=>e)}};Wr.id="ui";let Br=Wr;const qr={activeToolbars:{},activeSidebars:{},activeModal:null,openMenus:{},sidebarTabs:{},enabledOverlays:{}},Gr={documents:{},disabledCategories:[],hiddenItems:[]};function Vr(e,t){const n=function(e){return e.ui??null}(e);return(null==n?void 0:n.documents[t])??null}function Kr(e,t){return`${e}-${t}`}function Zr(e,t,n,o,i){const r=function(e,t,n,o){const i=Vr(e,t);return i?i.activeToolbars[Kr(n,o)]??null:null}(e,t,n,o);return!(!r||!r.isOpen)&&(!i||r.toolbarId===i)}function Yr(e,t,n,o,i){const r=function(e,t,n,o){const i=Vr(e,t);return i?i.activeSidebars[Kr(n,o)]??null:null}(e,t,n,o);return!(!r||!r.isOpen)&&(!i||r.sidebarId===i)}const Xr={manifest:qi,create:(e,t)=>new Br(Bi,e,t),reducer:(e=Gr,t)=>{var n;switch(t.type){case Gi:{const{documentId:n,schema:o}=t.payload,i={};Object.values(o.toolbars).forEach(e=>{if(e.permanent&&e.position){const t=`${e.position.placement}-${e.position.slot}`;i[t]={toolbarId:e.id,isOpen:!0}}});const r={};return o.overlays&&Object.values(o.overlays).forEach(e=>{r[e.id]=e.defaultEnabled??!0}),{...e,documents:{...e.documents,[n]:{...qr,activeToolbars:i,enabledOverlays:r}}}}case Vi:{const{documentId:n}=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i}}case Ki:{const{documentId:n,placement:o,slot:i,toolbarId:r}=t.payload,a=e.documents[n]||qr,s=`${o}-${i}`;return{...e,documents:{...e.documents,[n]:{...a,activeToolbars:{...a.activeToolbars,[s]:{toolbarId:r,isOpen:!0}}}}}}case Zi:{const{documentId:n,placement:o,slot:i}=t.payload,r=e.documents[n];if(!r)return e;const a=`${o}-${i}`,s=r.activeToolbars[a];return s?{...e,documents:{...e.documents,[n]:{...r,activeToolbars:{...r.activeToolbars,[a]:{...s,isOpen:!1}}}}}:e}case Yi:{const{documentId:n,placement:o,slot:i,sidebarId:r,activeTab:a}=t.payload,s=e.documents[n]||qr,l=`${o}-${i}`;return{...e,documents:{...e.documents,[n]:{...s,activeSidebars:{...s.activeSidebars,[l]:{sidebarId:r,isOpen:!0}},...a&&{sidebarTabs:{...s.sidebarTabs,[r]:a}}}}}}case Xi:{const{documentId:n,placement:o,slot:i}=t.payload,r=e.documents[n];if(!r)return e;const a=`${o}-${i}`,s=r.activeSidebars[a];return s?{...e,documents:{...e.documents,[n]:{...r,activeSidebars:{...r.activeSidebars,[a]:{...s,isOpen:!1}}}}}:e}case Qi:{const{documentId:n,sidebarId:o,tabId:i}=t.payload,r=e.documents[n]||qr;return{...e,documents:{...e.documents,[n]:{...r,sidebarTabs:{...r.sidebarTabs,[o]:i}}}}}case Ji:{const{documentId:n,modalId:o,props:i}=t.payload,r=e.documents[n]||qr;return{...e,documents:{...e.documents,[n]:{...r,activeModal:{modalId:o,isOpen:!0,props:i},openMenus:{}}}}}case er:{const{documentId:n}=t.payload,o=e.documents[n];return(null==o?void 0:o.activeModal)?{...e,documents:{...e.documents,[n]:{...o,activeModal:{...o.activeModal,isOpen:!1}}}}:e}case tr:{const{documentId:o}=t.payload,i=e.documents[o];return i?(null==(n=i.activeModal)?void 0:n.isOpen)?e:{...e,documents:{...e.documents,[o]:{...i,activeModal:null}}}:e}case nr:{const{documentId:n,menuState:o}=t.payload,i=e.documents[n]||qr;return{...e,documents:{...e.documents,[n]:{...i,openMenus:{[o.menuId]:o}}}}}case or:{const{documentId:n,menuId:o}=t.payload,i=e.documents[n];if(!i)return e;const{[o]:r,...a}=i.openMenus;return{...e,documents:{...e.documents,[n]:{...i,openMenus:a}}}}case ir:{const{documentId:n}=t.payload,o=e.documents[n];return o?{...e,documents:{...e.documents,[n]:{...o,openMenus:{}}}}:e}case rr:{const{documentId:n,overlayId:o,enabled:i}=t.payload,r=e.documents[n]||qr;return{...e,documents:{...e.documents,[n]:{...r,enabledOverlays:{...r.enabledOverlays,[o]:i}}}}}case ar:return{...e,disabledCategories:t.payload.categories};case sr:return{...e,hiddenItems:t.payload.hiddenItems};default:return e}},initialState:Gr},Qr=()=>Oo(Br.id),Jr=e=>{const{provides:t}=Qr(),[n,o]=Se(null);return Me(()=>{if(!t)return;const n=t.forDocument(e);o(n.getState());const i=n.onToolbarChanged(()=>o(n.getState())),r=n.onSidebarChanged(()=>o(n.getState())),a=n.onModalChanged(()=>o(n.getState())),s=n.onMenuChanged(()=>o(n.getState())),l=n.onOverlayChanged(()=>o(n.getState()));return()=>{i(),r(),a(),s(),l()}},[t,e]),n},ea=de(null);function ta(){const e=Te(ea);if(!e)throw new Error("useUIContainer must be used within a UIProvider");return e}const na=de(null);function oa({children:e}){const t=De(new Map),n={register:ze((e,n,o)=>{const i=`${e}:${n}`;t.current.set(i,o)},[]),unregister:ze((e,n)=>{const o=`${e}:${n}`;t.current.delete(o)},[]),getAnchor:ze((e,n)=>{const o=`${e}:${n}`;return t.current.get(o)||null},[])};return He(na.Provider,{value:n,children:e})}function ia(){const e=Te(na);if(!e)throw new Error("useAnchorRegistry must be used within UIProvider");return e}function ra(e,t){const n=ia(),o=De(null),i=De(e),r=De(t);return i.current=e,r.current=t,ze(e=>{const t=o.current;o.current=e,e?e!==t&&n.register(i.current,r.current,e):t&&n.unregister(i.current,r.current)},[n])}const aa=de(null);function sa({children:e,initialComponents:t={}}){const n=De(new Map(Object.entries(t))),o={register:ze((e,t)=>{n.current.set(e,t)},[]),unregister:ze(e=>{n.current.delete(e)},[]),get:ze(e=>n.current.get(e),[]),has:ze(e=>n.current.has(e),[]),getRegisteredIds:ze(()=>Array.from(n.current.keys()),[])};return He(aa.Provider,{value:o,children:e})}function la(){const e=function(){const e=Te(aa);if(!e)throw new Error("useComponentRegistry must be used within UIProvider");return e}();return{renderCustomComponent:(t,n,o)=>{const i=e.get(t);return i?He(i,{documentId:n,...o||{}}):(console.error(`Component "${t}" not found in registry`),null)}}}const ca=de(null);function da({children:e,renderers:t}){return He(ca.Provider,{value:t,children:e})}function ua(){const e=Te(ca);if(!e)throw new Error("useRenderers must be used within UIProvider");return e}function ha(e,t){var n;const{provides:o}=Qr(),i=ua(),r=ze(n=>{var r;const a=null==o?void 0:o.getSchema(),s=null==(r=null==a?void 0:a.selectionMenus)?void 0:r[e];if(!s)return null;if(!n.selected)return null;return He(i.selectionMenu,{schema:s,documentId:t,props:n})},[o,i,e,t]),a=null==o?void 0:o.getSchema();if(null==(n=null==a?void 0:a.selectionMenus)?void 0:n[e])return r}function ma({container:e,documentId:t}){const n=Jr(t),{provides:o}=Qr(),i=ia(),r=ua(),[a,s]=Se(null),l=(null==n?void 0:n.openMenus)||{},c=null==o?void 0:o.getSchema();Me(()=>{const e=Object.keys(l);if(e.length>0){const n=e[0];if(!n)return void s(null);const o=l[n];if(o&&o.triggeredByItemId){const e=i.getAnchor(t,o.triggeredByItemId);s({menuId:n,anchorEl:e})}else s(null)}else s(null)},[l,i,t]);if(!a||!c)return null;const d=c.menus[a.menuId];if(!d)return console.warn(`Menu "${a.menuId}" not found in schema`),null;return He(r.menu,{schema:d,documentId:t,anchorEl:a.anchorEl,onClose:()=>{a&&(null==o||o.forDocument(t).closeMenu(a.menuId))},container:e})}function ga({children:e,style:t,...n}){const{plugin:o}=Lo(Br.id),{provides:i}=Qr(),[r,a]=Se([]),[s,l]=Se([]),c=De(null),d=De(null),u=De(null),h=De(null),m=Re(()=>({containerRef:h,getContainer:()=>h.current}),[]),g=ze(e=>{const t=u.current;if(u.current=e,h.current=e,e&&e!==t&&o){const t=function(e){const t=e.getRootNode();return t instanceof ShadowRoot?t:document.head}(e);d.current=t;const n=t.querySelector(Sr.STYLES);if(n)return c.current=n,void(n.textContent=o.getStylesheet());const i=o.getStylesheet(),r=document.createElement("style");r.setAttribute(wr,""),r.textContent=i,t instanceof ShadowRoot?t.insertBefore(r,t.firstChild):t.appendChild(r),c.current=r}},[o]);Me(()=>()=>{var e;(null==(e=c.current)?void 0:e.parentNode)&&!u.current&&c.current.remove(),c.current=null,d.current=null},[]),Me(()=>{if(o)return o.onStylesheetInvalidated(()=>{c.current&&(c.current.textContent=o.getStylesheet())})},[o]),Me(()=>{if(i)return a(i.getDisabledCategories()),l(i.getHiddenItems()),i.onCategoryChanged(({disabledCategories:e,hiddenItems:t})=>{a(e),l(t)})},[i]);const p=Re(()=>r.length>0?r.join(" "):void 0,[r]),f=Re(()=>s.length>0?s.join(" "):void 0,[s]),v=Re(()=>{const e={containerType:"inline-size"};return t&&"object"==typeof t?{...e,...t}:e},[t]),y={[br]:"",[kr]:p,[Ir]:f};return He(ea.Provider,{value:m,children:He("div",{ref:g,...y,...n,style:v,children:e})})}function pa({children:e,documentId:t,components:n={},renderers:o,menuContainer:i,...r}){return He(oa,{children:He(sa,{initialComponents:n,children:He(da,{renderers:o,children:He(ga,{...r,children:[e,He(ma,{documentId:t,container:i})]})})})})}const fa=class extends bo{constructor(e,t,n){super(e,t),this.id=e,this.documentOpened$=Do(),this.documentClosed$=Do(),this.activeDocumentChanged$=Do(),this.documentError$=Do(),this.documentOrderChanged$=Do(),this.openFileRequest$=Po(),this.loadOptions=new Map,this.maxDocuments=null==n?void 0:n.maxDocuments}buildCapability(){return{openFileDialog:e=>this.openFileDialog(e),openDocumentUrl:e=>this.openDocumentUrl(e),openDocumentBuffer:e=>this.openDocumentBuffer(e),retryDocument:(e,t)=>this.retryDocument(e,t),closeDocument:e=>this.closeDocument(e),closeAllDocuments:()=>this.closeAllDocuments(),setActiveDocument:e=>{if(!this.isDocumentOpen(e))throw new Error(`Cannot set active document: ${e} is not open`);this.dispatchCoreAction((e=>({type:Zn,payload:e}))(e))},getActiveDocumentId:()=>this.coreState.core.activeDocumentId,getActiveDocument:()=>{var e;const t=this.coreState.core.activeDocumentId;return t?(null==(e=this.coreState.core.documents[t])?void 0:e.document)??null:null},getDocumentOrder:()=>this.coreState.core.documentOrder,moveDocument:(e,t)=>{this.dispatchCoreAction(((e,t)=>({type:Xn,payload:{documentId:e,toIndex:t}}))(e,t))},swapDocuments:(e,t)=>{const n=this.coreState.core.documentOrder,o=n.indexOf(e),i=n.indexOf(t);if(-1===o||-1===i)throw new Error("One or both documents not found in order");const r=[...n];[r[o],r[i]]=[r[i],r[o]],this.dispatchCoreAction((e=>({type:Yn,payload:e}))(r))},getDocument:e=>{var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.document)??null},getDocumentState:e=>this.coreState.core.documents[e]??null,getOpenDocuments:()=>this.coreState.core.documentOrder.map(e=>this.coreState.core.documents[e]).filter(e=>null!==e),isDocumentOpen:e=>this.isDocumentOpen(e),getDocumentCount:()=>Object.keys(this.coreState.core.documents).length,getDocumentIndex:e=>this.coreState.core.documentOrder.indexOf(e),setDocumentEncryption:(e,t)=>this.setDocumentEncryption(e,t),unlockOwnerPermissions:(e,t)=>this.unlockOwnerPermissions(e,t),removeEncryption:e=>this.removeEncryption(e),onDocumentOpened:this.documentOpened$.on,onDocumentClosed:this.documentClosed$.on,onDocumentError:this.documentError$.on,onActiveDocumentChanged:this.activeDocumentChanged$.on,onDocumentOrderChanged:this.documentOrderChanged$.on}}isDocumentOpen(e){return!!this.coreState.core.documents[e]}onDocumentLoaded(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&(this.loadOptions.delete(e),this.documentOpened$.emit(t),this.logger.info("DocumentManagerPlugin","DocumentOpened",`Document ${e} opened successfully`,{name:t.name}))}onDocumentClosed(e){this.loadOptions.delete(e),this.documentClosed$.emit(e),this.logger.info("DocumentManagerPlugin","DocumentClosed",`Document ${e} closed`)}onActiveDocumentChanged(e,t){this.activeDocumentChanged$.emit({previousDocumentId:e,currentDocumentId:t}),this.logger.info("DocumentManagerPlugin","ActiveDocumentChanged",`Active document changed from ${e} to ${t}`)}onCoreStoreUpdated(e,t){e.core.documentOrder!==t.core.documentOrder&&this.documentOrderChanged$.emit({order:t.core.documentOrder})}onOpenFileRequest(e){return this.openFileRequest$.on(e)}openDocumentUrl(e){const t=new Ct,n=e.documentId||this.generateDocumentId(),o=this.checkDocumentLimit();if(o)return t.reject(o),t;const i=e.name??this.extractNameFromUrl(e.url);this.loadOptions.set(n,e),this.dispatchCoreAction(oo(n,i,e.scale,e.rotation,!!e.password,e.autoActivate,e.permissions)),this.logger.info("DocumentManagerPlugin","OpenDocumentUrl",`Starting to load document from URL: ${e.url}`,{documentId:n,passwordProvided:!!e.password});const r={id:n,url:e.url},a=this.engine.openDocumentUrl(r,{password:e.password,mode:e.mode,requestOptions:e.requestOptions,normalizeRotation:!0});return t.resolve({documentId:n,task:a}),this.handleLoadTask(n,a,"OpenDocumentUrl"),t}openDocumentBuffer(e){const t=new Ct,n=this.checkDocumentLimit();if(n)return t.reject(n),t;const o=e.documentId||this.generateDocumentId();this.loadOptions.set(o,e),this.dispatchCoreAction(oo(o,e.name,e.scale,e.rotation,!!e.password,e.autoActivate,e.permissions)),this.logger.info("DocumentManagerPlugin","OpenDocumentBuffer",`Starting to load document from buffer: ${e.name}`,{documentId:o,passwordProvided:!!e.password});const i={id:o,content:e.buffer},r=this.engine.openDocumentBuffer(i,{password:e.password,normalizeRotation:!0});return t.resolve({documentId:o,task:r}),this.handleLoadTask(o,r,"OpenDocumentBuffer"),t}retryDocument(e,t){const n=new Ct,o=this.validateRetry(e);if(!o.valid)return n.reject(o.error),n;const i={...this.loadOptions.get(e),...(null==t?void 0:t.password)&&{password:t.password}};this.loadOptions.set(e,i),this.dispatchCoreAction(((e,t)=>({type:Vn,payload:{documentId:e,passwordProvided:t}}))(e,!!(null==t?void 0:t.password))),this.logger.info("DocumentManagerPlugin","RetryDocument",`Retrying to load document ${e}`,{passwordProvided:!!(null==t?void 0:t.password)});const r="url"in i?this.retryUrlDocument(e,i):this.retryBufferDocument(e,i);return n.resolve({documentId:e,task:r}),this.handleLoadTask(e,r,"RetryDocument"),n}openFileDialog(e){const t=new Ct;return this.openFileRequest$.emit({task:t,options:e}),t}closeDocument(e){const t=new Ct,n=this.coreState.core.documents[e];return n?("loaded"===n.status&&n.document?this.engine.closeDocument(n.document).wait(()=>{this.dispatchCoreAction(io(e)),t.resolve()},n=>{this.logger.error("DocumentManagerPlugin","CloseDocument",`Failed to close document ${e}`,n),t.fail(n)}):(this.logger.info("DocumentManagerPlugin","CloseDocument",`Closing document ${e} in ${n.status} state (skipping engine close)`),this.dispatchCoreAction(io(e)),t.resolve()),t):(this.logger.warn("DocumentManagerPlugin","CloseDocument",`Cannot close document ${e}: not found in state`),t.resolve(),t)}closeAllDocuments(){const e=Object.keys(this.coreState.core.documents),t=e.map(e=>this.closeDocument(e));return this.logger.info("DocumentManagerPlugin","CloseAllDocuments",`Closing ${e.length} documents`),Ct.all(t)}setDocumentEncryption(e,t){const n=new Ct,o=this.coreState.core.documents[e];if(!(null==o?void 0:o.document))return n.reject({code:tn.DocNotOpen,message:`Document ${e} is not open`}),n;this.logger.info("DocumentManagerPlugin","SetDocumentEncryption",`Setting encryption on document ${e}`,{hasUserPassword:!!t.userPassword,allowedFlags:t.allowedFlags});return this.engine.setDocumentEncryption(o.document,t.userPassword??"",t.ownerPassword,t.allowedFlags).wait(t=>{t&&this.logger.info("DocumentManagerPlugin","SetDocumentEncryption",`Encryption set successfully on document ${e}`),n.resolve(t)},t=>{this.logger.error("DocumentManagerPlugin","SetDocumentEncryption",`Failed to set encryption on document ${e}`,t),n.fail(t)}),n}unlockOwnerPermissions(e,t){const n=new Ct,o=this.coreState.core.documents[e];if(!(null==o?void 0:o.document))return n.reject({code:tn.DocNotOpen,message:`Document ${e} is not open`}),n;const i=o.document;this.logger.info("DocumentManagerPlugin","UnlockOwnerPermissions",`Attempting to unlock owner permissions on document ${e}`);return this.engine.unlockOwnerPermissions(i,t).wait(t=>{if(t){this.logger.info("DocumentManagerPlugin","UnlockOwnerPermissions",`Owner permissions unlocked on document ${e}`);const t=4294967295;this.dispatchCoreAction(((e,t,n)=>({type:Qn,payload:{documentId:e,permissions:t,isOwnerUnlocked:n}}))(e,t,!0))}n.resolve(t)},t=>{this.logger.error("DocumentManagerPlugin","UnlockOwnerPermissions",`Failed to unlock owner permissions on document ${e}`,t),n.fail(t)}),n}removeEncryption(e){const t=new Ct,n=this.coreState.core.documents[e];if(!(null==n?void 0:n.document))return t.reject({code:tn.DocNotOpen,message:`Document ${e} is not open`}),t;this.logger.info("DocumentManagerPlugin","RemoveEncryption",`Marking document ${e} for encryption removal on save`);return this.engine.removeEncryption(n.document).wait(n=>{n&&this.logger.info("DocumentManagerPlugin","RemoveEncryption",`Document ${e} marked for encryption removal`),t.resolve(n)},n=>{this.logger.error("DocumentManagerPlugin","RemoveEncryption",`Failed to mark document ${e} for encryption removal`,n),t.fail(n)}),t}checkDocumentLimit(){return this.maxDocuments&&Object.keys(this.coreState.core.documents).length>=this.maxDocuments?{code:tn.Unknown,message:`Maximum number of documents (${this.maxDocuments}) reached`}:null}validateRetry(e){const t=this.coreState.core.documents[e];return t?"loaded"===t.status?{valid:!1,error:{code:tn.Unknown,message:`Document ${e} is already loaded successfully`}}:"error"!==t.status?{valid:!1,error:{code:tn.Unknown,message:`Document ${e} is not in error state (current state: ${t.status})`}}:this.loadOptions.has(e)?{valid:!0}:{valid:!1,error:{code:tn.Unknown,message:`No retry information available for document ${e}`}}:{valid:!1,error:{code:tn.NotFound,message:`Document ${e} not found`}}}retryUrlDocument(e,t){const n={id:e,url:t.url};return this.engine.openDocumentUrl(n,{password:t.password,mode:t.mode,requestOptions:t.requestOptions})}retryBufferDocument(e,t){const n={id:e,content:t.buffer};return this.engine.openDocumentBuffer(n,{password:t.password,normalizeRotation:!0})}handleLoadTask(e,t,n){t.wait(t=>{this.dispatchCoreAction(((e,t)=>({type:qn,payload:{documentId:e,document:t}}))(e,t))},t=>{this.handleLoadError(e,t,n)})}handleLoadError(e,t,n){var o,i,r;const a=(null==(o=t.reason)?void 0:o.message)||"Failed to load document";this.logger.error("DocumentManagerPlugin",n,"Failed to load document",t),this.dispatchCoreAction(((e,t,n,o)=>({type:Gn,payload:{documentId:e,error:t,errorCode:n,errorDetails:o}}))(e,a,null==(i=t.reason)?void 0:i.code,t.reason)),this.documentError$.emit({documentId:e,message:a,code:null==(r=t.reason)?void 0:r.code,reason:t.reason})}generateDocumentId(){return`doc-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}extractNameFromUrl(e){try{const t=new URL(e),n=t.pathname.split("/").pop();if(!n)return;let o=decodeURIComponent(n);return o.toLowerCase().endsWith(".pdf")||(o+=".pdf"),o}catch{return}}async initialize(e){var t;if(this.logger.info("DocumentManagerPlugin","Initialize","Document Manager Plugin initialized",{maxDocuments:this.maxDocuments,initialDocumentsCount:(null==(t=e.initialDocuments)?void 0:t.length)??0}),e.initialDocuments&&e.initialDocuments.length>0)for(const t of e.initialDocuments)try{"buffer"in t?this.openDocumentBuffer(t):"url"in t&&this.openDocumentUrl(t)}catch(e){this.logger.error("DocumentManagerPlugin","Initialize","Failed to initiate initial document load",e)}}async destroy(){await this.closeAllDocuments().toPromise(),this.loadOptions.clear(),this.documentOpened$.clear(),this.documentClosed$.clear(),this.activeDocumentChanged$.clear(),this.documentOrderChanged$.clear(),this.documentError$.clear(),super.destroy()}};fa.id="document-manager";let va=fa;const ya="document-manager";function ba({documentId:e,children:t}){const n=jo(e);if(!n)return null;return He(H,{children:t({documentState:n,isLoading:"loading"===n.status,isError:"error"===n.status,isLoaded:"loaded"===n.status})})}const wa=()=>Oo(va.id);const xa=To({manifest:{id:ya,name:"Document Manager Plugin",version:"1.0.0",provides:["document-manager"],requires:[],optional:[],defaultConfig:{maxDocuments:10}},create:(e,t)=>new va(ya,e,t),reducer:e=>e,initialState:{}}).addUtility(function(){const{plugin:e}=Lo(va.id),{provides:t}=wa(),n=De(null),o=De(null),i=De(void 0);return Me(()=>{if(!(null==e?void 0:e.onOpenFileRequest))return;return e.onOpenFileRequest(({task:e,options:t})=>{var r;o.current=e,i.current=t,null==(r=n.current)||r.click()})},[e]),He("input",{ref:n,type:"file",accept:"application/pdf",style:{display:"none"},onChange:async e=>{var n,r,a,s,l;const c=null==(n=e.currentTarget.files)?void 0:n[0];if(!c||!t)return;const d=await c.arrayBuffer();t.openDocumentBuffer({name:c.name,buffer:d,documentId:null==(r=i.current)?void 0:r.documentId,scale:null==(a=i.current)?void 0:a.scale,rotation:null==(s=i.current)?void 0:s.rotation,autoActivate:null==(l=i.current)?void 0:l.autoActivate}).wait(e=>{var t;null==(t=o.current)||t.resolve(e)},e=>{var t;null==(t=o.current)||t.fail(e)})}})}).build(),Ca="commands",ka={id:Ca,name:"Commands Plugin",version:"1.0.0",provides:["commands"],requires:[],optional:["i18n","ui"],defaultConfig:{commands:{}}},Ia="COMMANDS/SET_DISABLED_CATEGORIES",Sa=e=>({type:Ia,payload:e}),Aa=class extends bo{constructor(e,t,n){var o;super(e,t),this.commands=new Map,this.i18n=null,this.shortcutMap=new Map,this.commandExecuted$=Po(),this.commandStateChanged$=Po(),this.shortcutExecuted$=Po(),this.categoryChanged$=Do(),this.previousStates=new Map;const i=t.getPlugin("i18n");this.i18n=(null==i?void 0:i.provides())??null,(null==(o=n.disabledCategories)?void 0:o.length)&&this.dispatch(Sa(n.disabledCategories)),Object.values(n.commands).forEach(e=>{this.registerCommand(e)}),this.registry.getStore().subscribe((e,t)=>{this.onGlobalStoreChange(t)})}onDocumentClosed(e){this.previousStates.delete(e),this.logger.debug("CommandsPlugin","DocumentClosed",`Cleaned up command state cache for document: ${e}`)}async initialize(){this.logger.info("CommandsPlugin","Initialize","Commands plugin initialized")}async destroy(){this.commandExecuted$.clear(),this.commandStateChanged$.clear(),this.shortcutExecuted$.clear(),this.categoryChanged$.clear(),this.commands.clear(),this.shortcutMap.clear(),this.previousStates.clear(),super.destroy()}disableCategoryImpl(e){const t=new Set(this.state.disabledCategories);t.has(e)||(t.add(e),this.dispatch(Sa(Array.from(t))),this.categoryChanged$.emit({disabledCategories:Array.from(t)}))}enableCategoryImpl(e){const t=new Set(this.state.disabledCategories);t.has(e)&&(t.delete(e),this.dispatch(Sa(Array.from(t))),this.categoryChanged$.emit({disabledCategories:Array.from(t)}))}toggleCategoryImpl(e){this.state.disabledCategories.includes(e)?this.enableCategoryImpl(e):this.disableCategoryImpl(e)}setDisabledCategoriesImpl(e){this.dispatch(Sa(e)),this.categoryChanged$.emit({disabledCategories:e})}isCommandCategoryDisabled(e){var t;return!!(null==(t=e.categories)?void 0:t.length)&&e.categories.some(e=>this.state.disabledCategories.includes(e))}buildCapability(){return{resolve:(e,t)=>this.resolve(e,t),execute:(e,t,n="ui")=>this.execute(e,t,n),getAllCommands:e=>this.getAllCommands(e),getCommandsByCategory:(e,t)=>this.getCommandsByCategory(e,t),getCommandByShortcut:e=>this.getCommandByShortcut(e),getAllShortcuts:()=>new Map(this.shortcutMap),forDocument:e=>this.createCommandScope(e),registerCommand:e=>this.registerCommand(e),unregisterCommand:e=>this.unregisterCommand(e),disableCategory:e=>this.disableCategoryImpl(e),enableCategory:e=>this.enableCategoryImpl(e),toggleCategory:e=>this.toggleCategoryImpl(e),setDisabledCategories:e=>this.setDisabledCategoriesImpl(e),getDisabledCategories:()=>this.state.disabledCategories,isCategoryDisabled:e=>this.state.disabledCategories.includes(e),onCommandExecuted:this.commandExecuted$.on,onCommandStateChanged:this.commandStateChanged$.on,onShortcutExecuted:this.shortcutExecuted$.on,onCategoryChanged:this.categoryChanged$.on}}createCommandScope(e){return{resolve:t=>this.resolve(t,e),execute:(t,n="ui")=>this.execute(t,e,n),getAllCommands:()=>this.getAllCommands(e),getCommandsByCategory:t=>this.getCommandsByCategory(t,e),onCommandStateChanged:t=>this.commandStateChanged$.on(n=>{if(n.documentId===e){const{documentId:e,...o}=n;t(o)}})}}resolve(e,t){const n=t??this.getActiveDocumentId(),o=this.commands.get(e);if(!o)throw new Error(`Command not found: ${e}`);const i=this.registry.getStore().getState(),r=this.resolveLabel(o,i,n),a=o.shortcuts?Array.isArray(o.shortcuts)?o.shortcuts:[o.shortcuts]:void 0,s=this.resolveDynamic(o.disabled,i,n)??!1,l=this.isCommandCategoryDisabled(o),c=s||l;return{id:o.id,label:r,icon:this.resolveDynamic(o.icon,i,n),iconProps:this.resolveDynamic(o.iconProps,i,n),active:this.resolveDynamic(o.active,i,n)??!1,disabled:c,visible:this.resolveDynamic(o.visible,i,n)??!0,shortcuts:a,shortcutLabel:o.shortcutLabel,categories:o.categories,description:o.description,execute:()=>o.action({registry:this.registry,state:i,documentId:n,logger:this.logger})}}resolveLabel(e,t,n){const o=this.resolveDynamic(e.labelKey,t,n);if(o&&this.i18n){const i=this.resolveDynamic(e.labelParams,t,n);return this.i18n.t(o,{params:i,documentId:n})}return e.label?e.label:e.id}resolveDynamic(e,t,n){if(void 0!==e)return"function"==typeof e?e({registry:this.registry,state:t,documentId:n,logger:this.logger}):e}execute(e,t,n="ui"){const o=t??this.getActiveDocumentId(),i=this.resolve(e,o);i.disabled?this.logger.warn("CommandsPlugin","ExecutionBlocked",`Command '${e}' is disabled for document '${o}'`):i.visible?(i.execute(),this.commandExecuted$.emit({commandId:e,documentId:o,source:n}),this.logger.debug("CommandsPlugin","CommandExecuted",`Command '${e}' executed for document '${o}' (source: ${n})`)):this.logger.warn("CommandsPlugin","ExecutionBlocked",`Command '${e}' is not visible for document '${o}'`)}registerCommand(e){if(this.commands.has(e.id)&&this.logger.warn("CommandsPlugin","CommandOverwrite",`Command '${e.id}' already exists and will be overwritten`),this.commands.set(e.id,e),e.shortcuts){(Array.isArray(e.shortcuts)?e.shortcuts:[e.shortcuts]).forEach(t=>{const n=this.normalizeShortcut(t);this.shortcutMap.set(n,e.id)})}this.logger.debug("CommandsPlugin","CommandRegistered",`Command '${e.id}' registered`)}unregisterCommand(e){const t=this.commands.get(e);if(t){if(t.shortcuts){(Array.isArray(t.shortcuts)?t.shortcuts:[t.shortcuts]).forEach(e=>{const t=this.normalizeShortcut(e);this.shortcutMap.delete(t)})}this.commands.delete(e),this.logger.debug("CommandsPlugin","CommandUnregistered",`Command '${e}' unregistered`)}}getCommandByShortcut(e){const t=this.normalizeShortcut(e),n=this.shortcutMap.get(t);return n?this.commands.get(n)??null:null}normalizeShortcut(e){return e.toLowerCase().split("+").sort().join("+")}getAllCommands(e){const t=e??this.getActiveDocumentId();return Array.from(this.commands.keys()).map(e=>this.resolve(e,t))}getCommandsByCategory(e,t){const n=t??this.getActiveDocumentId();return Array.from(this.commands.values()).filter(t=>{var n;return null==(n=t.categories)?void 0:n.includes(e)}).map(e=>this.resolve(e.id,n))}onGlobalStoreChange(e){Object.keys(e.core.documents).forEach(t=>{this.detectCommandChanges(t,e)})}detectCommandChanges(e,t){const n=t.core.documents[e];if(!n||"loaded"!==n.status)return;const o=this.previousStates.get(e)??new Map;this.commands.forEach((t,n)=>{const i=this.resolve(n,e),r=o.get(n);if(!r)return void o.set(n,i);const a={};r.active!==i.active&&(a.active=i.active),r.disabled!==i.disabled&&(a.disabled=i.disabled),r.visible!==i.visible&&(a.visible=i.visible),r.label!==i.label&&(a.label=i.label),r.icon!==i.icon&&(a.icon=i.icon),Io(r.iconProps,i.iconProps)||(a.iconProps=i.iconProps),Object.keys(a).length>0&&(o.set(n,i),this.commandStateChanged$.emit({commandId:n,documentId:e,changes:a}))}),this.previousStates.set(e,o)}};Aa.id="commands";let Ma=Aa;const Pa={disabledCategories:[]},Da=()=>Oo(Ma.id),Ra=(e,t)=>{const{provides:n}=Da(),[o,i]=Se(()=>n?n.resolve(e,t):null);return Me(()=>{if(!n)return void i(null);i(n.resolve(e,t));return n.onCommandStateChanged(o=>{o.commandId===e&&o.documentId===t&&i(n.resolve(e,t))})},[n,e,t]),o};const za=To({manifest:ka,create:(e,t)=>new Ma(Ca,e,t),reducer:(e=Pa,t)=>t.type===Ia?{...e,disabledCategories:t.payload}:e,initialState:Pa}).addUtility(function(){const{provides:e}=Da();return Me(()=>{if(!e)return;const t=function(e){return t=>{const n=t.composedPath()[0]||t.target;if("INPUT"===n.tagName||"TEXTAREA"===n.tagName||n.isContentEditable)return;const o=function(e){const t=[];e.ctrlKey&&t.push("ctrl"),e.shiftKey&&t.push("shift"),e.altKey&&t.push("alt"),e.metaKey&&t.push("meta");const n=e.key.toLowerCase();return["control","shift","alt","meta"].includes(n)?null:[...t,n].sort().join("+")}(t);if(!o)return;const i=e.getCommandByShortcut(o);if(!i)return;const r=e.resolve(i.id);!r.disabled&&r.visible&&(t.preventDefault(),t.stopPropagation(),e.execute(i.id,void 0,"keyboard"))}}(e);return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[e]),null}).build(),Ta="i18n",Ea={id:Ta,name:"I18n Plugin",version:"1.0.0",provides:["i18n"],requires:[],optional:[],defaultConfig:{defaultLocale:"en",locales:[{code:"en",name:"English",translations:{commands:{zoom:{in:"Zoom In",out:"Zoom Out",fitWidth:"Fit to Width",fitPage:"Fit to Page",automatic:"Automatic",level:"Zoom Level ({level}%)",inArea:"Zoom In Area"},fullscreen:{enter:"Enter Full Screen",exit:"Exit Full Screen"},rotate:{clockwise:"Rotate Clockwise",counterclockwise:"Rotate Counter-Clockwise"},menu:"Menu",sidebar:"Sidebar",search:"Search",comment:"Comment",download:"Download",print:"Print",openFile:"Open PDF",save:"Save",settings:"Settings",view:"View",annotate:"Annotate",shapes:"Shapes",redact:"Redact",fillAndSign:"Fill and Sign",form:"Form",pan:"Pan",pointer:"Pointer",undo:"Undo",redo:"Redo",copy:"Copy",screenshot:"Screenshot",nextPage:"Next Page",previousPage:"Previous Page"}}},{code:"es",name:"Español",translations:{commands:{zoom:{in:"Acercar",out:"Alejar",fitWidth:"Ajustar al ancho",fitPage:"Ajustar a la página",automatic:"Automático",level:"Nivel de zoom ({level}%)",inArea:"Acercar área"},fullscreen:{enter:"Pantalla completa",exit:"Salir de pantalla completa"},rotate:{clockwise:"Girar a la derecha",counterclockwise:"Girar a la izquierda"},menu:"Menú",sidebar:"Barra lateral",search:"Buscar",comment:"Comentario",download:"Descargar",print:"Imprimir",openFile:"Abrir PDF",save:"Guardar",settings:"Configuración",view:"Ver",annotate:"Anotar",shapes:"Formas",redact:"Redactar",fillAndSign:"Rellenar y firmar",form:"Formulario",pan:"Desplazar",pointer:"Puntero",undo:"Deshacer",redo:"Rehacer",copy:"Copiar",screenshot:"Captura de pantalla",nextPage:"Página siguiente",previousPage:"Página anterior"}}}]}},_a="I18N/SET_LOCALE",Na="I18N/REGISTER_LOCALE",La=e=>({type:_a,payload:e}),Oa=e=>({type:Na,payload:e}),$a=class extends bo{constructor(e,t,n){super(e,t),this.locales=new Map,this.paramResolvers=new Map,this.paramsCache=new Map,this.localeChange$=Po(),this.paramsChanged$=Ro((e,t)=>({documentId:e,...t}),{cache:!1}),this.config=n,n.locales.forEach(e=>{this.locales.set(e.code,e),this.dispatch(Oa(e.code))}),n.paramResolvers&&Object.entries(n.paramResolvers).forEach(([e,t])=>{this.paramResolvers.set(e,t)}),this.dispatch(La(n.defaultLocale)),this.registry.getStore().subscribe((e,t)=>{this.detectParamChanges(t)})}async initialize(){this.logger.info("I18nPlugin","Initialize","I18n plugin initialized")}async destroy(){this.localeChange$.clear(),this.paramsChanged$.clear(),this.paramResolvers.clear(),this.paramsCache.clear(),super.destroy()}onDocumentClosed(e){this.paramsCache.delete(e),this.paramsChanged$.clearScope(e),this.logger.debug("I18nPlugin","DocumentClosed",`Cleaned up params cache for document: ${e}`)}buildCapability(){return{t:(e,t)=>this.translate(e,t),forDocument:e=>this.createI18nScope(e),registerParamResolver:(e,t)=>this.registerParamResolver(e,t),unregisterParamResolver:e=>this.unregisterParamResolver(e),setLocale:e=>this.setLocale(e),getLocale:()=>this.state.currentLocale,getAvailableLocales:()=>[...this.state.availableLocales],getLocaleInfo:e=>this.locales.get(e)??null,registerLocale:e=>this.registerLocale(e),hasLocale:e=>this.locales.has(e),onLocaleChange:this.localeChange$.on,onParamsChanged:this.paramsChanged$.onGlobal}}createI18nScope(e){return{t:(t,n)=>this.translate(t,{documentId:e,...n}),onParamsChanged:this.paramsChanged$.forScope(e)}}translate(e,t){const n=this.locales.get(this.state.currentLocale),o=this.config.fallbackLocale?this.locales.get(this.config.fallbackLocale):null;let i=this.getNestedValue(null==n?void 0:n.translations,e);if(!i&&o&&(i=this.getNestedValue(o.translations,e)),!i){if(!(null==t?void 0:t.fallback))return this.logger.warn("I18nPlugin","MissingTranslation",`Translation not found for key: ${e}`),e;i=t.fallback}let r=null==t?void 0:t.params;return!r&&this.paramResolvers.has(e)&&(r=this.resolveParams(e,null==t?void 0:t.documentId)),this.interpolate(i,r)}resolveParams(e,t){const n=this.paramResolvers.get(e);if(!n)return;const o=this.registry.getStore().getState();try{return n({state:o,documentId:t})}catch(t){return void this.logger.error("I18nPlugin","ParamResolverError",`Error resolving params for key "${e}":`,t)}}getNestedValue(e,t){if(!e)return;const n=t.split(".");let o=e;for(const e of n){if(null==o)return;o=o[e]}return"string"==typeof o?o:void 0}interpolate(e,t){return t?e.replace(/\{(\w+)\}/g,(e,n)=>{const o=t[n];return void 0!==o?String(o):e}):e}detectParamChanges(e){Object.keys(e.core.documents).forEach(t=>{this.detectDocumentParamChanges(t,e)})}detectDocumentParamChanges(e,t){const n=this.paramsCache.get(e),o=[];this.paramResolvers.forEach((i,r)=>{try{const a=i({state:t,documentId:e});Io(null==n?void 0:n.get(r),a)||(o.push(r),this.paramsCache.has(e)||this.paramsCache.set(e,new Map),this.paramsCache.get(e).set(r,a))}catch(e){this.logger.error("I18nPlugin","ParamDetectionError",`Error detecting param changes for key "${r}":`,e)}}),o.length>0&&(this.paramsChanged$.emit(e,{changedKeys:o}),this.logger.debug("I18nPlugin","ParamsChanged",`Translation params changed for document ${e}:`,o))}registerParamResolver(e,t){this.paramResolvers.has(e)&&this.logger.warn("I18nPlugin","ResolverOverwrite",`Param resolver for "${e}" already exists and will be overwritten`),this.paramResolvers.set(e,t),this.paramsCache.forEach(t=>{t.delete(e)}),this.logger.debug("I18nPlugin","ResolverRegistered",`Param resolver registered for: ${e}`)}unregisterParamResolver(e){this.paramResolvers.delete(e)&&(this.paramsCache.forEach(t=>{t.delete(e)}),this.logger.debug("I18nPlugin","ResolverUnregistered",`Param resolver unregistered for: ${e}`))}setLocale(e){if(!this.locales.has(e))return void this.logger.warn("I18nPlugin","LocaleNotFound",`Locale '${e}' is not registered`);const t=this.state.currentLocale;t!==e&&(this.dispatch(La(e)),this.localeChange$.emit({previousLocale:t,currentLocale:e}),this.logger.info("I18nPlugin","LocaleChanged",`Locale changed to: ${e}`))}registerLocale(e){this.locales.has(e.code)?this.logger.warn("I18nPlugin","LocaleAlreadyRegistered",`Locale '${e.code}' is already registered`):(this.locales.set(e.code,e),this.dispatch(Oa(e.code)),this.logger.info("I18nPlugin","LocaleRegistered",`Locale registered: ${e.code}`))}};$a.id="i18n";let ja=$a;const Fa={currentLocale:"en",availableLocales:[]},Ua={manifest:Ea,create:(e,t)=>new ja(Ta,e,t),reducer:(e=Fa,t)=>{switch(t.type){case _a:{const n=t.payload;return e.availableLocales.includes(n)?{...e,currentLocale:n}:(console.warn(`I18nPlugin: Locale '${n}' not available`),e)}case Na:{const n=t.payload;return e.availableLocales.includes(n)?e:{...e,availableLocales:[...e.availableLocales,n]}}default:return e}},initialState:Fa},Ha=e=>{const{provides:t}=Oo(ja.id),[,n]=Ae(e=>e+1,0),o=ze((n,o)=>t?t.t(n,{documentId:e,params:null==o?void 0:o.params,fallback:null==o?void 0:o.fallback}):(null==o?void 0:o.fallback)??n,[t,e]);return Me(()=>{if(!t)return;const o=t.onLocaleChange(()=>{n()}),i=e?t.forDocument(e).onParamsChanged(()=>{n()}):t.onParamsChanged(()=>{n()});return()=>{o(),i()}},[t,e]),{translate:o,locale:(null==t?void 0:t.getLocale())??"en"}};var Wa=(e=>(e.Automatic="automatic",e.FitPage="fit-page",e.FitWidth="fit-width",e))(Wa||{}),Ba=(e=>(e[e.Center=0]="Center",e[e.Top=1]="Top",e))(Ba||{});const qa="zoom",Ga={id:qa,name:"Zoom Plugin",version:"1.0.0",provides:["zoom"],requires:["viewport","scroll"],optional:["interaction-manager","spread"],defaultConfig:{defaultZoomLevel:Wa.Automatic,minZoom:.2,maxZoom:60,zoomStep:.1,zoomRanges:[{min:.2,max:.5,step:.05},{min:.5,max:1,step:.1},{min:1,max:2,step:.2},{min:2,max:4,step:.4},{min:4,max:10,step:.8},{min:10,max:20,step:1.6},{min:20,max:40,step:3.2},{min:40,max:60,step:6.4}],presets:[{name:"Fit Page",value:Wa.FitPage},{name:"Fit Width",value:Wa.FitWidth},{name:"Automatic",value:Wa.Automatic},{name:"25%",value:.25},{name:"50%",value:.5},{name:"100%",value:1},{name:"125%",value:1.25},{name:"150%",value:1.5},{name:"200%",value:2},{name:"400%",value:4},{name:"800%",value:8},{name:"1600%",value:16}]}},Va="ZOOM/INIT_STATE",Ka="ZOOM/CLEANUP_STATE",Za="ZOOM/SET_ZOOM_LEVEL",Ya="ZOOM/SET_MARQUEE_ZOOM_ACTIVE";const Xa={zoomLevel:Wa.Automatic,currentZoomLevel:1,isMarqueeZoomActive:!1},Qa={documents:{},activeDocumentId:null};const Ja=class extends bo{constructor(e,t,n){var o,i,r;super(e,t),this.zoom$=Po(),this.state$=Do(),this.viewportPlugin=t.getPlugin("viewport"),this.viewport=this.viewportPlugin.provides(),this.scroll=t.getPlugin("scroll").provides();const a=t.getPlugin("interaction-manager");this.interactionManager=(null==a?void 0:a.provides())??null;const s=t.getPlugin("spread");this.spread=(null==s?void 0:s.provides())??null,this.minZoom=n.minZoom??.25,this.maxZoom=n.maxZoom??10,this.zoomStep=n.zoomStep??.1,this.defaultZoomLevel=n.defaultZoomLevel,this.presets=n.presets??[],this.zoomRanges=this.normalizeRanges(n.zoomRanges??[]),this.viewport.onViewportResize(e=>this.recalcAuto(e.documentId,Ba.Top),{mode:"debounce",wait:150,keyExtractor:e=>e.documentId}),null==(o=this.spread)||o.onSpreadChange(e=>{this.recalcAuto(e.documentId,Ba.Top)}),null==(i=this.interactionManager)||i.registerMode({id:"marqueeZoom",scope:"page",exclusive:!0,cursor:"zoom-in"}),null==(r=this.interactionManager)||r.onModeChange(e=>{const t="marqueeZoom"===e.activeMode,n=this.getDocumentState(e.documentId);var o;n&&n.isMarqueeZoomActive!==t&&this.dispatch((o=e.documentId,{type:Ya,payload:{documentId:o,isActive:t}}))})}onDocumentLoadingStarted(e){this.viewport.gate("zoom",e);const t={...Xa,zoomLevel:this.defaultZoomLevel};this.dispatch(function(e,t){return{type:Va,payload:{documentId:e,state:t}}}(e,t)),this.logger.debug("ZoomPlugin","DocumentOpened",`Initialized zoom state for document: ${e}`)}onDocumentLoaded(e){this.recalcAuto(e,Ba.Top)}onDocumentClosed(e){this.dispatch(function(e){return{type:Ka,payload:e}}(e)),this.logger.debug("ZoomPlugin","DocumentClosed",`Cleaned up zoom state for document: ${e}`)}onRotationChanged(e){this.recalcAuto(e,Ba.Top)}buildCapability(){return{requestZoom:(e,t)=>this.requestZoom(e,t),requestZoomBy:(e,t)=>this.requestZoomBy(e,t),zoomIn:()=>this.zoomIn(),zoomOut:()=>this.zoomOut(),zoomToArea:(e,t)=>this.zoomToArea(e,t),enableMarqueeZoom:()=>this.enableMarqueeZoom(),disableMarqueeZoom:()=>this.disableMarqueeZoom(),toggleMarqueeZoom:()=>this.toggleMarqueeZoom(),isMarqueeZoomActive:()=>this.isMarqueeZoomActive(),getState:()=>this.getDocumentStateOrThrow(),forDocument:e=>this.createZoomScope(e),registerMarqueeOnPage:e=>this.registerMarqueeOnPage(e),getPresets:()=>this.presets,onZoomChange:this.zoom$.on,onStateChange:this.state$.on}}createZoomScope(e){return{requestZoom:(t,n)=>this.requestZoom(t,n,e),requestZoomBy:(t,n)=>this.requestZoomBy(t,n,e),zoomIn:()=>this.zoomIn(e),zoomOut:()=>this.zoomOut(e),zoomToArea:(t,n)=>this.zoomToArea(t,n,e),enableMarqueeZoom:()=>this.enableMarqueeZoom(e),disableMarqueeZoom:()=>this.disableMarqueeZoom(e),toggleMarqueeZoom:()=>this.toggleMarqueeZoom(e),isMarqueeZoomActive:()=>this.isMarqueeZoomActive(e),getState:()=>this.getDocumentStateOrThrow(e),onZoomChange:t=>this.zoom$.on(n=>{n.documentId===e&&t(n)}),onStateChange:t=>this.state$.on(n=>{n.documentId===e&&t(n.state)})}}getDocumentState(e){const t=e??this.getActiveDocumentId();return this.state.documents[t]??null}getDocumentStateOrThrow(e){const t=this.getDocumentState(e);if(!t)throw new Error(`Zoom state not found for document: ${e??"active"}`);return t}requestZoom(e,t,n){this.handleRequest({level:e,center:t},n)}requestZoomBy(e,t,n){const o=n??this.getActiveDocumentId(),i=this.getDocumentStateOrThrow(o).currentZoomLevel,r=this.toZoom(i+e);this.handleRequest({level:r,center:t},o)}zoomIn(e){const t=e??this.getActiveDocumentId(),n=this.getDocumentStateOrThrow(t).currentZoomLevel;this.handleRequest({level:n,delta:this.stepFor(n)},t)}zoomOut(e){const t=e??this.getActiveDocumentId(),n=this.getDocumentStateOrThrow(t).currentZoomLevel;this.handleRequest({level:n,delta:-this.stepFor(n)},t)}zoomToArea(e,t,n){const o=n??this.getActiveDocumentId();this.handleZoomToArea(o,e,t)}enableMarqueeZoom(e){var t;const n=e??this.getActiveDocumentId();null==(t=this.interactionManager)||t.forDocument(n).activate("marqueeZoom")}disableMarqueeZoom(e){var t;const n=e??this.getActiveDocumentId();null==(t=this.interactionManager)||t.forDocument(n).activateDefaultMode()}toggleMarqueeZoom(e){var t;const n=e??this.getActiveDocumentId(),o=null==(t=this.interactionManager)?void 0:t.forDocument(n);"marqueeZoom"===(null==o?void 0:o.getActiveMode())?o.activateDefaultMode():null==o||o.activate("marqueeZoom")}isMarqueeZoomActive(e){var t;const n=e??this.getActiveDocumentId();return"marqueeZoom"===(null==(t=this.interactionManager)?void 0:t.forDocument(n).getActiveMode())}handleRequest({level:e,delta:t=0,center:n,focus:o=Ba.Center,align:i="keep"},r){const a=r??this.getActiveDocumentId(),s=this.getDocumentStateOrThrow(a);if(!this.coreState.core.documents[a])return;const l=this.viewport.forDocument(a),c=l.getMetrics(),d=s.currentZoomLevel;if(0===c.clientWidth||0===c.clientHeight)return;const u="number"==typeof e?e:this.computeZoomForMode(a,e,c);if(!1===u)return;const h=ko(u+t,this.minZoom,this.maxZoom),m=Math.floor(1e3*h)/1e3,g=n??{vx:c.clientWidth/2,vy:o===Ba.Top?0:c.clientHeight/2},{desiredScrollLeft:p,desiredScrollTop:f}=this.computeScrollForZoomChange(a,c,d,m,g,i);isNaN(p)||isNaN(f)||this.viewportPlugin.setViewportScrollMetrics(a,{scrollLeft:p,scrollTop:f}),this.dispatch(function(e,t,n){return{type:Za,payload:{documentId:e,zoomLevel:t,currentZoomLevel:n}}}(a,"number"==typeof e?m:e,m)),this.dispatchCoreAction(((e,t)=>({type:eo,payload:{scale:e,documentId:t}}))(m,a)),this.viewport.isGated(a)&&this.viewport.releaseGate("zoom",a),l.scrollTo({x:p,y:f,behavior:"instant"});const v={documentId:a,oldZoom:d,newZoom:m,level:e,center:g,desiredScrollLeft:p,desiredScrollTop:f,viewport:c};this.zoom$.emit(v)}computeZoomForMode(e,t,n){if(!this.coreState.core.documents[e])return!1;const o=this.scroll.forDocument(e),i=o?this.scroll.getPageGap():0,r=this.viewport.getViewportGap(),a=o.getSpreadPagesWithRotatedSize();if(!a.length)return!1;if(0===n.clientWidth||0===n.clientHeight)return!1;const s=n.clientWidth-2*r,l=n.clientHeight-2*r;if(s<=0||l<=0)return!1;let c=0,d=0;switch(a.forEach(e=>{const t=e.reduce((e,t,n)=>e+t.rotatedSize.width+(n?i:0),0),n=Math.max(...e.map(e=>e.rotatedSize.height));c=Math.max(c,t),d=Math.max(d,n)}),t){case Wa.FitWidth:return s/c;case Wa.FitPage:return Math.min(s/c,l/d);case Wa.Automatic:return Math.min(s/c,1);default:return 1}}computeScrollForZoomChange(e,t,n,o,i,r="keep"){const a=this.scroll.forDocument(e).getLayout(),s=this.viewport.getViewportGap(),l=a.totalContentSize.width,c=a.totalContentSize.height,d=t.clientWidth-2*s,u=t.clientHeight-2*s,h=(e,t,n)=>t*ne.pageLayouts.some(e=>e.pageIndex===t));if(!u)return;const h=u.pageLayouts.find(e=>e.pageIndex===t),m=tt({width:h.width,height:h.height},n,i),g=this.toZoom(Math.min(l/m.size.width,c/m.size.height)),p=u.x+h.x,f=u.y+h.y,v=p+m.origin.x+m.size.width/2,y=f+m.origin.y+m.size.height/2,b=(e,t,n)=>t*ne.step>0&&e.max>e.min).sort((e,t)=>e.min-t.min)}stepFor(e){const t=this.zoomRanges.find(t=>e>=t.min&&e{};const t=this.coreState.core.documents[e.documentId];if(!t||!t.document)return this.logger.warn("ZoomPlugin","DocumentNotFound","Document not found"),()=>{};const n=t.document.pages[e.pageIndex];if(!n)return this.logger.warn("ZoomPlugin","PageNotFound",`Page ${e.pageIndex} not found`),()=>{};const o=function(e){const{pageSize:t,scale:n,minDragPx:o=5,onPreview:i,onCommit:r,onSmallDrag:a}=e;let s=null,l=null;return{onPointerDown:(e,t)=>{var n;s=e,l={origin:{x:e.x,y:e.y},size:{width:0,height:0}},null==i||i(l),null==(n=t.setPointerCapture)||n.call(t)},onPointerMove:e=>{if(!s)return;const n=ko(e.x,0,t.width),o=ko(e.y,0,t.height);l={origin:{x:Math.min(s.x,n),y:Math.min(s.y,o)},size:{width:Math.abs(n-s.x),height:Math.abs(o-s.y)}},null==i||i(l)},onPointerUp:(e,t)=>{var c;l&&(Math.max(l.size.width,l.size.height)*n>o?null==r||r(l):null==a||a()),s=null,l=null,null==i||i(null),null==(c=t.releasePointerCapture)||c.call(t)},onPointerCancel:(e,t)=>{var n;s=null,l=null,null==i||i(null),null==(n=t.releasePointerCapture)||n.call(t)}}}({pageSize:n.size,scale:e.scale,onPreview:e.callback.onPreview,onCommit:t=>{var n,o;this.zoomToArea(e.pageIndex,t,e.documentId),null==(o=(n=e.callback).onCommit)||o.call(n,t)},onSmallDrag:()=>{var t,n;this.zoomIn(e.documentId),null==(n=(t=e.callback).onSmallDrag)||n.call(t)}});return this.interactionManager.registerHandlers({documentId:e.documentId,modeId:"marqueeZoom",handlers:o,pageIndex:e.pageIndex})}onStoreUpdated(e,t){for(const n in t.documents){const o=e.documents[n],i=t.documents[n];o&&i&&(o.currentZoomLevel!==i.currentZoomLevel||o.zoomLevel!==i.zoomLevel||o.isMarqueeZoomActive!==i.isMarqueeZoomActive)&&this.state$.emit({documentId:n,state:i})}}async initialize(){this.logger.info("ZoomPlugin","Initialize","Zoom plugin initialized")}async destroy(){this.zoom$.clear(),this.state$.clear(),super.destroy()}};Ja.id="zoom";let es=Ja;const ts={manifest:Ga,create:(e,t)=>new es(qa,e,t),reducer:(e=Qa,t)=>{switch(t.type){case Va:{const{documentId:n,state:o}=t.payload;return{...e,documents:{...e.documents,[n]:o},activeDocumentId:e.activeDocumentId??n}}case Ka:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i,activeDocumentId:e.activeDocumentId===n?null:e.activeDocumentId}}case"ZOOM/SET_ACTIVE_DOCUMENT":return{...e,activeDocumentId:t.payload};case Za:{const{documentId:n,zoomLevel:o,currentZoomLevel:i}=t.payload,r=e.documents[n];return r?{...e,documents:{...e.documents,[n]:{...r,zoomLevel:o,currentZoomLevel:i}}}:e}case Ya:{const{documentId:n,isActive:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,isMarqueeZoomActive:o}}}:e}default:return e}},initialState:Qa},ns=()=>Oo(es.id);function os(e){const[t,n]=[e[0],e[1]],o=n.clientX-t.clientX,i=n.clientY-t.clientY;return Math.hypot(o,i)}function is(e,t={}){const{provides:n}=Oo("viewport"),{provides:o}=ns(),i=Te(ui),r=De(null);return Pe(()=>{const a=r.current,s=null==i?void 0:i.current;if(a&&s&&o)return function({element:e,container:t,documentId:n,zoomProvides:o,viewportGap:i=0,options:r={}}){const{enablePinch:a=!0,enableWheel:s=!0}=r;if("undefined"==typeof window)return()=>{};const l=o.forDocument(n),c=()=>l.getState();let d=0,u=1,h=!1,m=0,g=null,p=1,f=0,v=0,y=0,b=0,w=0,x=0,C=0,k=0,I=0,S=0,A=0,M=0,P=0;const D=(e,t,n)=>Math.min(Math.max(e,t),n),R=()=>{const n=t.clientWidth-2*i,o=e.offsetWidth,r=o{const t=f*e,n=v*e;let o=I*(1-e);const i=k-t/2-y,r=S-P*e-y,a=Math.max(0,t-C),s=.3*C,l=Math.min(1,a/s);let c=i+(r-i)*l;return n>x-2*M&&(o=D(b+o,x-M-n,M)-b),t>w-2*M&&(c=D(y+c,w-M-t,M)-y),{tx:c,ty:o,blend:l,finalWidth:t}},T=t=>{u=t;const{tx:n,ty:o}=z(t);e.style.transformOrigin="0 0",e.style.transform=`translate(${n}px, ${o}px) scale(${t})`},E=()=>{e.style.transform="none",e.style.transformOrigin="0 0",u=1},_=()=>{const{tx:e,finalWidth:t}=z(u),n=(u-1)*d;let o,i=A;if(t<=C)o=k;else{const t=1-u;o=Math.abs(t)>.001?y+e/t:S}l.requestZoomBy(n,{vx:o,vy:i}),E(),d=0},N=(n,o)=>{const r=t.getBoundingClientRect(),a=e.getBoundingClientRect();M=i,f=a.width,v=a.height,y=a.left-r.left,b=a.top-r.top,w=r.width,x=r.height,C=t.clientWidth,k=t.clientLeft+C/2;const s=n-a.left;I=o-a.top,S=n-r.left,A=o-r.top,P=f{if(2!==e.touches.length)return;h=!0,d=c().currentZoomLevel,m=os(e.touches);const t=function(e){const[t,n]=[e[0],e[1]];return{x:(t.clientX+n.clientX)/2,y:(t.clientY+n.clientY)/2}}(e.touches);N(t.x,t.y),e.preventDefault()},O=e=>{if(!h||2!==e.touches.length)return;const t=os(e.touches);T(t/m),e.preventDefault()},$=e=>{h&&(e.touches.length>=2||(h=!1,_()))},j=e=>{if(!e.ctrlKey&&!e.metaKey)return;e.preventDefault(),null===g?(d=c().currentZoomLevel,p=1,N(e.clientX,e.clientY)):clearTimeout(g);const t=1-.01*e.deltaY;p*=t,p=Math.max(.1,Math.min(10,p)),T(p),g=setTimeout(()=>{g=null,_(),p=1},150)},F=l.onStateChange(()=>R()),U=new ResizeObserver(()=>R());return U.observe(e),U.observe(t),R(),a&&(t.addEventListener("touchstart",L,{passive:!1}),t.addEventListener("touchmove",O,{passive:!1}),t.addEventListener("touchend",$),t.addEventListener("touchcancel",$)),s&&t.addEventListener("wheel",j,{passive:!1}),()=>{a&&(t.removeEventListener("touchstart",L),t.removeEventListener("touchmove",O),t.removeEventListener("touchend",$),t.removeEventListener("touchcancel",$)),s&&t.removeEventListener("wheel",j),g&&clearTimeout(g),F(),U.disconnect(),E(),e.style.marginLeft=""}}({element:a,container:s,documentId:e,zoomProvides:o,viewportGap:(null==n?void 0:n.getViewportGap())||0,options:t})},[n,o,e,i,t.enablePinch,t.enableWheel]),{elementRef:r}}function rs({children:e,documentId:t,style:n,enablePinch:o=!0,enableWheel:i=!0,...r}){const a=Re(()=>({enablePinch:o,enableWheel:i}),[o,i]),{elementRef:s}=is(t,a);return He("div",{ref:s,...r,style:{...n,display:"inline-block",overflow:"visible",boxSizing:"border-box"},children:e})}const as=({documentId:e,pageIndex:t,scale:n,className:o,stroke:i="rgba(33,150,243,0.8)",fill:r="rgba(33,150,243,0.15)"})=>{const{provides:a}=ns(),s=jo(e),[l,c]=Se(null),d=Re(()=>void 0!==n?n:(null==s?void 0:s.scale)??1,[n,null==s?void 0:s.scale]);return Me(()=>{if(a)return a.registerMarqueeOnPage({documentId:e,pageIndex:t,scale:d,callback:{onPreview:c}})},[a,e,t,d]),l?He("div",{style:{position:"absolute",pointerEvents:"none",left:l.origin.x*d,top:l.origin.y*d,width:l.size.width*d,height:l.size.height*d,border:`1px solid ${i}`,background:r,boxSizing:"border-box"},className:o}):null},ss=class extends bo{constructor(e,t,n){super(e,t),this.config=n}buildCapability(){return{renderPage:e=>this.renderPage(e),renderPageRect:e=>this.renderPageRect(e),renderPageRaw:e=>this.renderPageRaw(e),renderPageRectRaw:e=>this.renderPageRectRaw(e),forDocument:e=>this.createRenderScope(e)}}createRenderScope(e){return{renderPage:t=>this.renderPage(t,e),renderPageRect:t=>this.renderPageRect(t,e),renderPageRaw:t=>this.renderPageRaw(t,e),renderPageRectRaw:t=>this.renderPageRectRaw(t,e)}}renderPage({pageIndex:e,options:t},n){const o=n??this.getActiveDocumentId(),i=this.coreState.core.documents[o];if(!(null==i?void 0:i.document))throw new Error(`Document ${o} not loaded`);const r=i.document.pages.find(t=>t.index===e);if(!r)throw new Error(`Page ${e} not found in document ${o}`);const a={...t??{},withForms:(null==t?void 0:t.withForms)??this.config.withForms??!1,withAnnotations:(null==t?void 0:t.withAnnotations)??this.config.withAnnotations??!1,imageType:(null==t?void 0:t.imageType)??this.config.defaultImageType??"image/png",imageQuality:(null==t?void 0:t.imageQuality)??this.config.defaultImageQuality??.92};return this.engine.renderPage(i.document,r,a)}renderPageRect({pageIndex:e,rect:t,options:n},o){const i=o??this.getActiveDocumentId(),r=this.coreState.core.documents[i];if(!(null==r?void 0:r.document))throw new Error(`Document ${i} not loaded`);const a=r.document.pages.find(t=>t.index===e);if(!a)throw new Error(`Page ${e} not found in document ${i}`);const s={...n??{},withForms:(null==n?void 0:n.withForms)??this.config.withForms??!1,withAnnotations:(null==n?void 0:n.withAnnotations)??this.config.withAnnotations??!1,imageType:(null==n?void 0:n.imageType)??this.config.defaultImageType??"image/png",imageQuality:(null==n?void 0:n.imageQuality)??this.config.defaultImageQuality??.92};return this.engine.renderPageRect(r.document,a,t,s)}renderPageRaw({pageIndex:e,options:t},n){const o=n??this.getActiveDocumentId(),i=this.coreState.core.documents[o];if(!(null==i?void 0:i.document))throw new Error(`Document ${o} not loaded`);const r=i.document.pages.find(t=>t.index===e);if(!r)throw new Error(`Page ${e} not found in document ${o}`);const a={...t??{},withForms:(null==t?void 0:t.withForms)??this.config.withForms??!1,withAnnotations:(null==t?void 0:t.withAnnotations)??this.config.withAnnotations??!1};return this.engine.renderPageRaw(i.document,r,a)}renderPageRectRaw({pageIndex:e,rect:t,options:n},o){const i=o??this.getActiveDocumentId(),r=this.coreState.core.documents[i];if(!(null==r?void 0:r.document))throw new Error(`Document ${i} not loaded`);const a=r.document.pages.find(t=>t.index===e);if(!a)throw new Error(`Page ${e} not found in document ${i}`);const s={...n??{},withForms:(null==n?void 0:n.withForms)??this.config.withForms??!1,withAnnotations:(null==n?void 0:n.withAnnotations)??this.config.withAnnotations??!1};return this.engine.renderPageRectRaw(r.document,a,t,s)}async initialize(e){this.logger.info("RenderPlugin","Initialize","Render plugin initialized")}async destroy(){super.destroy()}};ss.id="render";let ls=ss;const cs="render",ds={manifest:{id:cs,name:"Render Plugin",version:"1.0.0",provides:["render"],requires:[],optional:[],defaultConfig:{}},create:(e,t)=>new ls(cs,e,t),reducer:()=>{},initialState:{}};function us({documentId:e,pageIndex:t,scale:n,dpr:o,style:i,...r}){const{provides:a}=Oo(ls.id),s=jo(e),[l,c]=Se(null),d=De(null),u=Re(()=>s&&s.pageRefreshVersions[t]||0,[s,t]),h=Re(()=>void 0!==n?n:(null==s?void 0:s.scale)??1,[n,null==s?void 0:s.scale]),m=Re(()=>void 0!==o?o:window.devicePixelRatio,[o]);Me(()=>{if(!a)return;const n=a.forDocument(e).renderPage({pageIndex:t,options:{scaleFactor:h,dpr:m}});return n.wait(e=>{const t=URL.createObjectURL(e);c(t),d.current=t},Ln),()=>{d.current?(URL.revokeObjectURL(d.current),d.current=null):n.abort({code:tn.Cancelled,message:"canceled render task"})}},[e,t,h,m,a,u]);return He(H,{children:l&&He("img",{src:l,onLoad:()=>{d.current&&(URL.revokeObjectURL(d.current),d.current=null)},...r,style:{width:"100%",height:"100%",...i||{}}})})}const hs="rotate",ms={id:hs,name:"Rotate Plugin",version:"1.0.0",provides:["rotate"],requires:[],optional:[],defaultConfig:{}};const gs="ROTATE/INIT_STATE",ps="ROTATE/CLEANUP_STATE",fs="ROTATE/SET_ROTATION";const vs=class extends bo{constructor(e,t,n){super(e,t),this.rotate$=Do(),this.defaultRotation=n.defaultRotation??0}onDocumentLoadingStarted(e){const t={rotation:this.defaultRotation};this.dispatch(function(e,t){return{type:gs,payload:{documentId:e,state:t}}}(e,t)),this.dispatchCoreAction(ao(this.defaultRotation,e)),this.logger.debug("RotatePlugin","DocumentOpened",`Initialized rotation state for document: ${e}`)}onDocumentClosed(e){this.dispatch(function(e){return{type:ps,payload:e}}(e)),this.logger.debug("RotatePlugin","DocumentClosed",`Cleaned up rotation state for document: ${e}`)}buildCapability(){return{setRotation:e=>this.setRotationForDocument(e),getRotation:()=>this.getRotationForDocument(),rotateForward:()=>this.rotateForward(),rotateBackward:()=>this.rotateBackward(),forDocument:e=>this.createRotateScope(e),onRotateChange:this.rotate$.on}}createRotateScope(e){return{setRotation:t=>this.setRotationForDocument(t,e),getRotation:()=>this.getRotationForDocument(e),rotateForward:()=>this.rotateForward(e),rotateBackward:()=>this.rotateBackward(e),onRotateChange:t=>this.rotate$.on(n=>{n.documentId===e&&t(n.rotation)})}}getDocumentState(e){const t=e??this.getActiveDocumentId();return this.state.documents[t]??null}getDocumentStateOrThrow(e){const t=this.getDocumentState(e);if(!t)throw new Error(`Rotation state not found for document: ${e??"active"}`);return t}setRotationForDocument(e,t){const n=t??this.getActiveDocumentId(),o=this.coreState.core.documents[n];if(!(null==o?void 0:o.document))throw new Error(`Document ${n} not loaded`);this.dispatch(function(e,t){return{type:fs,payload:{documentId:e,rotation:t}}}(n,e)),this.dispatchCoreAction(ao(e,n)),this.rotate$.emit({documentId:n,rotation:e})}getRotationForDocument(e){return this.getDocumentStateOrThrow(e).rotation}rotateForward(e){const t=e??this.getActiveDocumentId(),n=this.getRotationForDocument(t),o=(n+1)%4;this.setRotationForDocument(o,t)}rotateBackward(e){const t=e??this.getActiveDocumentId(),n=this.getRotationForDocument(t),o=(n+3)%4;this.setRotationForDocument(o,t)}getMatrixAsString(e){return function(e,t,n){const[o,i,r,a,s,l]=function(e,t,n){let o=1,i=0,r=0,a=1,s=0,l=0;switch(e){case 1:o=0,i=1,r=-1,a=0,s=n;break;case 2:o=-1,i=0,r=0,a=-1,s=t,l=n;break;case 3:o=0,i=-1,r=1,a=0,l=t}return[o,i,r,a,s,l]}(e,t,n);return`matrix(${o},${i},${r},${a},${s},${l})`}(e.rotation,e.width,e.height)}onStoreUpdated(e,t){for(const n in t.documents){const o=e.documents[n],i=t.documents[n];(null==o?void 0:o.rotation)!==i.rotation&&this.logger.debug("RotatePlugin","RotationChanged",`Rotation changed for document ${n}: ${(null==o?void 0:o.rotation)??0} -> ${i.rotation}`)}}async initialize(e){this.logger.info("RotatePlugin","Initialize","Rotate plugin initialized")}async destroy(){this.rotate$.clear(),super.destroy()}};vs.id="rotate";let ys=vs;const bs={documents:{},activeDocumentId:null},ws={manifest:ms,create:(e,t)=>new ys(hs,e,t),reducer:(e=bs,t)=>{switch(t.type){case gs:{const{documentId:n,state:o}=t.payload;return{...e,documents:{...e.documents,[n]:o},activeDocumentId:e.activeDocumentId??n}}case ps:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i,activeDocumentId:e.activeDocumentId===n?null:e.activeDocumentId}}case"ROTATE/SET_ACTIVE_DOCUMENT":return{...e,activeDocumentId:t.payload};case fs:{const{documentId:n,rotation:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,rotation:o}}}:e}default:return e}},initialState:bs};function xs({children:e,documentId:t,pageIndex:n,rotation:o,scale:i,style:r,...a}){var s,l,c,d;const{plugin:u}=Lo(ys.id),h=jo(t),m=null==(l=null==(s=null==h?void 0:h.document)?void 0:s.pages)?void 0:l[n],g=(null==(c=null==m?void 0:m.size)?void 0:c.width)??0,p=(null==(d=null==m?void 0:m.size)?void 0:d.height)??0,f=(null==m?void 0:m.rotation)??0,v=(null==h?void 0:h.rotation)??0,y=void 0!==o?o:(f+v)%4,b=i??(null==h?void 0:h.scale)??1,w=(null==u?void 0:u.getMatrixAsString({width:g*b,height:p*b,rotation:y}))??"matrix(1, 0, 0, 1, 0, 0)";return m?He("div",{...a,style:{position:"absolute",transformOrigin:"0 0",transform:w,...r},children:e}):null}const Cs="SEARCH/INIT_STATE",ks="SEARCH/CLEANUP_STATE",Is="SEARCH/START_SEARCH_SESSION",Ss="SEARCH/STOP_SEARCH_SESSION",As="SEARCH/SET_SEARCH_FLAGS",Ms="SEARCH/SET_SHOW_ALL_RESULTS",Ps="SEARCH/START_SEARCH",Ds="SEARCH/SET_SEARCH_RESULTS",Rs="SEARCH/APPEND_SEARCH_RESULTS",zs="SEARCH/SET_ACTIVE_RESULT_INDEX";function Ts(e,t){return{type:Ms,payload:{documentId:e,showAll:t}}}function Es(e,t,n,o){return{type:Ds,payload:{documentId:e,results:t,total:n,activeResultIndex:o}}}function _s(e,t){return{type:zs,payload:{documentId:e,index:t}}}const Ns={flags:[],results:[],total:0,activeResultIndex:-1,showAllResults:!0,query:"",loading:!1,active:!1},Ls={documents:{}},Os=(e,t,n)=>{const o=e.documents[t]||Ns;return{...e,documents:{...e.documents,[t]:{...o,...n}}}},$s=class extends bo{constructor(e,t,n){super(e,t),this.searchStop$=Do(),this.searchStart$=Do(),this.searchResult$=Do(),this.searchActiveResultChange$=Do(),this.searchResultState$=Do(),this.searchState$=Do(),this.currentTask=new Map,this.pluginConfig=n}onDocumentLoadingStarted(e){const t={...Ns,flags:this.pluginConfig.flags||[],showAllResults:this.pluginConfig.showAllResults??!0};this.dispatch(function(e,t){return{type:Cs,payload:{documentId:e,state:t}}}(e,t))}onDocumentClosed(e){this.stopSearchSession(e),this.dispatch(function(e){return{type:ks,payload:e}}(e)),this.currentTask.delete(e)}async initialize(){}onStoreUpdated(e,t){for(const n in t.documents){const o=e.documents[n],i=t.documents[n];o!==i&&(this.searchState$.emit({documentId:n,state:i}),o&&o.results===i.results&&o.activeResultIndex===i.activeResultIndex&&o.showAllResults===i.showAllResults&&o.active===i.active||this.searchResultState$.emit({documentId:n,state:{results:i.results,activeResultIndex:i.activeResultIndex,showAllResults:i.showAllResults,active:i.active}}))}}buildCapability(){const e=e=>e??this.getActiveDocumentId(),t=t=>{const n=e(t),o=this.state.documents[n];if(!o)throw new Error(`Search state not found for document ${n}`);return o};return{startSearch:t=>this.startSearchSession(e(t)),stopSearch:t=>this.stopSearchSession(e(t)),searchAllPages:(t,n)=>this.searchAllPages(t,e(n)),nextResult:t=>this.nextResult(e(t)),previousResult:t=>this.previousResult(e(t)),goToResult:(t,n)=>this.goToResult(t,e(n)),setShowAllResults:(t,n)=>this.dispatch(Ts(e(n),t)),getShowAllResults:e=>t(e).showAllResults,getFlags:e=>t(e).flags,setFlags:(t,n)=>this.setFlags(t,e(n)),getState:e=>t(e),forDocument:this.createSearchScope.bind(this),onSearchResult:this.searchResult$.on,onSearchStart:this.searchStart$.on,onSearchStop:this.searchStop$.on,onActiveResultChange:this.searchActiveResultChange$.on,onSearchResultStateChange:this.searchResultState$.on,onStateChange:this.searchState$.on}}createSearchScope(e){const t=()=>{const t=this.state.documents[e];if(!t)throw new Error(`Search state not found for document ${e}`);return t};return{startSearch:()=>this.startSearchSession(e),stopSearch:()=>this.stopSearchSession(e),searchAllPages:t=>this.searchAllPages(t,e),nextResult:()=>this.nextResult(e),previousResult:()=>this.previousResult(e),goToResult:t=>this.goToResult(t,e),setShowAllResults:t=>this.dispatch(Ts(e,t)),getShowAllResults:()=>t().showAllResults,getFlags:()=>t().flags,setFlags:t=>this.setFlags(t,e),getState:t,onSearchResult:t=>this.searchResult$.on(n=>{n.documentId===e&&t(n.results)}),onSearchStart:t=>this.searchStart$.on(n=>{n.documentId===e&&t()}),onSearchStop:t=>this.searchStop$.on(n=>{n.documentId===e&&t()}),onActiveResultChange:t=>this.searchActiveResultChange$.on(n=>{n.documentId===e&&t(n.index)}),onSearchResultStateChange:t=>this.searchResultState$.on(n=>{n.documentId===e&&t(n.state)}),onStateChange:t=>this.searchState$.on(n=>{n.documentId===e&&t(n.state)})}}setFlags(e,t){this.dispatch(function(e,t){return{type:As,payload:{documentId:e,flags:t}}}(t,e));const n=this.state.documents[t];(null==n?void 0:n.active)&&this.searchAllPages(n.query,t,!0)}notifySearchStart(e){this.searchStart$.emit({documentId:e})}notifySearchStop(e){this.searchStop$.emit({documentId:e})}notifyActiveResultChange(e,t){this.searchActiveResultChange$.emit({documentId:e,index:t})}startSearchSession(e){this.getCoreDocument(e)&&(this.dispatch(function(e){return{type:Is,payload:{documentId:e}}}(e)),this.notifySearchStart(e))}stopSearchSession(e){var t;const n=this.state.documents[e];if(!(null==n?void 0:n.active))return;const o=this.currentTask.get(e);if(o){try{null==(t=o.abort)||t.call(o,{code:tn.Cancelled,message:"search stopped"})}catch{}this.currentTask.delete(e)}this.dispatch(function(e){return{type:Ss,payload:{documentId:e}}}(e)),this.notifySearchStop(e)}searchAllPages(e,t,n=!1){var o;const i=this.state.documents[t];if(!i)return nn.reject({code:tn.NotFound,message:"Search state not initialized"});const r=this.getCoreDocument(t);if(!(null==r?void 0:r.document))return nn.reject({code:tn.NotFound,message:"Document not loaded"});const a=e.trim();if(i.query===a&&!n)return nn.resolve({results:i.results,total:i.total});const s=this.currentTask.get(t);if(s){try{null==(o=s.abort)||o.call(s,{code:tn.Cancelled,message:"new search"})}catch{}this.currentTask.delete(t)}if(this.dispatch(function(e,t){return{type:Ps,payload:{documentId:e,query:t}}}(t,a)),!a)return this.dispatch(Es(t,[],0,-1)),nn.resolve({results:[],total:0});i.active||this.startSearchSession(t);const l=this.engine.searchAllPages(r.document,a,{flags:i.flags});return this.currentTask.set(t,l),l.onProgress(e=>{var n;(null==(n=null==e?void 0:e.results)?void 0:n.length)&&this.currentTask.get(t)===l&&(this.dispatch(function(e,t){return{type:Rs,payload:{documentId:e,results:t}}}(t,e.results)),-1===this.state.documents[t].activeResultIndex&&(this.dispatch(_s(t,0)),this.notifyActiveResultChange(t,0)))}),l.wait(e=>{this.currentTask.delete(t);const n=e.total>0?0:-1;this.dispatch(Es(t,e.results,e.total,n)),this.searchResult$.emit({documentId:t,results:e}),e.total>0&&this.notifyActiveResultChange(t,0)},e=>{var n;(null==(n=null==e?void 0:e.reason)?void 0:n.code)!==tn.Cancelled&&(console.error("Error during search:",e),this.dispatch(Es(t,[],0,-1))),this.currentTask.delete(t)}),l}nextResult(e){const t=this.state.documents[e];if(!t||0===t.results.length)return-1;const n=t.activeResultIndex>=t.results.length-1?0:t.activeResultIndex+1;return this.goToResult(n,e)}previousResult(e){const t=this.state.documents[e];if(!t||0===t.results.length)return-1;const n=t.activeResultIndex<=0?t.results.length-1:t.activeResultIndex-1;return this.goToResult(n,e)}goToResult(e,t){const n=this.state.documents[t];return!n||0===n.results.length||e<0||e>=n.results.length?-1:(this.dispatch(_s(t,e)),this.notifyActiveResultChange(t,e),e)}async destroy(){for(const e of Object.keys(this.state.documents))this.stopSearchSession(e);this.searchResult$.clear(),this.searchStart$.clear(),this.searchStop$.clear(),this.searchActiveResultChange$.clear(),this.searchResultState$.clear(),this.searchState$.clear(),super.destroy()}};$s.id="search";let js=$s;const Fs="search",Us={manifest:{id:Fs,name:"Search Plugin",version:"1.0.0",provides:["search"],requires:[],optional:[],defaultConfig:{flags:[]}},create:(e,t)=>new js(Fs,e,t),reducer:(e=Ls,t)=>{switch(t.type){case Cs:return{...e,documents:{...e.documents,[t.payload.documentId]:t.payload.state}};case ks:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i}}case Is:return Os(e,t.payload.documentId,{active:!0});case Ss:return Os(e,t.payload.documentId,{results:[],total:0,activeResultIndex:-1,query:"",loading:!1,active:!1});case As:return Os(e,t.payload.documentId,{flags:t.payload.flags});case Ms:return Os(e,t.payload.documentId,{showAllResults:t.payload.showAll});case Ps:return Os(e,t.payload.documentId,{loading:!0,query:t.payload.query,results:[],total:0,activeResultIndex:-1});case Rs:{const{documentId:n,results:o}=t.payload,i=e.documents[n];if(!i)return e;const r=[...i.results,...o],a=-1===i.activeResultIndex&&r.length>0?0:i.activeResultIndex;return Os(e,n,{results:r,total:r.length,activeResultIndex:a,loading:!0})}case Ds:{const{documentId:n,results:o,total:i,activeResultIndex:r}=t.payload;return Os(e,n,{results:o,total:i,activeResultIndex:r,loading:!1})}case zs:return Os(e,t.payload.documentId,{activeResultIndex:t.payload.index});default:return e}},initialState:Ls},Hs=()=>Oo(js.id);function Ws({documentId:e,pageIndex:t,scale:n,style:o,highlightColor:i="#FFFF00",activeHighlightColor:r="#FFBF00",...a}){const{provides:s}=Hs(),[l,c]=Se(null),d=jo(e),u=Re(()=>null==s?void 0:s.forDocument(e),[s,e]),h=Re(()=>void 0!==n?n:(null==d?void 0:d.scale)??1,[n,null==d?void 0:d.scale]);if(Me(()=>{if(!u)return void c(null);const e=u.getState();return c({results:e.results,activeResultIndex:e.activeResultIndex,showAllResults:e.showAllResults,active:e.active}),u.onSearchResultStateChange(e=>{c(e)})},[u]),!l||!l.active)return null;return He("div",{style:{...o,pointerEvents:"none"},...a,children:l.results.map((e,t)=>({result:e,originalIndex:t})).filter(({result:e})=>e.pageIndex===t).filter(({originalIndex:e})=>l.showAllResults||e===l.activeResultIndex).map(({result:e,originalIndex:t})=>e.rects.map((e,n)=>He("div",{style:{position:"absolute",top:e.origin.y*h,left:e.origin.x*h,width:e.size.width*h,height:e.size.height*h,backgroundColor:t===l.activeResultIndex?r:i,mixBlendMode:"multiply",transform:"scale(1.02)",transformOrigin:"center",transition:"opacity .3s ease-in-out",opacity:1}},`${t}-${n}`)))})}const Bs="selection",qs={id:Bs,name:"Selection Plugin",version:"1.0.0",provides:["selection"],requires:["interaction-manager"],optional:["viewport","scroll"],defaultConfig:{menuHeight:40}},Gs="SELECTION/INIT_STATE",Vs="SELECTION/CLEANUP_STATE",Ks="SELECTION/CACHE_PAGE_GEOMETRY",Zs="SELECTION/SET_SELECTION",Ys="SELECTION/START_SELECTION",Xs="SELECTION/END_SELECTION",Qs="SELECTION/CLEAR_SELECTION",Js="SELECTION/SET_RECTS",el="SELECTION/SET_SLICES",tl="SELECTION/EVICT_PAGE_GEOMETRY",nl=(e,t)=>({type:Zs,payload:{documentId:e,selection:t}}),ol=e=>({type:Ys,payload:{documentId:e}}),il=e=>({type:Xs,payload:{documentId:e}}),rl=(e,t)=>({type:Js,payload:{documentId:e,rects:t}}),al=(e,t)=>({type:el,payload:{documentId:e,slices:t}}),sl={geometry:{},rects:{},slices:{},selection:null,active:!1,selecting:!1},ll={documents:{}},cl=(e,t,n)=>({...e,documents:{...e.documents,[t]:n}});function dl(e,t){return e.rects[t]??[]}function ul(e,t){return rt(dl(e,t))}function hl(e){const t=[],n=e.rects;for(const e in n){const o=Number(e),i=rt(n[o]);i&&t.push({page:o,rect:i})}return t}function ml(e,t){const n=e.rects[t]||[];if(0===n.length)return null;const o=ul(e,t);return o?{pageIndex:t,rect:o,segmentRects:n}:null}function gl(e){const t=[],n=Object.keys(e.rects).map(Number);for(const o of n){const n=e.rects[o]||[];if(0===n.length)continue;const i=ul(e,o);i&&t.push({pageIndex:o,rect:i,segmentRects:n})}return t}function pl(e,t,n=1.5){for(const n of e.runs){if(!(t.y>=n.rect.y&&t.y<=n.rect.y+n.rect.height&&t.x>=n.rect.x&&t.x<=n.rect.x+n.rect.width))continue;const e=n.glyphs.findIndex(e=>{const n=e.tightX??e.x,o=e.tightY??e.y,i=e.tightWidth??e.width,r=e.tightHeight??e.height;return t.x>=n&&t.x<=n+i&&t.y>=o&&t.y<=o+r});if(-1!==e)return n.charStart+e}if(n<=0)return-1;const o=function(e,t){let n=0,o=0;for(const t of e.runs)for(const e of t.glyphs)2!==e.flags&&(n+=e.height,o++);return 0===o?0:n/o*t}(e,n),i=o/2;let r=-1,a=1/0;for(const n of e.runs)if(!(t.yn.rect.y+n.rect.height+i||t.xn.rect.x+n.rect.width+i))for(let e=0;eh||t.yg)continue;const p=Math.min(Math.abs(t.x-s),Math.abs(t.x-(s+c)))+Math.min(Math.abs(t.y-l),Math.abs(t.y-(l+d)));pe.end.page)return null;const o=n===e.start.page?e.start.index:0,i=t.runs[t.runs.length-1],r=i.charStart+i.glyphs.length-1;return{from:o,to:n===e.end.page?e.end.index:r}}function vl(e,t,n,o=!0){const i=[];for(const o of e.runs){const e=o.charStart,r=e+o.glyphs.length-1;if(rn)continue;const a=Math.max(t,e)-e,s=Math.min(n,r)-e;let l=1/0,c=-1/0,d=1/0,u=-1/0,h=0,m=0,g=-1/0;const p=()=>{l!==1/0&&h>0&&i.push({rect:{origin:{x:l,y:d},size:{width:c-l,height:u-d}},charCount:h,fontSize:o.fontSize}),l=1/0,c=-1/0,d=1/0,u=-1/0,h=0,m=0,g=-1/0};for(let e=a;e<=s;e++){const t=o.glyphs[e];if(2!==t.flags){if(h>0&&g>-1/0){const e=Math.abs(t.x-g),n=m/h;n>0&&e>2.5*n&&p()}l=Math.min(l,t.x),c=Math.max(c,t.x+t.width),d=Math.min(d,t.y),u=Math.max(u,t.y+t.height),h++,m+=t.width,g=t.x+t.width}}p()}return o?function(e){const t=[];let n=null,o=null;for(const i of e)n&&o?xl(n,i)?o=yl(o,i.rect):(t.push(o),o=i.rect):o=i.rect,n=i;o&&!bl(o)&&t.push(o);return t}(i):i.map(e=>e.rect)}function yl(e,t){const n=Math.min(e.origin.x,t.origin.x),o=Math.min(e.origin.y,t.origin.y);return{origin:{x:n,y:o},size:{width:Math.max(e.origin.x+e.size.width,t.origin.x+t.size.width)-n,height:Math.max(e.origin.y+e.size.height,t.origin.y+t.size.height)-o}}}function bl(e){return e.size.width<=0||e.size.height<=0}function wl(e,t){if(bl(e)||bl(t))return 0;const n=yl(e,t);if(n.size.height===e.size.height||n.size.height===t.size.height)return 1;const o=function(e,t){const n=Math.max(e.origin.x,t.origin.x),o=Math.max(e.origin.y,t.origin.y),i=Math.min(e.origin.x+e.size.width,t.origin.x+t.size.width),r=Math.min(e.origin.y+e.size.height,t.origin.y+t.size.height);return{origin:{x:n,y:o},size:{width:Math.max(0,i-n),height:Math.max(0,r-o)}}}(e,t);return o.size.height/n.size.height}function xl(e,t){if(null!=e.fontSize&&null!=t.fontSize&&e.fontSize>0&&t.fontSize>0){if(Math.max(e.fontSize,t.fontSize)/Math.min(e.fontSize,t.fontSize)>1.5)return!1}const n=e.rect,o=t.rect;if(wl(n,o)<.8)return!1;const i=1*n.size.width/e.charCount,r=1*o.size.width/t.charCount,a=n.origin.x-i,s=n.origin.x+n.size.width+i,l=o.origin.x-r;return al}function Cl(e,t){for(let n=0;n=0&&i=.5}const Al=class extends bo{constructor(e,t,n){var o,i,r;super(e,t),this.enabledModesPerDoc=new Map,this.selecting=new Map,this.anchor=new Map,this.hasTextAnchor=new Map,this.marqueePage=new Map,this.pageCallbacks=new Map,this.geoAccessOrder=new Map,this.menuPlacement$=Ro((e,t)=>({documentId:e,placement:t})),this.selChange$=Ro((e,t)=>({documentId:e,selection:t,modeId:this.interactionManagerCapability.forDocument(e).getActiveMode()})),this.textRetrieved$=Ro((e,t)=>({documentId:e,text:t})),this.copyToClipboard$=Ro((e,t)=>({documentId:e,text:t}),{cache:!1}),this.beginSelection$=Ro((e,t)=>({documentId:e,page:t.page,index:t.index,modeId:t.modeId}),{cache:!1}),this.endSelection$=Ro((e,t)=>({documentId:e,modeId:t.modeId}),{cache:!1}),this.marqueeChange$=Ro((e,t)=>({documentId:e,pageIndex:t.pageIndex,rect:t.rect,modeId:t.modeId}),{cache:!1}),this.marqueeEnd$=Ro((e,t)=>({documentId:e,pageIndex:t.pageIndex,rect:t.rect,modeId:t.modeId}),{cache:!1}),this.emptySpaceClick$=Ro((e,t)=>({documentId:e,pageIndex:t.pageIndex,modeId:t.modeId}),{cache:!1}),this.viewportCapability=null,this.scrollCapability=null,this.config=n,this.menuHeight=n.menuHeight??40;const a=t.getPlugin("interaction-manager");if(!a)throw new Error("SelectionPlugin: InteractionManagerPlugin is required.");this.interactionManagerCapability=a.provides(),this.viewportCapability=(null==(o=t.getPlugin("viewport"))?void 0:o.provides())??null,this.scrollCapability=(null==(i=t.getPlugin("scroll"))?void 0:i.provides())??null,this.coreStore.onAction(Jn,e=>{const{documentId:t,pageIndexes:n}=e.payload,o=n.map(e=>this.getNewPageGeometryAndCache(t,e));Ct.all(o).wait(()=>{n.forEach(e=>{this.notifyPage(t,e)})},Ln)}),null==(r=this.viewportCapability)||r.onViewportChange(e=>{this.recalculateMenuPlacement(e.documentId)},{mode:"throttle",wait:100})}onDocumentLoadingStarted(e){var t;this.dispatch(((e,t)=>({type:Gs,payload:{documentId:e,state:t}}))(e,sl));const n=!1!==(null==(t=this.config.marquee)?void 0:t.enabled);this.enabledModesPerDoc.set(e,new Map([["pointerMode",{enableSelection:!0,showSelectionRects:!0,enableMarquee:n,showMarqueeRects:!0}]])),this.pageCallbacks.set(e,new Map),this.geoAccessOrder.set(e,[]),this.selecting.set(e,!1),this.anchor.set(e,void 0),this.hasTextAnchor.set(e,!1)}onDocumentClosed(e){this.dispatch((e=>({type:Vs,payload:e}))(e)),this.enabledModesPerDoc.delete(e),this.pageCallbacks.delete(e),this.geoAccessOrder.delete(e),this.selecting.delete(e),this.hasTextAnchor.delete(e),this.anchor.delete(e),this.marqueePage.delete(e),this.selChange$.clearScope(e),this.textRetrieved$.clearScope(e),this.copyToClipboard$.clearScope(e),this.beginSelection$.clearScope(e),this.endSelection$.clearScope(e),this.menuPlacement$.clearScope(e),this.marqueeChange$.clearScope(e),this.marqueeEnd$.clearScope(e),this.emptySpaceClick$.clearScope(e)}async initialize(){}async destroy(){this.selChange$.clear(),this.textRetrieved$.clear(),this.copyToClipboard$.clear(),this.beginSelection$.clear(),this.endSelection$.clear(),this.menuPlacement$.clear(),this.marqueeChange$.clear(),this.marqueeEnd$.clear(),this.emptySpaceClick$.clear(),super.destroy()}buildCapability(){const e=e=>e??this.getActiveDocumentId();return{getFormattedSelection:t=>gl(this.getDocumentState(e(t))),getFormattedSelectionForPage:(t,n)=>ml(this.getDocumentState(e(n)),t),getHighlightRectsForPage:(t,n)=>dl(this.getDocumentState(e(n)),t),getHighlightRects:t=>this.getDocumentState(e(t)).rects,getBoundingRectForPage:(t,n)=>ul(this.getDocumentState(e(n)),t),getBoundingRects:t=>hl(this.getDocumentState(e(t))),getSelectedText:t=>this.getSelectedText(e(t)),clear:t=>this.clearSelection(e(t)),copyToClipboard:t=>this.copyToClipboard(e(t)),getState:t=>this.getDocumentState(e(t)),enableForMode:(t,n,o)=>{var i;return null==(i=this.enabledModesPerDoc.get(e(o)))?void 0:i.set(t,{...n})},isEnabledForMode:(t,n)=>{var o;return(null==(o=this.enabledModesPerDoc.get(e(n)))?void 0:o.has(t))??!1},setMarqueeEnabled:(t,n)=>this.setMarqueeEnabled(e(n),t),isMarqueeEnabled:t=>this.isMarqueeEnabled(e(t)),forDocument:this.createSelectionScope.bind(this),onCopyToClipboard:this.copyToClipboard$.onGlobal,onSelectionChange:this.selChange$.onGlobal,onTextRetrieved:this.textRetrieved$.onGlobal,onBeginSelection:this.beginSelection$.onGlobal,onEndSelection:this.endSelection$.onGlobal,onMarqueeChange:this.marqueeChange$.onGlobal,onMarqueeEnd:this.marqueeEnd$.onGlobal,onEmptySpaceClick:this.emptySpaceClick$.onGlobal}}createSelectionScope(e){return{getFormattedSelection:()=>gl(this.getDocumentState(e)),getFormattedSelectionForPage:t=>ml(this.getDocumentState(e),t),getHighlightRectsForPage:t=>dl(this.getDocumentState(e),t),getHighlightRects:()=>this.getDocumentState(e).rects,getBoundingRectForPage:t=>ul(this.getDocumentState(e),t),getBoundingRects:()=>hl(this.getDocumentState(e)),getSelectedText:()=>this.getSelectedText(e),clear:()=>this.clearSelection(e),copyToClipboard:()=>this.copyToClipboard(e),getState:()=>this.getDocumentState(e),setMarqueeEnabled:t=>this.setMarqueeEnabled(e,t),isMarqueeEnabled:()=>this.isMarqueeEnabled(e),onSelectionChange:this.selChange$.forScope(e),onTextRetrieved:this.textRetrieved$.forScope(e),onCopyToClipboard:this.copyToClipboard$.forScope(e),onBeginSelection:this.beginSelection$.forScope(e),onEndSelection:this.endSelection$.forScope(e),onMarqueeChange:this.marqueeChange$.forScope(e),onMarqueeEnd:this.marqueeEnd$.forScope(e),onEmptySpaceClick:this.emptySpaceClick$.forScope(e)}}getDocumentState(e){const t=this.state.documents[e];if(!t)throw new Error(`Selection state not found for document: ${e}`);return t}onMenuPlacement(e,t){return this.menuPlacement$.forScope(e)(t)}registerSelectionOnPage(e){var t;const{documentId:n,pageIndex:o,onRectsChange:i}=e,r=this.state.documents[n];if(!r)return this.logger.warn("SelectionPlugin","RegisterFailed",`Cannot register selection on page ${o} for document ${n}: document state not initialized.`),()=>{};null==(t=this.pageCallbacks.get(n))||t.set(o,i);const a=this.getOrLoadGeometry(n,o),s=this.interactionManagerCapability.forDocument(n),l=this.enabledModesPerDoc.get(n);i({rects:dl(r,o),boundingRect:ul(r,o)}),a.wait(e=>{const t=this.getDocumentState(n),i=t.selection;if(!i||oi.end.page)return;const r=fl(i,e,o);if(!r)return;const a=vl(e,r.from,r.to);this.dispatch(rl(n,{...t.rects,[o]:a})),this.dispatch(al(n,{...t.slices,[o]:{start:r.from,count:r.to-r.from+1}})),this.notifyPage(n,o)},Ln);const c=function(e){const t=e.minDragDistance??3,n=e.toleranceFactor??1.5;let o=null,i=null,r=!1,a=0;function s(){var t;o=null,i=null,r=!1,null==(t=e.setHasTextAnchor)||t.call(e,!1)}return{onPointerDown:(t,s,l)=>{var c,d;if(s.target===s.currentTarget&&(null==(c=e.onEmptySpaceClick)||c.call(e,l)),!e.isEnabled(l))return;const u=Date.now();(0===a||u-a>=500)&&e.onClear(l);const h=e.getGeometry();if(!h)return;const m=pl(h,t,n);-1!==m&&(o=m,i=t,r=!1,null==(d=e.setHasTextAnchor)||d.call(e,!0))},onPointerMove:(a,s,l)=>{if(!e.isEnabled(l))return;const c=e.getGeometry();if(!c)return;const d=pl(c,a,n);if(e.setCursor(-1!==d?"text":null),null!==o&&i&&!r){const n=a.x-i.x,s=a.y-i.y;return void(Math.sqrt(n*n+s*s)>=t&&(r=!0,e.onBegin(o,l),-1!==d&&e.onUpdate(d,l)))}e.isSelecting()&&-1!==d&&e.onUpdate(d,l)},onPointerUp:(t,n,o)=>{e.isEnabled(o)?(r&&e.onEnd(o),s()):s()},onDoubleClick:(t,o,i)=>{var r;if(!e.isEnabled(i))return;const s=e.getGeometry();if(!s)return;const l=pl(s,t,n);-1!==l&&(a=Date.now(),null==(r=e.onWordSelect)||r.call(e,l,i))},onClick:(t,o,i)=>{var r;if(!e.isEnabled(i))return;if(0===a)return;if(Date.now()-a>500)return void(a=0);a=0;const s=e.getGeometry();if(!s)return;const l=pl(s,t,n);-1!==l&&(null==(r=e.onLineSelect)||r.call(e,l,i))},onHandlerActiveEnd:t=>{s(),e.isEnabled(t)&&e.onClear(t)}}}({getGeometry:()=>this.getDocumentState(n).geometry[o],isEnabled:e=>{const t=null==l?void 0:l.get(e);return!!t&&!1!==t.enableSelection},onBegin:(e,t)=>this.beginSelection(n,o,e,t),onUpdate:(e,t)=>this.updateSelection(n,o,e,t),onEnd:e=>this.endSelection(n,e),onClear:e=>this.clearSelection(n,e),isSelecting:()=>this.selecting.get(n)??!1,setCursor:e=>e?s.setCursor("selection-text",e,10):s.removeCursor("selection-text"),onEmptySpaceClick:e=>this.emptySpaceClick$.emit(n,{pageIndex:o,modeId:e}),onWordSelect:(e,t)=>this.selectWord(n,o,e,t),onLineSelect:(e,t)=>this.selectLine(n,o,e,t),setHasTextAnchor:e=>this.hasTextAnchor.set(n,e),minDragDistance:this.config.minSelectionDragDistance,toleranceFactor:this.config.toleranceFactor}),d=this.interactionManagerCapability.registerAlways({scope:{type:"page",documentId:n,pageIndex:o},handlers:c});return()=>{var e;d(),null==(e=this.pageCallbacks.get(n))||e.delete(o),a.abort({code:tn.Cancelled,message:"Cleanup"})}}registerMarqueeOnPage(e){var t;const{documentId:n,pageIndex:o,scale:i,onRectChange:r}=e;if(!this.state.documents[n])return this.logger.warn("SelectionPlugin","RegisterMarqueeFailed",`Cannot register marquee on page ${o} for document ${n}: document state not initialized.`),()=>{};const a=this.coreState.core.documents[n];if(!a||!a.document)return this.logger.warn("SelectionPlugin","DocumentNotFound",`Cannot register marquee on page ${o}: document not found`),()=>{};const s=a.document.pages[o];if(!s)return this.logger.warn("SelectionPlugin","PageNotFound",`Cannot register marquee on page ${o}: page not found`),()=>{};const l=s.size,c=(null==(t=this.config.marquee)?void 0:t.minDragPx)??5,d=()=>{var e;const t=this.interactionManagerCapability.forDocument(n).getActiveMode(),o=null==(e=this.enabledModesPerDoc.get(n))?void 0:e.get(t);return!1!==(null==o?void 0:o.showMarqueeRects)},u=function(e){const{pageSize:t,scale:n,minDragPx:o=5}=e;let i=null,r=null;return{onPointerDown:(t,n,o)=>{var a,s;e.isEnabled(o)&&((null==(a=e.isTextSelecting)?void 0:a.call(e))||(i=t,r={origin:{x:t.x,y:t.y},size:{width:0,height:0}},e.onBegin(t,o),null==(s=n.setPointerCapture)||s.call(n)))},onPointerMove:(n,o,a)=>{if(!i||!e.isEnabled(a))return;const s=ko(n.x,0,t.width),l=ko(n.y,0,t.height);r={origin:{x:Math.min(i.x,s),y:Math.min(i.y,l)},size:{width:Math.abs(s-i.x),height:Math.abs(l-i.y)}},e.onChange(r,a)},onPointerUp:(t,a,s)=>{var l;e.isEnabled(s)&&(r&&i&&(Math.max(r.size.width,r.size.height)*n>o?e.onEnd(r,s):e.onCancel(s)),i=null,r=null,null==(l=a.releasePointerCapture)||l.call(a))},onPointerCancel:(t,n,o)=>{var a;e.isEnabled(o)&&(i=null,r=null,e.onCancel(o),null==(a=n.releasePointerCapture)||a.call(n))}}}({pageSize:l,scale:i,minDragPx:c,isEnabled:e=>{var t;const o=null==(t=this.enabledModesPerDoc.get(n))?void 0:t.get(e);return!0===(null==o?void 0:o.enableMarquee)},isTextSelecting:()=>(this.selecting.get(n)??!1)||(this.hasTextAnchor.get(n)??!1),onBegin:(e,t)=>this.beginMarquee(n,o,e,t),onChange:(e,t)=>{this.updateMarquee(n,o,e,t),r(d()?e:null)},onEnd:(e,t)=>{this.endMarquee(n,o,e,t),r(null)},onCancel:e=>{this.cancelMarquee(n,e),r(null)}});return this.interactionManagerCapability.registerAlways({scope:{type:"page",documentId:n,pageIndex:o},handlers:u})}getPlacementMetrics(e,t,n,o){var i;const r=null==(i=this.scrollCapability)?void 0:i.forDocument(e),a=null==r?void 0:r.getRectPositionForPage(t,n);if(!a)return null;const s=a.origin.y-o.scrollTop,l=a.origin.y+a.size.height-o.scrollTop;return{pageIndex:t,rect:n,spaceAbove:s,spaceBelow:o.clientHeight-l,isBottomVisible:l>0&&l<=o.clientHeight,isTopVisible:s>=0&&sthis.menuHeight?this.emitMenuPlacement(e,{...a,suggestTop:!1,isVisible:!0}):s&&s.isTopVisible?this.emitMenuPlacement(e,{...s,suggestTop:!0,isVisible:!0}):a&&a.isBottomVisible?this.emitMenuPlacement(e,{...a,suggestTop:!1,isVisible:!0}):this.emitMenuPlacement(e,null)}notifyPage(e,t){var n,o;const i=null==(n=this.pageCallbacks.get(e))?void 0:n.get(t);if(i){const n=this.getDocumentState(e),r=this.interactionManagerCapability.forDocument(e).getActiveMode(),a=null==(o=this.enabledModesPerDoc.get(e))?void 0:o.get(r);i(a&&!1!==(a.showSelectionRects??a.showRects)?{rects:dl(n,t),boundingRect:ul(n,t)}:{rects:[],boundingRect:null})}}notifyAllPages(e){var t;null==(t=this.pageCallbacks.get(e))||t.forEach((t,n)=>{this.notifyPage(e,n)})}getNewPageGeometryAndCache(e,t){const n=this.getCoreDocument(e);if(!n||!n.document)return nn.reject({code:tn.NotFound,message:"Doc Not Found"});const o=n.document.pages.find(e=>e.index===t),i=this.engine.getPageGeometry(n.document,o);return i.wait(n=>{this.dispatch(((e,t,n)=>({type:Ks,payload:{documentId:e,page:t,geo:n}}))(e,t,n)),this.touchGeometry(e,t)},Ln),i}getOrLoadGeometry(e,t){const n=this.getDocumentState(e).geometry[t];return n?(this.touchGeometry(e,t),nn.resolve(n)):this.getNewPageGeometryAndCache(e,t)}touchGeometry(e,t){const n=this.geoAccessOrder.get(e);if(!n)return;const o=n.indexOf(t);o>-1&&n.splice(o,1),n.push(t),this.evictGeometryIfNeeded(e)}evictGeometryIfNeeded(e){const t=this.config.maxCachedGeometries??50,n=this.geoAccessOrder.get(e);if(!n||n.length<=t)return;const o=this.pageCallbacks.get(e),i=[];for(;n.length-i.length>t;){const e=n.find(e=>!i.includes(e)&&!(null==o?void 0:o.has(e)));if(void 0===e)break;i.push(e)}if(0!==i.length){for(const e of i){const t=n.indexOf(e);t>-1&&n.splice(t,1)}this.dispatch(((e,t)=>({type:tl,payload:{documentId:e,pages:t}}))(e,i))}}beginSelection(e,t,n,o){this.selecting.set(e,!0),this.anchor.set(e,{page:t,index:n}),this.dispatch(ol(e)),this.beginSelection$.emit(e,{page:t,index:n,modeId:o}),this.recalculateMenuPlacement(e)}endSelection(e,t){this.selecting.set(e,!1),this.anchor.set(e,void 0),this.dispatch(il(e)),this.endSelection$.emit(e,{modeId:t}),this.recalculateMenuPlacement(e)}clearSelection(e,t){this.selecting.set(e,!1),this.anchor.set(e,void 0),this.dispatch((e=>({type:Qs,payload:{documentId:e}}))(e)),this.selChange$.emit(e,null),this.emitMenuPlacement(e,null),this.notifyAllPages(e)}selectWord(e,t,n,o){const i=this.getDocumentState(e).geometry[t];if(!i)return;const r=function(e,t){if(!Cl(e,t))return null;const n=function(e){if(0===e.runs.length)return 0;const t=e.runs[e.runs.length-1];return t.charStart+t.glyphs.length}(e);if(0===n)return null;let o=t;for(;o>0;){const t=Cl(e,o-1);if(!t)break;if(kl(e.runs[t.runIdx].glyphs[t.localIdx].flags))break;o--}let i=t;for(;i=0;t--){const n=e.runs[t];if(!Il(n)){if(!Sl(n.rect.y,n.rect.y+n.rect.height,i,r))break;a=n.charStart}}for(let t=n.runIdx+1;ti.page||t===i.page&&n>=i.index,a={start:r?i:{page:t,index:n},end:r?{page:t,index:n}:i};this.dispatch(nl(e,a)),this.updateRectsAndSlices(e,a),this.selChange$.emit(e,a);for(let t=a.start.page;t<=a.end.page;t++)this.notifyPage(e,t)}updateRectsAndSlices(e,t){const n=this.getDocumentState(e),o={},i={};for(let e=t.start.page;e<=t.end.page;e++){const r=n.geometry[e],a=fl(t,r,e);a&&(o[e]=vl(r,a.from,a.to),i[e]={start:a.from,count:a.to-a.from+1})}this.dispatch(rl(e,o)),this.dispatch(al(e,i))}getSelectedText(e){if(!this.checkPermission(e,Qt.CopyContents))return this.logger.debug("SelectionPlugin","GetSelectedText",`Cannot get selected text: document ${e} lacks CopyContents permission`),nn.reject({code:tn.Security,message:"Document lacks CopyContents permission"});const t=this.getCoreDocument(e),n=this.getDocumentState(e);if(!(null==t?void 0:t.document)||!n.selection)return nn.reject({code:tn.NotFound,message:"Doc Not Found or No Selection"});const o=n.selection,i=[];for(let e=o.start.page;e<=o.end.page;e++){const t=n.slices[e];t&&i.push({pageIndex:e,charIndex:t.start,charCount:t.count})}if(0===i.length)return nn.resolve([]);const r=this.engine.getTextSlices(t.document,i);return r.wait(t=>{this.textRetrieved$.emit(e,t)},Ln),r}copyToClipboard(e){if(!this.checkPermission(e,Qt.CopyContents))return void this.logger.debug("SelectionPlugin","CopyToClipboard",`Cannot copy to clipboard: document ${e} lacks CopyContents permission`);this.getSelectedText(e).wait(t=>{this.copyToClipboard$.emit(e,t.join("\n"))},Ln)}beginMarquee(e,t,n,o){this.marqueePage.set(e,t)}updateMarquee(e,t,n,o){this.marqueeChange$.emit(e,{pageIndex:t,rect:n,modeId:o})}endMarquee(e,t,n,o){this.marqueeEnd$.emit(e,{pageIndex:t,rect:n,modeId:o}),this.marqueeChange$.emit(e,{pageIndex:t,rect:null,modeId:o}),this.marqueePage.delete(e)}cancelMarquee(e,t){const n=this.marqueePage.get(e);void 0!==n&&(this.marqueeChange$.emit(e,{pageIndex:n,rect:null,modeId:t}),this.marqueePage.delete(e))}setMarqueeEnabled(e,t){const n=this.enabledModesPerDoc.get(e);if(!n)return;const o=n.get("pointerMode");o?o.enableMarquee=t:t&&n.set("pointerMode",{enableMarquee:!0})}isMarqueeEnabled(e){var t;const n=null==(t=this.enabledModesPerDoc.get(e))?void 0:t.get("pointerMode");return!1!==(null==n?void 0:n.enableMarquee)}};Al.id="selection";let Ml=Al;const Pl={manifest:qs,create:(e,t)=>new Ml(Bs,e,t),reducer:(e=ll,t)=>{switch(t.type){case Gs:{const{documentId:n,state:o}=t.payload;return cl(e,n,o)}case Vs:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i}}case Ks:{const{documentId:n,page:o,geo:i}=t.payload,r=e.documents[n];return r?cl(e,n,{...r,geometry:{...r.geometry,[o]:i}}):e}case Zs:{const{documentId:n,selection:o}=t.payload,i=e.documents[n];return i?cl(e,n,{...i,selection:o,active:!0}):e}case Ys:{const{documentId:n}=t.payload,o=e.documents[n];return o?cl(e,n,{...o,selecting:!0,selection:null,rects:{}}):e}case Xs:{const{documentId:n}=t.payload,o=e.documents[n];return o?cl(e,n,{...o,selecting:!1}):e}case Qs:{const{documentId:n}=t.payload,o=e.documents[n];return o?cl(e,n,{...o,selecting:!1,selection:null,rects:{},active:!1}):e}case Js:{const{documentId:n,rects:o}=t.payload,i=e.documents[n];return i?cl(e,n,{...i,rects:o}):e}case el:{const{documentId:n,slices:o}=t.payload,i=e.documents[n];return i?cl(e,n,{...i,slices:o}):e}case tl:{const{documentId:n,pages:o}=t.payload,i=e.documents[n];if(!i)return e;const r={...i.geometry},a={...i.rects},s={...i.slices};for(const e of o)delete r[e],delete a[e],delete s[e];return cl(e,n,{...i,geometry:r,rects:a,slices:s})}case"SELECTION/RESET":{const{documentId:n}=t.payload;return e.documents[n]?cl(e,n,sl):e}default:return e}},initialState:ll};function Dl(e,t){const{width:n,height:o}=e.size;switch(t%4){case 1:return{matrix:`matrix(0, -1, 1, 0, 0, ${o})`,width:o,height:n};case 2:return{matrix:`matrix(-1, 0, 0, -1, ${n}, ${o})`,width:n,height:o};case 3:return{matrix:`matrix(0, 1, -1, 0, ${n}, 0)`,width:o,height:n};default:return{matrix:"matrix(1, 0, 0, 1, 0, 0)",width:n,height:o}}}const Rl="onDblClick";function zl({children:e,...t}){const{rect:n,rotation:o}=t,{matrix:i,width:r,height:a}=Dl(n,o),s=De(null);Me(()=>{const e=s.current;if(!e)return;const t=e=>{e.stopPropagation()},n=e=>{e.stopPropagation()};return e.addEventListener("pointerdown",t,{capture:!0}),e.addEventListener("touchstart",n,{capture:!0,passive:!0}),()=>{e.removeEventListener("pointerdown",t,{capture:!0}),e.removeEventListener("touchstart",n,{capture:!0})}},[]);return He(H,{children:e({menuWrapperProps:{style:{position:"absolute",left:n.origin.x,top:n.origin.y,transform:i,transformOrigin:"0 0",width:r,height:a,pointerEvents:"none",zIndex:3},ref:e=>{s.current=e}},matrix:i,rect:{origin:{x:n.origin.x,y:n.origin.y},size:{width:r,height:a}}})})}function Tl(e,t,n,o=!1){if(!t)return e;let{origin:{x:i,y:r},size:{width:a,height:s}}=e;const l=t.minWidth??1,c=t.minHeight??1,d=t.maxWidth,u=t.maxHeight;if(n&&a>0&&s>0){const e=a/s;ad&&(a=d,s=a/e),void 0!==u&&s>u&&(s=u,a=s*e)}else a=Math.max(l,a),s=Math.max(c,s),void 0!==d&&(a=Math.min(d,a)),void 0!==u&&(s=Math.min(u,s));return t.boundingBox&&!o&&(i=Math.max(0,Math.min(i,t.boundingBox.width-a)),r=Math.max(0,Math.min(r,t.boundingBox.height-s))),{origin:{x:i,y:r},size:{width:a,height:s}}}function El(e,t,n){const o=1e-6,i=ut(e,t);return i.origin.x>=-o&&i.origin.y>=-o&&i.origin.x+i.size.width<=n.width+o&&i.origin.y+i.size.height<=n.height+o}function _l(e,t,n,o,i){const{startRect:r,maintainAspectRatio:a=!1,annotationRotation:s=0,constraints:l}=n,c=function(e){return{x:e.includes("e")?"left":e.includes("w")?"right":"center",y:e.includes("s")?"top":e.includes("n")?"bottom":"center"}}(t),d=r.size.width/r.size.height||1;let u=function(e,t,n){let o=e.origin.x,i=e.origin.y,r=e.size.width,a=e.size.height;return"left"===n.x?r+=t.x:"right"===n.x&&(o+=t.x,r-=t.x),"top"===n.y?a+=t.y:"bottom"===n.y&&(i+=t.y,a-=t.y),{origin:{x:o,y:i},size:{width:r,height:a}}}(r,e,c);if(a&&(u=function(e,t,n,o){let{x:i,y:r}=e.origin,{width:a,height:s}=e.size;if("center"===n.x||"center"===n.y)"center"===n.y?(s=a/o,r=t.origin.y+(t.size.height-s)/2):(a=s*o,i=t.origin.x+(t.size.width-a)/2);else{const e=Math.abs(a-t.size.width),n=Math.abs(s-t.size.height),i=e+n;if(0===i)a=t.size.width,s=t.size.height;else{const t=e/i,r=n/i,l=a/o;a=t*a+r*(s*o),s=t*l+r*s}}return"right"===n.x&&(i=t.origin.x+t.size.width-a),"bottom"===n.y&&(r=t.origin.y+t.size.height-s),{origin:{x:i,y:r},size:{width:a,height:s}}}(u,r,c,d)),o&&(u=function(e,t,n,o,i){if(!o)return e;let{x:r,y:a}=e.origin,{width:s,height:l}=e.size;s=Math.max(1,s),l=Math.max(1,l);const c="left"===n.x?t.origin.x:t.origin.x+t.size.width,d="top"===n.y?t.origin.y:t.origin.y+t.size.height,u="left"===n.x?o.width-c:"right"===n.x?c:2*Math.min(t.origin.x,o.width-t.origin.x-t.size.width)+t.size.width,h="top"===n.y?o.height-d:"bottom"===n.y?d:2*Math.min(t.origin.y,o.height-t.origin.y-t.size.height)+t.size.height;if(i){const e=s>u?u/s:1,t=l>h?h/l:1,n=Math.min(e,t);n<1&&(s*=n,l*=n)}else s=Math.min(s,u),l=Math.min(l,h);return r="left"===n.x?c:"right"===n.x?c-s:t.origin.x+(t.size.width-s)/2,a="top"===n.y?d:"bottom"===n.y?d-l:t.origin.y+(t.size.height-l)/2,r=Math.max(0,Math.min(r,o.width-s)),a=Math.max(0,Math.min(a,o.height-l)),{origin:{x:r,y:a},size:{width:s,height:l}}}(u,r,c,null==l?void 0:l.boundingBox,a)),u=Tl(u,l,a,i),i&&(u=function(e,t,n){let o,i;return o="left"===n.x?t.origin.x:"right"===n.x?t.origin.x+t.size.width-e.size.width:t.origin.x+(t.size.width-e.size.width)/2,i="top"===n.y?t.origin.y:"bottom"===n.y?t.origin.y+t.size.height-e.size.height:t.origin.y+(t.size.height-e.size.height)/2,{origin:{x:o,y:i},size:e.size}}(u,r,c)),0!==s){const e=function(e,t){return{x:"left"===t.x?e.origin.x:"right"===t.x?e.origin.x+e.size.width:e.origin.x+e.size.width/2,y:"top"===t.y?e.origin.y:"bottom"===t.y?e.origin.y+e.size.height:e.origin.y+e.size.height/2}}(r,c),t={x:r.origin.x+r.size.width/2,y:r.origin.y+r.size.height/2},n={x:u.origin.x+u.size.width/2,y:u.origin.y+u.size.height/2},o=lt(e,t,s),i=lt(e,n,s);u={origin:{x:u.origin.x+(o.x-i.x),y:u.origin.y+(o.y-i.y)},size:u.size}}return u}const Nl={n:0,ne:45,e:90,se:135,s:180,sw:225,w:270,nw:315},Ll=["ns-resize","nesw-resize","ew-resize","nwse-resize","ns-resize","nesw-resize","ew-resize","nwse-resize"];function Ol(e,t,n=0){const o=((Nl[e]+90*t+n)%360+360)%360,i=Math.round(o/45)%8;return Ll[i]}function $l(e,t,n){const o=-e/2;return"center"===n?o:"outside"===n?o-t:o+t}class jl{constructor(e,t){this.config=e,this.onUpdate=t,this.state="idle",this.startPoint=null,this.startElement=null,this.startRotationElement=null,this.gestureRotationCenter=null,this.activeHandle=null,this.currentPosition=null,this.activeVertexIndex=null,this.startVertices=[],this.currentVertices=[],this.rotationCenter=null,this.centerScreen=null,this.initialRotation=0,this.lastComputedRotation=0,this.rotationDelta=0,this.rotationSnappedAngle=null,this.currentVertices=e.vertices||[]}updateConfig(e){this.config={...this.config,...e},"vertex-editing"!==this.state&&(this.currentVertices=e.vertices||[])}startDrag(e,t){this.state="dragging",this.startPoint={x:e,y:t},this.startElement={...this.config.element},this.startRotationElement=this.config.rotationElement?{...this.config.rotationElement}:null,this.currentPosition={...this.config.element},this.onUpdate({state:"start",transformData:{type:"move",changes:{rect:this.startElement}}})}startResize(e,t,n){this.state="resizing",this.activeHandle=e,this.startPoint={x:t,y:n},this.startElement={...this.config.element},this.currentPosition={...this.config.element},this.onUpdate({state:"start",transformData:{type:"resize",changes:{rect:this.startElement},metadata:{handle:this.activeHandle,maintainAspectRatio:this.config.maintainAspectRatio}}})}startVertexEdit(e,t,n){this.currentVertices=[...this.config.vertices??this.currentVertices],e<0||e>=this.currentVertices.length||(this.state="vertex-editing",this.activeVertexIndex=e,this.startPoint={x:t,y:n},this.startVertices=[...this.currentVertices],this.gestureRotationCenter=this.config.rotationCenter??{x:this.config.element.origin.x+this.config.element.size.width/2,y:this.config.element.origin.y+this.config.element.size.height/2},this.onUpdate({state:"start",transformData:{type:"vertex-edit",changes:{vertices:this.startVertices},metadata:{vertexIndex:e}}}))}startRotation(e,t,n=0,o){this.state="rotating",this.startPoint={x:e,y:t},this.startElement={...this.config.element},this.rotationCenter=this.config.rotationCenter??{x:this.config.element.origin.x+this.config.element.size.width/2,y:this.config.element.origin.y+this.config.element.size.height/2};const{scale:i=1}=this.config,r=this.config.rotationElement??this.config.element,a=r.size.width*i,s=r.size.height*i,l=o??Math.max(a,s)/2+35,c=(n+90*(this.config.pageRotation??0))*Math.PI/180;this.centerScreen={x:e-l*Math.sin(c),y:t+l*Math.cos(c)},this.initialRotation=n,this.lastComputedRotation=n,this.rotationDelta=0,this.rotationSnappedAngle=null,this.onUpdate({state:"start",transformData:{type:"rotate",changes:{rotation:n},metadata:{rotationAngle:n,rotationDelta:0,rotationCenter:this.rotationCenter,isSnapped:!1}}})}move(e,t,n,o){if("idle"!==this.state&&this.startPoint)if(void 0===n||0!==n){if("dragging"===this.state&&this.startElement){const n=this.calculateDelta(e,t),o=this.calculateDragPosition(n);this.currentPosition=o,this.onUpdate({state:"move",transformData:{type:"move",changes:{rect:o}}})}else if("resizing"===this.state&&this.activeHandle&&this.startElement){const n=function(e,t,n){const{annotationRotation:o=0,constraints:i}=n,r=null==i?void 0:i.boundingBox;if(0!==o&&r){const i=_l(e,t,n,!1,!0);if(El(i,o,r))return i;let a=_l({x:0,y:0},t,n,!1,!0),s=0,l=1;for(let i=0;i<20;i+=1){const i=(s+l)/2,c=_l({x:e.x*i,y:e.y*i},t,n,!1,!0);El(c,o,r)?(a=c,s=i):l=i}return a}return _l(e,t,n,!0,!1)}(this.calculateLocalDelta(e,t),this.activeHandle,{startRect:this.startElement,maintainAspectRatio:this.config.maintainAspectRatio||!!o,annotationRotation:this.config.annotationRotation,constraints:this.config.constraints});this.currentPosition=n,this.onUpdate({state:"move",transformData:{type:"resize",changes:{rect:n},metadata:{handle:this.activeHandle,maintainAspectRatio:this.config.maintainAspectRatio||!!o}}})}else if("vertex-editing"===this.state&&null!==this.activeVertexIndex){const n=this.calculateVertexPosition(e,t);this.currentVertices=n,this.onUpdate({state:"move",transformData:{type:"vertex-edit",changes:{vertices:n},metadata:{vertexIndex:this.activeVertexIndex}}})}else if("rotating"===this.state&&this.rotationCenter){const n=this.calculateAngleFromMouse(e,t),o=this.applyRotationSnapping(n),i=at(o.angle),r=i-this.lastComputedRotation,a=r>180?r-360:r<-180?r+360:r;this.rotationDelta+=a,this.lastComputedRotation=i,this.rotationSnappedAngle=o.isSnapped?i:null,this.onUpdate({state:"move",transformData:{type:"rotate",changes:{rotation:i},metadata:{rotationAngle:i,rotationDelta:this.rotationDelta,rotationCenter:this.rotationCenter,isSnapped:o.isSnapped,snappedAngle:this.rotationSnappedAngle??void 0,cursorPosition:{clientX:e,clientY:t}}}})}}else this.end()}end(){if("idle"===this.state)return;const e=this.state,t=this.activeHandle,n=this.activeVertexIndex;if("vertex-editing"===e)this.onUpdate({state:"end",transformData:{type:"vertex-edit",changes:{vertices:this.currentVertices},metadata:{vertexIndex:n||void 0}}});else if("rotating"===e)this.onUpdate({state:"end",transformData:{type:"rotate",changes:{rotation:this.lastComputedRotation},metadata:{rotationAngle:this.lastComputedRotation,rotationDelta:this.rotationDelta,rotationCenter:this.rotationCenter||void 0,isSnapped:null!==this.rotationSnappedAngle,snappedAngle:this.rotationSnappedAngle??void 0}}});else{const n=this.currentPosition||this.config.element;this.onUpdate({state:"end",transformData:{type:"dragging"===e?"move":"resize",changes:{rect:n},metadata:"dragging"===e?void 0:{handle:t||void 0,maintainAspectRatio:this.config.maintainAspectRatio}}})}this.reset()}cancel(){"idle"!==this.state&&("vertex-editing"===this.state?this.onUpdate({state:"end",transformData:{type:"vertex-edit",changes:{vertices:this.startVertices},metadata:{vertexIndex:this.activeVertexIndex||void 0}}}):"rotating"===this.state?this.onUpdate({state:"end",transformData:{type:"rotate",changes:{rotation:this.initialRotation},metadata:{rotationAngle:this.initialRotation,rotationDelta:0,rotationCenter:this.rotationCenter||void 0,isSnapped:!1}}}):this.startElement&&this.onUpdate({state:"end",transformData:{type:"dragging"===this.state?"move":"resize",changes:{rect:this.startElement},metadata:"dragging"===this.state?void 0:{handle:this.activeHandle||void 0,maintainAspectRatio:this.config.maintainAspectRatio}}}),this.reset())}reset(){this.state="idle",this.startPoint=null,this.startElement=null,this.startRotationElement=null,this.gestureRotationCenter=null,this.activeHandle=null,this.currentPosition=null,this.activeVertexIndex=null,this.startVertices=[],this.rotationCenter=null,this.centerScreen=null,this.initialRotation=0,this.lastComputedRotation=0,this.rotationDelta=0,this.rotationSnappedAngle=null}calculateDelta(e,t){if(!this.startPoint)return{x:0,y:0};const n={x:e-this.startPoint.x,y:t-this.startPoint.y};return this.transformDelta(n)}transformDelta(e){const{pageRotation:t=0,scale:n=1}=this.config,o=t*Math.PI/2,i=Math.cos(o),r=Math.sin(o),a=e.x/n,s=e.y/n;return{x:i*a+r*s,y:-r*a+i*s}}calculateLocalDelta(e,t){const n=this.calculateDelta(e,t),{annotationRotation:o=0}=this.config;if(0===o)return n;const i=o*Math.PI/180,r=Math.cos(i),a=Math.sin(i);return{x:r*n.x+a*n.y,y:-a*n.x+r*n.y}}clampPoint(e){var t;const n=null==(t=this.config.constraints)?void 0:t.boundingBox;if(!n)return e;const{annotationRotation:o=0}=this.config;if(0===o)return{x:Math.max(0,Math.min(e.x,n.width)),y:Math.max(0,Math.min(e.y,n.height))};const i=this.gestureRotationCenter??this.config.rotationCenter??{x:this.config.element.origin.x+this.config.element.size.width/2,y:this.config.element.origin.y+this.config.element.size.height/2},r=lt(e,i,o),a=Math.max(0,Math.min(r.x,n.width)),s=Math.max(0,Math.min(r.y,n.height));return a===r.x&&s===r.y?e:lt({x:a,y:s},i,-o)}calculateVertexPosition(e,t){if(null===this.activeVertexIndex)return this.startVertices;const n=this.calculateLocalDelta(e,t),o=[...this.startVertices],i=o[this.activeVertexIndex],r={x:i.x+n.x,y:i.y+n.y};return o[this.activeVertexIndex]=this.clampPoint(r),o}calculateDragPosition(e){if(!this.startElement)return this.config.element;const t={origin:{x:this.startElement.origin.x+e.x,y:this.startElement.origin.y+e.y},size:{width:this.startElement.size.width,height:this.startElement.size.height}},{annotationRotation:n=0,constraints:o}=this.config,i=null==o?void 0:o.boundingBox;if(0!==n&&i){let e,o,r,a;if(this.startRotationElement)e=this.startRotationElement.size.width,o=this.startRotationElement.size.height,r=this.startRotationElement.origin.x-this.startElement.origin.x,a=this.startRotationElement.origin.y-this.startElement.origin.y;else{const i=Math.abs(n*Math.PI/180),s=Math.abs(Math.cos(i)),l=Math.abs(Math.sin(i)),c=t.size.width,d=t.size.height;e=c*s+d*l,o=c*l+d*s,r=(c-e)/2,a=(d-o)/2}let{x:s,y:l}=t.origin;return s=Math.max(-r,Math.min(s,i.width-e-r)),l=Math.max(-a,Math.min(l,i.height-o-a)),{origin:{x:s,y:l},size:t.size}}return Tl(t,o,this.config.maintainAspectRatio??!1)}calculateAngleFromMouse(e,t){if(!this.centerScreen)return this.initialRotation;const n=e-this.centerScreen.x,o=t-this.centerScreen.y;if(Math.sqrt(n*n+o*o)<10)return this.lastComputedRotation;const i=90*(this.config.pageRotation??0),r=Math.atan2(o,n)*(180/Math.PI)+90-i;return at(Math.round(r))}applyRotationSnapping(e){const t=this.config.rotationSnapAngles??[0,90,180,270],n=this.config.rotationSnapThreshold??4,o=at(e);for(const e of t){const t=at(e),i=Math.abs(o-t);if(Math.min(i,360-i)<=n)return{angle:t,isSnapped:!0,snapTarget:t}}return{angle:o,isSnapped:!1}}}function Fl(e){var t,n,o,i,r,a;const{controller:s,resizeUI:l,vertexUI:c,rotationUI:d,includeVertices:u=!1,includeRotation:h=!1,currentRotation:m=0,handleAttrs:g,vertexAttrs:p,rotationAttrs:f}=e,{dragProps:v,createResizeProps:y,createVertexProps:b,createRotationProps:w}=function(e){const{onUpdate:t,enabled:n=!0,...o}=e,i=De(null),r=De(t),a=De(null),s=De(null);Me(()=>{r.current=t},[t]),Me(()=>{i.current?i.current.updateConfig(o):i.current=new jl(o,e=>{var t;return null==(t=r.current)?void 0:t.call(r,e)})},[o.element,o.rotationCenter,o.rotationElement,o.constraints,o.maintainAspectRatio,o.pageRotation,o.annotationRotation,o.scale,o.vertices]);const l=ze(e=>{var t,n;const o=a.current,i=s.current,r=e??o;if(i&&null!==r)try{(null==(t=i.hasPointerCapture)?void 0:t.call(i,r))&&(null==(n=i.releasePointerCapture)||n.call(i,r))}catch{}a.current=null,s.current=null},[]),c=ze(e=>{var t;null!==a.current&&a.current!==e.pointerId&&(null==(t=i.current)||t.end(),l(a.current));const n=e.currentTarget;a.current=e.pointerId,s.current=n;try{n.setPointerCapture(e.pointerId)}catch{}},[l]);Me(()=>{const e=globalThis,t=e=>{var t;const n=a.current;null!==n&&e.pointerId===n&&(null==(t=i.current)||t.end(),l(e.pointerId))},n=()=>{var e;null!==a.current&&(null==(e=i.current)||e.end(),l())};return e.addEventListener("pointerup",t,!0),e.addEventListener("pointercancel",t,!0),e.addEventListener("blur",n,!0),()=>{e.removeEventListener("pointerup",t,!0),e.removeEventListener("pointercancel",t,!0),e.removeEventListener("blur",n,!0)}},[l]),Me(()=>()=>{var e;null!==a.current&&(null==(e=i.current)||e.end(),l())},[l]);const d=ze(e=>{var t;n&&(e.preventDefault(),e.stopPropagation(),null==(t=i.current)||t.startDrag(e.clientX,e.clientY),c(e))},[n,c]),u=ze(e=>{var t;e.preventDefault(),e.stopPropagation();const n=a.current;null!==n&&e.pointerId!==n||(null==(t=i.current)||t.move(e.clientX,e.clientY,e.buttons,e.shiftKey),a.current===e.pointerId&&0===e.buttons&&l(e.pointerId))},[l]),h=ze(e=>{var t;e.preventDefault(),e.stopPropagation();const n=a.current;null!==n&&e.pointerId!==n||(null==(t=i.current)||t.end(),l(e.pointerId))},[l]),m=ze(e=>{var t;const n=a.current;null!==n&&e.pointerId===n&&(null==(t=i.current)||t.end(),l(e.pointerId))},[l]),g=ze(e=>({onPointerDown:t=>{var o;n&&(t.preventDefault(),t.stopPropagation(),null==(o=i.current)||o.startResize(e,t.clientX,t.clientY),c(t))},onPointerMove:u,onPointerUp:h,onPointerCancel:h,onLostPointerCapture:m}),[n,u,h,m,c]),p=ze(e=>({onPointerDown:t=>{var o;n&&(t.preventDefault(),t.stopPropagation(),null==(o=i.current)||o.startVertexEdit(e,t.clientX,t.clientY),c(t))},onPointerMove:u,onPointerUp:h,onPointerCancel:h,onLostPointerCapture:m}),[n,u,h,m,c]),f=ze((e=0,t)=>({onPointerDown:o=>{var r;if(!n)return;o.preventDefault(),o.stopPropagation();const a=o.currentTarget.getBoundingClientRect(),s=a.left+a.width/2,l=a.top+a.height/2;null==(r=i.current)||r.startRotation(s,l,e,t),c(o)},onPointerMove:u,onPointerUp:h,onPointerCancel:h,onLostPointerCapture:m}),[n,u,h,m,c]);return{dragProps:n?{onPointerDown:d,onPointerMove:u,onPointerUp:h,onPointerCancel:h,onLostPointerCapture:m}:{},createResizeProps:g,createVertexProps:p,createRotationProps:f}}(s),x=Re(()=>function(e,t={}){const{handleSize:n=8,spacing:o=1,offsetMode:i="outside",includeSides:r=!1,zIndex:a=3,rotationAwareCursor:s=!0}=t,l=(e.pageRotation??0)%4,c=e.annotationRotation??0,d=e=>({[e]:$l(n,o,i)+"px"});return[["nw",{...d("top"),...d("left")}],["ne",{...d("top"),...d("right")}],["sw",{...d("bottom"),...d("left")}],["se",{...d("bottom"),...d("right")}],...r?[["n",{...d("top"),left:`calc(50% - ${n/2}px)`}],["s",{...d("bottom"),left:`calc(50% - ${n/2}px)`}],["w",{...d("left"),top:`calc(50% - ${n/2}px)`}],["e",{...d("right"),top:`calc(50% - ${n/2}px)`}]]:[]].map(([e,t])=>({handle:e,style:{position:"absolute",width:n+"px",height:n+"px",borderRadius:"50%",zIndex:a,cursor:s?Ol(e,l,c):"default",pointerEvents:"auto",touchAction:"none",...t},attrs:{"data-epdf-handle":e}}))}(s,l).map(e=>{var t;return{key:null==(t=e.attrs)?void 0:t["data-epdf-handle"],style:e.style,...y(e.handle),...e.attrs??{},...(null==g?void 0:g(e.handle))??{}}}),[s.element.origin.x,s.element.origin.y,s.element.size.width,s.element.size.height,s.scale,s.pageRotation,s.annotationRotation,s.maintainAspectRatio,null==l?void 0:l.handleSize,null==l?void 0:l.spacing,null==l?void 0:l.offsetMode,null==l?void 0:l.includeSides,null==l?void 0:l.zIndex,null==l?void 0:l.rotationAwareCursor,y,g]),C=Re(()=>{if(!u)return[];const e=function(e,t={},n){const{vertexSize:o=12,zIndex:i=4}=t,r=e.element,a=e.scale??1;return(n??e.vertices??[]).map((e,t)=>({handle:"nw",style:{position:"absolute",left:(e.x-r.origin.x)*a-o/2+"px",top:(e.y-r.origin.y)*a-o/2+"px",width:o+"px",height:o+"px",borderRadius:"50%",cursor:"pointer",zIndex:i,pointerEvents:"auto",touchAction:"none"},attrs:{"data-epdf-vertex":t}}))}(s,c,s.vertices);return e.map((e,t)=>({key:t,style:e.style,...b(t),...e.attrs??{},...(null==p?void 0:p(t))??{}}))},[u,s.element.origin.x,s.element.origin.y,s.element.size.width,s.element.size.height,s.scale,s.vertices,null==c?void 0:c.vertexSize,null==c?void 0:c.zIndex,b,p]);return{dragProps:v,resize:x,vertices:C,rotation:Re(()=>{if(!h)return null;const e=function(e,t={},n=0){const{handleSize:o=16,zIndex:i=5,showConnector:r=!0,connectorWidth:a=1}=t,s=e.scale??1,l=e.element,c=e.rotationElement??l,d=e.rotationCenter??{x:l.origin.x+l.size.width/2,y:l.origin.y+l.size.height/2};c.size.width,c.size.height;const u=(d.x-c.origin.x)*s,h=(d.y-c.origin.y)*s,m=n*Math.PI/180,g=t.margin??35,p=l.size.height*s/2+g;return{handleStyle:{position:"absolute",left:u+p*Math.sin(m)-o/2+"px",top:h-p*Math.cos(m)-o/2+"px",width:o+"px",height:o+"px",borderRadius:"50%",cursor:"grab",zIndex:i,pointerEvents:"auto",touchAction:"none"},connectorStyle:r?{position:"absolute",left:u-a/2+"px",top:h-p+"px",width:a+"px",height:p+"px",transformOrigin:"center bottom",transform:`rotate(${n}deg)`,zIndex:i-1,pointerEvents:"none"}:{},radius:p,attrs:{"data-epdf-rotation-handle":!0}}}(s,d,m);return{handle:{style:e.handleStyle,...w(m,e.radius),...e.attrs??{},...(null==f?void 0:f())??{}},connector:{style:e.connectorStyle,"data-epdf-rotation-connector":!0}}},[h,s.element.origin.x,s.element.origin.y,s.element.size.width,s.element.size.height,null==(t=s.rotationCenter)?void 0:t.x,null==(n=s.rotationCenter)?void 0:n.y,null==(o=s.rotationElement)?void 0:o.origin.x,null==(i=s.rotationElement)?void 0:i.origin.y,null==(r=s.rotationElement)?void 0:r.size.width,null==(a=s.rotationElement)?void 0:a.size.height,s.scale,m,null==d?void 0:d.handleSize,null==d?void 0:d.margin,null==d?void 0:d.zIndex,null==d?void 0:d.showConnector,null==d?void 0:d.connectorWidth,w,f])}}const Ul=()=>Oo(Ml.id),Hl=()=>Lo(Ml.id);function Wl({documentId:e,pageIndex:t,scale:n,rotation:o,background:i="rgba(33,150,243)",selectionMenu:r}){var a,s;const{plugin:l}=Hl(),c=jo(e),d=null==(s=null==(a=null==c?void 0:c.document)?void 0:a.pages)?void 0:s[t],[u,h]=Se([]),[m,g]=Se(null),[p,f]=Se(null);Me(()=>{if(l&&e)return l.registerSelectionOnPage({documentId:e,pageIndex:t,onRectsChange:({rects:e,boundingRect:t})=>{h(e),g(t)}})},[l,e,t]),Me(()=>{if(l&&e)return l.onMenuPlacement(e,e=>{f(e)})},[l,e]);const v=Re(()=>void 0!==n?n:(null==c?void 0:c.scale)??1,[n,null==c?void 0:c.scale]),y=Re(()=>{if(void 0!==o)return o;return(((null==d?void 0:d.rotation)??0)+((null==c?void 0:c.rotation)??0))%4},[o,null==d?void 0:d.rotation,null==c?void 0:c.rotation]),b=r&&p&&p.pageIndex===t&&p.isVisible;return m?He(H,{children:[He("div",{style:{position:"absolute",left:m.origin.x*v,top:m.origin.y*v,width:m.size.width*v,height:m.size.height*v,mixBlendMode:"multiply",isolation:"isolate",pointerEvents:"none"},children:u.map((e,t)=>He("div",{style:{position:"absolute",left:(e.origin.x-m.origin.x)*v,top:(e.origin.y-m.origin.y)*v,width:e.size.width*v,height:e.size.height*v,background:i}},t))}),b&&He(zl,{rect:{origin:{x:p.rect.origin.x*v,y:p.rect.origin.y*v},size:{width:p.rect.size.width*v,height:p.rect.size.height*v}},rotation:y,children:e=>r({...e,context:{type:"selection",pageIndex:t},selected:!0,placement:p})})]}):null}const Bl=({documentId:e,pageIndex:t,scale:n,className:o,background:i,borderColor:r,borderStyle:a="dashed",stroke:s,fill:l})=>{const{plugin:c}=Hl(),d=jo(e),[u,h]=Se(null),m=r??s??"rgba(0,122,204,0.8)",g=i??l??"rgba(0,122,204,0.15)",p=Re(()=>void 0!==n?n:(null==d?void 0:d.scale)??1,[n,null==d?void 0:d.scale]);return Me(()=>{if(c&&e)return c.registerMarqueeOnPage({documentId:e,pageIndex:t,scale:p,onRectChange:h})},[c,e,t,p]),u?He("div",{style:{position:"absolute",pointerEvents:"none",left:u.origin.x*p,top:u.origin.y*p,width:u.size.width*p,height:u.size.height*p,border:`1px ${a} ${m}`,background:g,boxSizing:"border-box",zIndex:1e3},className:o}):null};function ql({documentId:e,pageIndex:t,scale:n,rotation:o,background:i,textStyle:r,marqueeStyle:a,marqueeClassName:s,selectionMenu:l}){return He(H,{children:[He(Wl,{documentId:e,pageIndex:t,scale:n,rotation:o,background:(null==r?void 0:r.background)??i,selectionMenu:l}),He(Bl,{documentId:e,pageIndex:t,scale:n,background:null==a?void 0:a.background,borderColor:null==a?void 0:a.borderColor,borderStyle:null==a?void 0:a.borderStyle,className:s})]})}const Gl=To(Pl).addUtility(function(){const{provides:e}=Ul();return Me(()=>{if(e)return e.onCopyToClipboard(({text:e})=>{navigator.clipboard.writeText(e)})},[e]),null}).build(),Vl="tiling",Kl={id:Vl,name:"Tiling Plugin",version:"1.0.0",provides:["tiling"],requires:["render","scroll","viewport"],optional:[],defaultConfig:{tileSize:768,overlapPx:2.5,extraRings:0}},Zl="TILING/INIT_STATE",Yl="TILING/CLEANUP_STATE",Xl="TILING/UPDATE_VISIBLE_TILES",Ql="TILING/MARK_TILE_STATUS",Jl=(e,t)=>({type:Xl,payload:{documentId:e,tiles:t}}),ec=(e,t,n,o)=>({type:Ql,payload:{documentId:e,pageIndex:t,tileId:n,status:o}}),tc={visibleTiles:{}};function nc({tileSize:e=768,overlapPx:t=2.5,extraRings:n=0,scale:o,rotation:i,page:r,metric:a}){const s=r.size.width*o,l=r.size.height*o,c=e-t,d=function(e,t,n,o){return nt(tt(e,t,(4-n)%4),1/o)}(Ke(r.size,i,o),{origin:{x:a.scaled.pageX,y:a.scaled.pageY},size:{width:a.scaled.visibleWidth,height:a.scaled.visibleHeight}},i,1),u=d.origin.x,h=d.origin.y,m=u+d.size.width,g=h+d.size.height,p=Math.floor((s-1)/c),f=Math.floor((l-1)/c),v=Math.max(0,Math.floor(u/c)-n),y=Math.min(p,Math.floor((m-1)/c)+n),b=Math.max(0,Math.floor(h/c)-n),w=Math.min(f,Math.floor((g-1)/c)+n),x=[];for(let t=v;t<=y;t++){const n=t*c,i=Math.min(e,s-n),a=n/o,d=i/o;for(let s=b;s<=w;s++){const u=s*c,h=Math.min(e,l-u),m=u/o,g=h/o;x.push({id:`p${r.index}-${o}-x${n}-y${u}-w${i}-h${h}`,col:t,row:s,pageRect:{origin:{x:a,y:m},size:{width:d,height:g}},screenRect:{origin:{x:n,y:u},size:{width:i,height:h}},status:"queued",srcScale:o,isFallback:!1})}}return x}const oc=class extends bo{constructor(e,t,n){super(e,t),this.tileRendering$=Do(),this.config=n,this.renderCapability=this.registry.getPlugin("render").provides(),this.scrollCapability=this.registry.getPlugin("scroll").provides(),this.viewportCapability=this.registry.getPlugin("viewport").provides(),this.scrollCapability.onScroll(e=>this.calculateVisibleTiles(e.documentId,e.metrics),{mode:"throttle",wait:50,throttleMode:"trailing"}),this.coreStore.onAction(Jn,e=>this.recalculateTiles(e.payload))}onDocumentLoadingStarted(e){this.dispatch(((e,t)=>({type:Zl,payload:{documentId:e,state:t}}))(e,tc))}onDocumentClosed(e){this.dispatch((e=>({type:Yl,payload:e}))(e))}onScaleChanged(e){this.recalculateTilesForDocument(e)}onRotationChanged(e){this.recalculateTilesForDocument(e)}recalculateTilesForDocument(e){const t=this.scrollCapability.forDocument(e),n=this.viewportCapability.forDocument(e),o=t.getMetrics(n.getMetrics());this.calculateVisibleTiles(e,o)}async recalculateTiles(e){const{documentId:t,pageIndexes:n}=e,o=this.getCoreDocument(t);if(!o||!o.document)return;const i=this.scrollCapability.forDocument(t),r=this.viewportCapability.forDocument(t),a=i.getMetrics(r.getMetrics()),s={},l=Date.now(),c=o.scale;for(const e of n){const t=a.pageVisibilityMetrics.find(t=>t.pageNumber===e+1);if(!t)continue;const n=o.document.pages[e];if(!n)continue;const i=((n.rotation??0)+o.rotation)%4;s[e]=nc({page:n,metric:t,scale:c,rotation:i,tileSize:this.config.tileSize,overlapPx:this.config.overlapPx,extraRings:this.config.extraRings}).map(e=>({...e,id:`${e.id}-r${l}`}))}Object.keys(s).length>0&&this.dispatch(Jl(t,s))}async initialize(){}calculateVisibleTiles(e,t){const n=this.getCoreDocument(e);if(!n||!n.document)return;const o=n.scale,i={};for(const e of t.pageVisibilityMetrics){const t=e.pageNumber-1,r=n.document.pages[t];if(!r)continue;const a=nc({page:r,metric:e,scale:o,rotation:((r.rotation??0)+n.rotation)%4,tileSize:this.config.tileSize,overlapPx:this.config.overlapPx,extraRings:this.config.extraRings});i[t]=a}this.dispatch(Jl(e,i))}onStoreUpdated(e,t){for(const n in t.documents){const o=e.documents[n],i=t.documents[n];o!==i&&this.tileRendering$.emit({documentId:n,tiles:i.visibleTiles})}}buildCapability(){return{renderTile:this.renderTile.bind(this),forDocument:this.createTilingScope.bind(this),onTileRendering:this.tileRendering$.on}}createTilingScope(e){return{renderTile:t=>this.renderTile(t,e),onTileRendering:t=>this.tileRendering$.on(n=>{n.documentId===e&&t(n.tiles)})}}renderTile(e,t){const n=t??this.getActiveDocumentId();if(!this.renderCapability)throw new Error("Render capability not available.");this.dispatch(ec(n,e.pageIndex,e.tile.id,"rendering"));const o=this.renderCapability.forDocument(n).renderPageRect({pageIndex:e.pageIndex,rect:e.tile.pageRect,options:{scaleFactor:e.tile.srcScale,dpr:e.dpr}});return o.wait(()=>{this.dispatch(ec(n,e.pageIndex,e.tile.id,"ready"))},Ln),o}};oc.id="tiling";let ic=oc;const rc={manifest:Kl,create:(e,t)=>new ic(Vl,e,t),reducer:(e,t)=>((e,t)=>{var n,o;switch(t.type){case Zl:{const{documentId:n,state:o}=t.payload;return{...e,documents:{...e.documents,[n]:o}}}case Yl:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i}}case Xl:{const{documentId:o,tiles:i}=t.payload,r=e.documents[o];if(!r)return e;const a={...r.visibleTiles};for(const e in i){const t=Number(e),o=i[t],r=a[t]??[],s=null==(n=r.find(e=>!e.isFallback))?void 0:n.srcScale,l=o.length>0?o[0].srcScale:s;if(void 0!==s&&s!==l){const e=r.filter(e=>!e.isFallback&&"ready"===e.status).map(e=>({...e,isFallback:!0})),n=e.length>0?[]:r.filter(e=>e.isFallback);a[t]=[...n,...e,...o]}else{const e=new Set(o.map(e=>e.id)),n=[],i=new Set;for(const t of r)(t.isFallback||e.has(t.id))&&(n.push(t),i.add(t.id));for(const e of o)i.has(e.id)||n.push(e);a[t]=n}}return{...e,documents:{...e.documents,[o]:{...r,visibleTiles:a}}}}case Ql:{const{documentId:n,pageIndex:i,tileId:r,status:a}=t.payload,s=e.documents[n];if(!s)return e;const l=(null==(o=s.visibleTiles[i])?void 0:o.map(e=>e.id===r?{...e,status:a}:e))??[],c=l.filter(e=>!e.isFallback),d=c.length>0&&c.every(e=>"ready"===e.status),u=d?c:l;return{...e,documents:{...e.documents,[n]:{...s,visibleTiles:{...s.visibleTiles,[i]:u}}}}}default:return e}})(e,t),initialState:{documents:{}}},ac=()=>Oo(ic.id);function sc({documentId:e,pageIndex:t,tile:n,dpr:o,scale:i}){const{provides:r}=ac(),a=Re(()=>null==r?void 0:r.forDocument(e),[r,e]),[s,l]=Se(),c=De(null),d=i/n.srcScale;Me(()=>{if("ready"===n.status&&c.current)return;if(!a)return;const e=a.renderTile({pageIndex:t,tile:n,dpr:o});return e.wait(e=>{const t=URL.createObjectURL(e);c.current=t,l(t)},Ln),()=>{c.current?(URL.revokeObjectURL(c.current),c.current=null):e.abort({code:tn.Cancelled,message:"canceled render task"})}},[a,t,n.id]);return s?He("img",{src:s,onLoad:()=>{c.current&&(URL.revokeObjectURL(c.current),c.current=null)},style:{position:"absolute",left:n.screenRect.origin.x*d,top:n.screenRect.origin.y*d,width:n.screenRect.size.width*d,height:n.screenRect.size.height*d,display:"block"}}):null}function lc({documentId:e,pageIndex:t,scale:n,style:o,...i}){const{provides:r}=ac(),a=jo(e),[s,l]=Se([]);Me(()=>{if(r)return r.onTileRendering(n=>{n.documentId===e&&l(n.tiles[t]??[])})},[r,e,t]);const c=Re(()=>void 0!==n?n:(null==a?void 0:a.scale)??1,[n,null==a?void 0:a.scale]);return He("div",{style:{...o},...i,children:null==s?void 0:s.map(n=>He(sc,{documentId:e,pageIndex:t,tile:n,dpr:window.devicePixelRatio,scale:c},n.id))})}const cc="thumbnail",dc={id:cc,name:"Thumbnail Plugin",version:"1.0.0",provides:["thumbnail"],requires:["render"],optional:["scroll"],defaultConfig:{width:150,gap:10,buffer:3,labelHeight:16,autoScroll:!0,scrollBehavior:"smooth",imagePadding:0,paddingY:0}},uc="THUMBNAIL/INIT_STATE",hc="THUMBNAIL/CLEANUP_STATE",mc="THUMBNAIL/SET_WINDOW_STATE",gc="THUMBNAIL/UPDATE_VIEWPORT_METRICS";function pc(e,t){return{type:uc,payload:{documentId:e,state:t}}}const fc={thumbs:[],window:null,viewportH:0,scrollY:0},vc={documents:{},activeDocumentId:null},yc=class extends bo{constructor(e,t,n){var o;super(e,t),this.cfg=n,this.scrollCapability=null,this.taskCaches=new Map,this.canAutoScroll=new Map,this.window$=Ro((e,t)=>({documentId:e,window:t})),this.scrollTo$=Ro((e,t)=>({documentId:e,options:t})),this.refreshPages$=Ro((e,t)=>({documentId:e,pages:t}),{cache:!1}),this.renderCapability=this.registry.getPlugin("render").provides(),this.scrollCapability=(null==(o=this.registry.getPlugin("scroll"))?void 0:o.provides())??null,this.coreStore.onAction(Jn,e=>{const t=e.payload.documentId??this.getActiveDocumentId(),n=e.payload.pageIndexes;this.refreshPages$.emit(t,n);const o=this.taskCaches.get(t);if(o)for(const e of n)o.delete(e)}),this.scrollCapability&&!1!==this.cfg.autoScroll&&(this.scrollCapability.onPageChangeState(({documentId:e,state:t})=>{this.canAutoScroll.set(e,!t.isChanging),t.isChanging||this.scrollToThumb(t.targetPage-1,e)}),this.scrollCapability.onPageChange(({documentId:e,pageNumber:t})=>{!1!==this.canAutoScroll.get(e)&&this.scrollToThumb(t-1,e)}))}onDocumentLoadingStarted(e){this.dispatch(pc(e,{...fc})),this.taskCaches.set(e,new Map),this.canAutoScroll.set(e,!0),this.logger.debug("ThumbnailPlugin","DocumentOpened",`Initialized thumbnail state for document: ${e}`)}onDocumentLoaded(e){this.calculateWindowState(e)}onDocumentClosed(e){this.dispatch(function(e){return{type:hc,payload:e}}(e));const t=this.taskCaches.get(e);t&&(t.forEach(e=>{e.abort({code:"cancelled",message:"Document closed"})}),t.clear(),this.taskCaches.delete(e)),this.canAutoScroll.delete(e),this.window$.clearScope(e),this.scrollTo$.clearScope(e),this.refreshPages$.clearScope(e),this.logger.debug("ThumbnailPlugin","DocumentClosed",`Cleaned up thumbnail state for document: ${e}`)}onRotationChanged(e){this.calculateWindowState(e)}buildCapability(){return{scrollToThumb:e=>this.scrollToThumb(e),renderThumb:(e,t)=>this.renderThumb(e,t),updateWindow:(e,t)=>this.updateWindow(e,t),getWindow:()=>this.getWindow(),forDocument:e=>this.createThumbnailScope(e),onWindow:this.window$.onGlobal,onScrollTo:this.scrollTo$.onGlobal,onRefreshPages:this.refreshPages$.onGlobal}}createThumbnailScope(e){return{scrollToThumb:t=>this.scrollToThumb(t,e),renderThumb:(t,n)=>this.renderThumb(t,n,e),updateWindow:(t,n)=>this.updateWindow(t,n,e),getWindow:()=>this.getWindow(e),onWindow:this.window$.forScope(e),onScrollTo:this.scrollTo$.forScope(e),onRefreshPages:this.refreshPages$.forScope(e)}}getDocumentState(e){const t=e??this.getActiveDocumentId();return this.state.documents[t]??null}calculateWindowState(e){const t=this.coreState.core.documents[e];if(!(null==t?void 0:t.document))return;const n=this.cfg.width??120,o=this.cfg.labelHeight??16,i=this.cfg.gap??8,r=this.cfg.imagePadding??0,a=this.cfg.paddingY??0,s=Math.max(1,n-2*r);let l=a;const c=t.document.pages.map(e=>{const t=e.rotation%2==1,n=t?e.size.height:e.size.width,a=(t?e.size.width:e.size.height)/n,c=Math.round(s*a),d=r+c+r+o,u={pageIndex:e.index,width:s,height:c,wrapperHeight:d,top:l,labelHeight:o,padding:r};return l+=d+i,u}),d={start:-1,end:-1,items:[],totalHeight:l-i+a},u=this.getDocumentState(e);u&&(this.dispatch(pc(e,{...u,thumbs:c,window:d})),u.viewportH>0?this.updateWindow(u.scrollY,u.viewportH,e):this.window$.emit(e,d))}updateWindow(e,t,n){const o=n??this.getActiveDocumentId(),i=this.getDocumentState(o);if(!i||!i.window||0===i.thumbs.length)return;const r=this.cfg.buffer??3;this.dispatch(function(e,t,n){return{type:gc,payload:{documentId:e,scrollY:t,viewportH:n}}}(o,e,t));let a=0,s=i.thumbs.length-1,l=0;for(;a<=s;){const t=a+s>>1,n=i.thumbs[t];n.top+n.wrapperHeighto.scrollY+o.viewportH-8;c?this.scrollTo$.emit(n,{top:Math.max(0,s-a),behavior:r}):d&&this.scrollTo$.emit(n,{top:Math.max(0,l-o.viewportH+a),behavior:r})}renderThumb(e,t,n){const o=n??this.getActiveDocumentId(),i=this.taskCaches.get(o);if(!i)throw new Error(`Task cache not found for document: ${o}`);if(i.has(e))return i.get(e);const r=this.coreState.core.documents[o];if(!(null==r?void 0:r.document))throw new Error(`Document not found: ${o}`);const a=r.document.pages[e];if(!a)throw new Error(`Page ${e} not found in document: ${o}`);const s=this.cfg.width??120,l=this.cfg.imagePadding??0,c=Math.max(1,s-2*l)/a.size.width,d=this.renderCapability.forDocument(o).renderPageRect({pageIndex:e,rect:{origin:{x:0,y:0},size:a.size},options:{scaleFactor:c,dpr:t,rotation:a.rotation}});return i.set(e,d),d.wait(Ln,()=>i.delete(e)),d}async initialize(){this.logger.info("ThumbnailPlugin","Initialize","Thumbnail plugin initialized")}async destroy(){this.window$.clear(),this.refreshPages$.clear(),this.scrollTo$.clear(),this.taskCaches.forEach(e=>{e.forEach(e=>{e.abort({code:"cancelled",message:"Plugin destroyed"})}),e.clear()}),this.taskCaches.clear(),this.canAutoScroll.clear(),super.destroy()}};yc.id="thumbnail";let bc=yc;const wc={manifest:dc,create:(e,t)=>new bc(cc,e,t),reducer:(e=vc,t)=>{switch(t.type){case uc:{const{documentId:n,state:o}=t.payload;return{...e,documents:{...e.documents,[n]:o},activeDocumentId:e.activeDocumentId??n}}case hc:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i,activeDocumentId:e.activeDocumentId===n?null:e.activeDocumentId}}case"THUMBNAIL/SET_ACTIVE_DOCUMENT":return{...e,activeDocumentId:t.payload};case mc:{const{documentId:n,window:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,window:o}}}:e}case gc:{const{documentId:n,scrollY:o,viewportH:i}=t.payload,r=e.documents[n];return r?{...e,documents:{...e.documents,[n]:{...r,scrollY:o,viewportH:i}}}:e}default:return e}},initialState:vc},xc=()=>Lo(bc.id);function Cc({documentId:e,style:t,children:n,...o}){const{plugin:i}=xc(),r=De(null),[a,s]=Se({window:null,docId:null}),l=a.docId===e?a.window:null;Me(()=>{if(!i)return;const t=i.provides().forDocument(e),n=t.getWindow();n&&s({window:n,docId:e});const o=t.onWindow(t=>{s({window:t,docId:e})});return()=>{o(),s({window:null,docId:null})}},[i,e]),Me(()=>{const t=r.current;if(!t||!i)return;const n=i.provides().forDocument(e),o=()=>n.updateWindow(t.scrollTop,t.clientHeight);return t.addEventListener("scroll",o),()=>t.removeEventListener("scroll",o)},[i,e]),Me(()=>{const t=r.current;if(!t||!i)return;const n=i.provides().forDocument(e),o=new ResizeObserver(()=>{n.updateWindow(t.scrollTop,t.clientHeight)});return o.observe(t),()=>o.disconnect()},[i,e]),Me(()=>{const t=r.current;if(!t||!i)return;i.provides().forDocument(e).updateWindow(t.scrollTop,t.clientHeight)},[l,i,e]),Me(()=>{const t=r.current;if(!t||!i||!l)return;return i.provides().forDocument(e).onScrollTo(({top:e,behavior:n})=>{t.scrollTo({top:e,behavior:n})})},[i,e,!!l]);const c=(null==i?void 0:i.cfg.paddingY)??0;return He("div",{ref:r,style:{overflowY:"auto",position:"relative",paddingTop:c,paddingBottom:c,height:"100%",...t},...o,children:He("div",{style:{height:(null==l?void 0:l.totalHeight)??0,position:"relative"},children:null==l?void 0:l.items.map(e=>n(e))})})}function kc({documentId:e,meta:t,style:n,...o}){const{provides:i}=Oo(bc.id),{plugin:r}=xc(),[a,s]=Se(),l=De(null),[c,d]=Se(0);Me(()=>{if(!r)return;return r.provides().forDocument(e).onRefreshPages(e=>{e.includes(t.pageIndex)&&d(e=>e+1)})},[r,e,t.pageIndex]),Me(()=>{const n=null==i?void 0:i.forDocument(e),o=null==n?void 0:n.renderThumb(t.pageIndex,window.devicePixelRatio);return null==o||o.wait(e=>{const t=URL.createObjectURL(e);l.current=t,s(t)},Ln),()=>{l.current?(URL.revokeObjectURL(l.current),l.current=null):null==o||o.abort({code:tn.Cancelled,message:"canceled render task"})}},[i,e,t.pageIndex,c]);return a?He("img",{src:a,onLoad:()=>{l.current&&(URL.revokeObjectURL(l.current),l.current=null)},style:n,...o}):null}const Ic="annotation",Sc={id:Ic,name:"Annotation Plugin",version:"1.0.0",provides:["annotation"],requires:["interaction-manager","selection"],optional:["history"],defaultConfig:{autoCommit:!0,annotationAuthor:"Guest",deactivateToolAfterCreate:!1,selectAfterCreate:!0}},Ac="ANNOTATION/INIT_STATE",Mc="ANNOTATION/CLEANUP_STATE",Pc="ANNOTATION/SET_ANNOTATIONS",Dc="ANNOTATION/SELECT_ANNOTATION",Rc="ANNOTATION/DESELECT_ANNOTATION",zc="ANNOTATION/ADD_TO_SELECTION",Tc="ANNOTATION/REMOVE_FROM_SELECTION",Ec="ANNOTATION/SET_SELECTION",_c="ANNOTATION/SET_ACTIVE_TOOL_ID",Nc="ANNOTATION/CREATE_ANNOTATION",Lc="ANNOTATION/PATCH_ANNOTATION",Oc="ANNOTATION/MOVE_ANNOTATION",$c="ANNOTATION/DELETE_ANNOTATION",jc="ANNOTATION/COMMIT",Fc="ANNOTATION/PURGE_ANNOTATION",Uc="ANNOTATION/ADD_COLOR_PRESET",Hc="ANNOTATION/SET_TOOL_DEFAULTS",Wc="ANNOTATION/ADD_TOOL";const Bc=e=>({type:Rc,payload:{documentId:e}}),qc=(e,t,n)=>({type:zc,payload:{documentId:e,pageIndex:t,id:n}}),Gc=(e,t)=>({type:Tc,payload:{documentId:e,id:t}}),Vc=(e,t)=>({type:Ec,payload:{documentId:e,ids:t}}),Kc=(e,t)=>({type:_c,payload:{documentId:e,toolId:t}}),Zc=(e,t,n)=>({type:Nc,payload:{documentId:e,pageIndex:t,annotation:n}}),Yc=(e,t,n,o)=>({type:Lc,payload:{documentId:e,pageIndex:t,id:n,patch:o}}),Xc=(e,t,n,o)=>({type:Oc,payload:{documentId:e,pageIndex:t,id:n,patch:o}}),Qc=(e,t,n)=>({type:$c,payload:{documentId:e,pageIndex:t,id:n}}),Jc=(e,t,n)=>({type:Fc,payload:{documentId:e,pageIndex:t,uid:n}});function ed(e){return function(e){return e.object.type===Ot.HIGHLIGHT}(e)||function(e){return e.object.type===Ot.UNDERLINE}(e)||function(e){return e.object.type===Ot.STRIKEOUT}(e)||function(e){return e.object.type===Ot.SQUIGGLY}(e)}function td(e){return e.object.type===Ot.TEXT}function nd(e){return td(e)&&!e.object.inReplyToId||ed(e)||function(e){return e.object.type===Ot.INK}(e)||function(e){return e.object.type===Ot.SQUARE}(e)||function(e){return e.object.type===Ot.CIRCLE}(e)||function(e){return e.object.type===Ot.POLYGON}(e)||function(e){return e.object.type===Ot.LINE}(e)||function(e){return e.object.type===Ot.POLYLINE}(e)||function(e){return e.object.type===Ot.FREETEXT}(e)||function(e){return e.object.type===Ot.STAMP}(e)||function(e){return e.object.type===Ot.REDACT}(e)||function(e){return e.object.type===Ot.CARET}(e)}const od=(e,t)=>(e.pages[t]??[]).map(t=>e.byUid[t]),id=e=>e.selectedUids.map(t=>e.byUid[t]).filter(e=>void 0!==e),rd=e=>e.selectedUids;function ad(e,t){const n=e.tools.find(e=>e.id===t);return null==n?void 0:n.defaults}const sd=(e,t)=>((e,t,n)=>{const o=[];for(const i of Object.values(e.pages))for(const r of i){const i=e.byUid[r];i&&"inReplyToId"in i.object&&i.object.inReplyToId===t&&n.includes(i.object.type)&&o.push(i)}return o})(e,t,[Ot.LINK]),ld=(e,t)=>{const n=e.byUid[t];if(n)return n.object.inReplyToId&&n.object.replyType===Ut.Group?n.object.inReplyToId:t},cd=(e,t)=>{const n=ld(e,t);if(!n)return[];const o=[],i=e.byUid[n];i&&i.object.type!==Ot.LINK&&o.push(i);for(const t of Object.values(e.pages))for(const i of t){const t=e.byUid[i];t&&t.object.inReplyToId===n&&t.object.replyType===Ut.Group&&t.object.type!==Ot.LINK&&o.push(t)}return o},dd=(e,t)=>{const n=e.byUid[t];if(!n)return!1;if(n.object.type===Ot.LINK)return!1;if(n.object.inReplyToId&&n.object.replyType===Ut.Group)return!0;for(const n of Object.values(e.pages))for(const o of n){const n=e.byUid[o];if(n&&n.object.inReplyToId===t&&n.object.replyType===Ut.Group&&n.object.type!==Ot.LINK)return!0}return!1},ud=[{id:"highlight",name:"Highlight",matchScore:e=>e.type===Ot.HIGHLIGHT?1:0,interaction:{exclusive:!1,textSelection:!0,isDraggable:!1,isResizable:!1,isRotatable:!1,isGroupDraggable:!1,isGroupResizable:!1},defaults:{type:Ot.HIGHLIGHT,strokeColor:"#FFCD45",color:"#FFCD45",opacity:1,blendMode:zt.Multiply}},{id:"underline",name:"Underline",matchScore:e=>e.type===Ot.UNDERLINE?1:0,interaction:{exclusive:!1,textSelection:!0,isDraggable:!1,isResizable:!1,isRotatable:!1,isGroupDraggable:!1,isGroupResizable:!1},defaults:{type:Ot.UNDERLINE,strokeColor:"#E44234",color:"#E44234",opacity:1}},{id:"strikeout",name:"Strikeout",matchScore:e=>e.type===Ot.STRIKEOUT?1:0,interaction:{exclusive:!1,textSelection:!0,isDraggable:!1,isResizable:!1,isRotatable:!1,isGroupDraggable:!1,isGroupResizable:!1},defaults:{type:Ot.STRIKEOUT,strokeColor:"#E44234",color:"#E44234",opacity:1}},{id:"squiggly",name:"Squiggly",matchScore:e=>e.type===Ot.SQUIGGLY?1:0,interaction:{exclusive:!1,textSelection:!0,isDraggable:!1,isResizable:!1,isRotatable:!1,isGroupDraggable:!1,isGroupResizable:!1},defaults:{type:Ot.SQUIGGLY,strokeColor:"#E44234",color:"#E44234",opacity:1}},{id:"insertText",name:"Insert Text",matchScore:e=>{var t;return e.type!==Ot.CARET?0:(null==(t=e.intent)?void 0:t.includes("Insert"))?2:1},interaction:{exclusive:!1,textSelection:!0,showSelectionRects:!0,isDraggable:!1,isResizable:!1,isRotatable:!1,isGroupDraggable:!1,isGroupResizable:!1},defaults:{type:Ot.CARET,strokeColor:"#E44234",opacity:1,intent:"Insert"}},{id:"replaceText",name:"Replace Text",matchScore:e=>{var t,n;return e.type===Ot.STRIKEOUT&&(null==(t=e.intent)?void 0:t.includes("StrikeOutTextEdit"))||e.type===Ot.CARET&&(null==(n=e.intent)?void 0:n.includes("Replace"))?2:0},interaction:{exclusive:!1,textSelection:!0,isDraggable:!1,isResizable:!1,isRotatable:!1,isGroupDraggable:!1,isGroupResizable:!1},defaults:{type:Ot.STRIKEOUT,strokeColor:"#E44234",opacity:1,intent:"StrikeOutTextEdit"}},{id:"ink",name:"Pen",matchScore:e=>e.type===Ot.INK&&"InkHighlight"!==e.intent?5:0,interaction:{exclusive:!1,cursor:"crosshair",isDraggable:!0,isResizable:!0,lockAspectRatio:!1},defaults:{type:Ot.INK,strokeColor:"#E44234",color:"#E44234",opacity:1,strokeWidth:6}},{id:"inkHighlighter",name:"Ink Highlighter",matchScore:e=>e.type===Ot.INK&&"InkHighlight"===e.intent?10:0,interaction:{exclusive:!1,cursor:"crosshair",isDraggable:!0,isResizable:!0,lockAspectRatio:!1,lockGroupAspectRatio:e=>{const t=((e.rotation??0)%90+90)%90;return t>=6&&t<=84}},defaults:{type:Ot.INK,intent:"InkHighlight",strokeColor:"#FFCD45",color:"#FFCD45",opacity:1,strokeWidth:14,blendMode:zt.Multiply}},{id:"circle",name:"Circle",matchScore:e=>e.type===Ot.CIRCLE?1:0,interaction:{exclusive:!1,cursor:"crosshair",isDraggable:!0,isResizable:!0,lockAspectRatio:!1,lockGroupAspectRatio:e=>{const t=((e.rotation??0)%90+90)%90;return t>=6&&t<=84}},defaults:{type:Ot.CIRCLE,color:"transparent",opacity:1,strokeWidth:6,strokeColor:"#E44234",strokeStyle:Bt.SOLID},clickBehavior:{enabled:!0,defaultSize:{width:100,height:100}}},{id:"square",name:"Square",matchScore:e=>e.type===Ot.SQUARE?1:0,interaction:{exclusive:!1,cursor:"crosshair",isDraggable:!0,isResizable:!0,lockAspectRatio:!1,lockGroupAspectRatio:e=>{const t=((e.rotation??0)%90+90)%90;return t>=6&&t<=84}},defaults:{type:Ot.SQUARE,color:"transparent",opacity:1,strokeWidth:6,strokeColor:"#E44234",strokeStyle:Bt.SOLID},clickBehavior:{enabled:!0,defaultSize:{width:100,height:100}}},{id:"line",name:"Line",matchScore:e=>e.type===Ot.LINE&&"LineArrow"!==e.intent?5:0,interaction:{exclusive:!1,cursor:"crosshair",isDraggable:!0,isResizable:!1,lockAspectRatio:!1,isGroupResizable:!0,lockGroupAspectRatio:e=>{const t=((e.rotation??0)%90+90)%90;return t>=6&&t<=84}},defaults:{type:Ot.LINE,color:"transparent",opacity:1,strokeWidth:6,strokeColor:"#E44234"},clickBehavior:{enabled:!0,defaultLength:100,defaultAngle:0}},{id:"lineArrow",name:"Arrow",matchScore:e=>e.type===Ot.LINE&&"LineArrow"===e.intent?10:0,interaction:{exclusive:!1,cursor:"crosshair",isDraggable:!0,isResizable:!1,lockAspectRatio:!1,isGroupResizable:!0,lockGroupAspectRatio:e=>{const t=((e.rotation??0)%90+90)%90;return t>=6&&t<=84}},defaults:{type:Ot.LINE,intent:"LineArrow",color:"transparent",opacity:1,strokeWidth:6,strokeColor:"#E44234",lineEndings:{start:Ft.None,end:Ft.OpenArrow}},clickBehavior:{enabled:!0,defaultLength:100,defaultAngle:0}},{id:"polyline",name:"Polyline",matchScore:e=>e.type===Ot.POLYLINE?1:0,interaction:{exclusive:!1,cursor:"crosshair",isDraggable:!0,isResizable:!1,lockAspectRatio:!1,isGroupResizable:!0,lockGroupAspectRatio:e=>{const t=((e.rotation??0)%90+90)%90;return t>=6&&t<=84}},defaults:{type:Ot.POLYLINE,color:"transparent",opacity:1,strokeWidth:6,strokeColor:"#E44234"}},{id:"polygon",name:"Polygon",matchScore:e=>e.type===Ot.POLYGON?1:0,interaction:{exclusive:!1,cursor:"crosshair",isDraggable:!0,isResizable:!1,lockAspectRatio:!1,isGroupResizable:!0,lockGroupAspectRatio:e=>{const t=((e.rotation??0)%90+90)%90;return t>=6&&t<=84}},defaults:{type:Ot.POLYGON,color:"transparent",opacity:1,strokeWidth:6,strokeColor:"#E44234"}},{id:"textComment",name:"Comment",matchScore:e=>e.type!==Ot.TEXT||e.inReplyToId?0:1,interaction:{exclusive:!1,cursor:"crosshair",isDraggable:!0,isResizable:!1,isRotatable:!1},defaults:{type:Ot.TEXT,strokeColor:"#FFCD45",opacity:1},behavior:{selectAfterCreate:!0}},{id:"freeText",name:"Free Text",matchScore:e=>e.type===Ot.FREETEXT?1:0,interaction:{exclusive:!1,cursor:"crosshair",isDraggable:!0,isResizable:!0,lockAspectRatio:!1,lockGroupAspectRatio:e=>{const t=((e.rotation??0)%90+90)%90;return t>=6&&t<=84}},defaults:{type:Ot.FREETEXT,contents:"Insert text",fontSize:14,fontColor:"#E44234",fontFamily:Pt.Helvetica,textAlign:Dt.Left,verticalAlign:Rt.Top,color:"transparent",backgroundColor:"transparent",opacity:1},clickBehavior:{enabled:!0,defaultSize:{width:100,height:20},defaultContent:"Insert text"},behavior:{insertUpright:!0}},{id:"stamp",name:"Image",matchScore:e=>e.type===Ot.STAMP?1:0,interaction:{exclusive:!1,cursor:"copy",isDraggable:!0,isResizable:!0,lockAspectRatio:!0,lockGroupAspectRatio:!0},defaults:{type:Ot.STAMP},behavior:{insertUpright:!0,useAppearanceStream:!1}}],hd=["#E44234","#FF8D00","#FFCD45","#5CC96E","#25D2D1","#597CE2","#C544CE","#7D2E25","#000000","#FFFFFF"],md=e=>1===e.length?e[0]:null,gd=(e,t,n)=>{const o=e.byUid[t];return o?{...e,byUid:{...e.byUid,[t]:{...o,commitState:"synced"===o.commitState||"moved"===o.commitState?"dirty":o.commitState,object:{...o.object,...n},dictMode:!0}},hasPendingChanges:!0}:e},pd=(e,t,n)=>{const o=e.byUid[t];return o?{...e,byUid:{...e.byUid,[t]:{...o,commitState:"synced"===o.commitState?"moved":o.commitState,object:{...o.object,...n}}},hasPendingChanges:!0}:e};function fd(e){let t=e;return[()=>t,e=>{t=e}]}const vd={annotationType:Ot.INK,create(e){const{onCommit:t,onPreview:n,getTool:o,pageSize:i}=e,[r,a]=fd([]),[s,l]=fd(!1),c={current:null},d=e=>({x:ko(e.x,0,i.width),y:ko(e.y,0,i.height)}),u=()=>{const e=o();return e?{...e.defaults,strokeWidth:e.defaults.strokeWidth??1,strokeColor:e.defaults.strokeColor??e.defaults.color??"#000000",opacity:e.defaults.opacity??1,flags:e.defaults.flags??["print"]}:null},h=()=>{const e=r();if(0===e.length||0===e[0].points.length)return null;const t=u();if(!t)return null;const n=e.flatMap(e=>e.points),o=et(Je(n),t.strokeWidth/2);return{type:Ot.INK,bounds:o,data:{...t,rect:o,inkList:e}}};return{onPointerDown:(e,t)=>{var o;const i=d(e);l(!0),c.current&&clearTimeout(c.current);const s=[...r(),{points:[i]}];a(s),n(h()),null==(o=t.setPointerCapture)||o.call(t)},onPointerMove:e=>{if(!s())return;const t=r();if(0===t.length)return;const o=d(e);t[t.length-1].points.push(o),a(t),n(h())},onPointerUp:(o,i)=>{var s;l(!1),null==(s=i.releasePointerCapture)||s.call(i),c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{const o=r();if(o.length>0&&o[0].points.length>1){const n=u();if(!n)return;const i=o.flatMap(e=>e.points),r=et(Je(i),n.strokeWidth/2);t({...n,inkList:o,rect:r,type:Ot.INK,pageIndex:e.pageIndex,id:_n(),created:new Date})}a([]),n(null)},800)},onPointerCancel:(e,t)=>{var o;a([]),l(!1),n(null),c.current&&clearTimeout(c.current),null==(o=t.releasePointerCapture)||o.call(t)}}}};function yd(e){const t=e=>{const t=9*e,n=Math.PI/6;return{x:-t*Math.cos(n),y:t*Math.sin(n)}};return{getSvgPath:n=>{const{x:o,y:i}=t(n);return e?`M 0 0 L ${o} ${i} L ${o} ${-i} Z`:`M ${o} ${i} L 0 0 L ${o} ${-i}`},getLocalPoints:e=>{const{x:n,y:o}=t(e);return[{x:0,y:0},{x:n,y:o},{x:n,y:-o}]},getRotation:e=>e,filled:e}}function bd(e,t){const n=t=>t*e/2;return{getSvgPath:e=>{const t=n(e);return`M ${-t} 0 L ${t} 0`},getLocalPoints:e=>{const t=n(e);return[{x:-t,y:0},{x:t,y:0}]},getRotation:t,filled:!1}}const wd=yd(!1),xd=yd(!0),Cd={[Ft.OpenArrow]:wd,[Ft.ClosedArrow]:xd,[Ft.ROpenArrow]:{...wd,getRotation:e=>e+Math.PI},[Ft.RClosedArrow]:{...xd,getRotation:e=>e+Math.PI},[Ft.Circle]:{getSvgPath:e=>{const t=5*e/2;return`M ${t} 0 A ${t} ${t} 0 1 1 ${-t} 0 A ${t} ${t} 0 1 1 ${t} 0`},getLocalPoints:e=>{const t=5*e/2;return[{x:-t,y:-t},{x:t,y:t}]},getRotation:()=>0,filled:!0},[Ft.Square]:{getSvgPath:e=>{const t=6*e/2;return`M ${-t} ${-t} L ${t} ${-t} L ${t} ${t} L ${-t} ${t} Z`},getLocalPoints:e=>{const t=6*e/2;return[{x:-t,y:-t},{x:t,y:-t},{x:t,y:t},{x:-t,y:t}]},getRotation:e=>e,filled:!0},[Ft.Diamond]:{getSvgPath:e=>{const t=6*e/2;return`M 0 ${-t} L ${t} 0 L 0 ${t} L ${-t} 0 Z`},getLocalPoints:e=>{const t=6*e/2;return[{x:0,y:-t},{x:t,y:0},{x:0,y:t},{x:-t,y:0}]},getRotation:e=>e,filled:!0},[Ft.Butt]:bd(6,e=>e+Math.PI/2),[Ft.Slash]:bd(18,e=>e+Math.PI/1.5)};function kd(e,t,n){if(!e||0===e.length)return{origin:{x:0,y:0},size:{width:0,height:0}};const o=[...e],i=(e,t)=>Math.atan2(t.y-e.y,t.x-e.x),r=(e,n,i)=>{if(!e)return;const r=Cd[e];if(!r)return;const a=r.getLocalPoints(t),s=r.getRotation(i),l=a.map(e=>function(e,t,n){const o=Math.cos(t),i=Math.sin(t),r=e.x*o-e.y*i,a=e.x*i+e.y*o;return{x:r+n.x,y:a+n.y}}(e,s,n));o.push(...l)};if(e.length>=2){const t=i(e[1],e[0]);r(null==n?void 0:n.start,e[0],t);const o=e.length-1,a=i(e[o-1],e[o]);r(null==n?void 0:n.end,e[o],a)}if(o.length<=1){const n=e[0]||{x:0,y:0},o=t;return{origin:{x:n.x-o,y:n.y-o},size:{width:2*o,height:2*o}}}return et(Je(o),t/2+1.2*t)}function Id(e,t){if(!e.unrotatedRect)return{rect:t};const n=st(t);return{rect:dt(t,e.rotation??0,n),unrotatedRect:t}}function Sd(e){return e.unrotatedRect?ht(e.unrotatedRect,e.rect,e.rotation??0):st(e.rect)}function Ad(e,t,n){const o=Sd(e),i=e.unrotatedRect??e.rect,r=t.origin.x-i.origin.x,a=t.origin.y-i.origin.y;return{rect:dt(t,n,{x:o.x+r,y:o.y+a}),unrotatedRect:t}}function Md(e,t,n){if(!e.unrotatedRect)return t;const o=e.rotation??0;if(Math.abs(o%360)<1e-8)return t;const i=Sd(e),r=st(n),a=o*Math.PI/180,s=Math.cos(a),l=Math.sin(a),c=i.x-r.x,d=i.y-r.y,u=(1-s)*c+l*d,h=-l*c+(1-s)*d;return Math.abs(u)<1e-8&&Math.abs(h)<1e-8?t:t.map(e=>({x:e.x+u,y:e.y+h}))}class Pd{constructor(){this.patches=new Map}register(e,t){this.patches.set(e,t)}transform(e,t){const n=this.patches.get(e.type);return n?n(e,t):t.changes}}const Dd=new Pd;function Rd(e,t){var n;if(void 0===(null==(n=t.metadata)?void 0:n.rotationAngle))return null;const o=t.metadata.rotationAngle,i=t.changes.unrotatedRect??e.unrotatedRect??e.rect;return{...Ad(e,{origin:{...i.origin},size:{...i.size}},o),rotation:o}}function zd(e,t){return{rotation:t,...Ad(e,e.unrotatedRect??e.rect,t)}}function Td(e,t){const n=t.origin.x-e.rect.origin.x,o=t.origin.y-e.rect.origin.y,i={rect:t};return e.unrotatedRect&&(i.unrotatedRect={origin:{x:e.unrotatedRect.origin.x+n,y:e.unrotatedRect.origin.y+o},size:{...e.unrotatedRect.size}}),{dx:n,dy:o,rects:i}}function Ed(e,t,n){const o=e.unrotatedRect??e.rect;let i=t.size.width/o.size.width,r=t.size.height/o.size.height;if((t.size.width<10||t.size.height<10)&&(i=Math.max(i,10/o.size.width),r=Math.max(r,10/o.size.height),t={origin:t.origin,size:{width:o.size.width*i,height:o.size.height*r}}),null==n?void 0:n.maintainAspectRatio){const e=Math.min(i,r);i=e,r=e,t={origin:t.origin,size:{width:o.size.width*e,height:o.size.height*e}}}return{scaleX:i,scaleY:r,oldRect:o,resolvedRect:t,rects:e.unrotatedRect?{unrotatedRect:t,rect:ut(t,e.rotation??0)}:{rect:t}}}function _d(e,t){const n=e.unrotatedRect??e.rect,o=t.unrotatedRect??n;return{dx:o.origin.x-n.origin.x,dy:o.origin.y-n.origin.y}}function Nd(e,t,n){if(0===t||void 0!==e.rotation)return e;const o=(4-t)%4*90;let i=e;if(n&&(1===t||3===t)){const t=e.rect,n=t.origin.x+t.size.width/2,o=t.origin.y+t.size.height/2;i={...e,rect:{origin:{x:n-t.size.height/2,y:o-t.size.width/2},size:{width:t.size.height,height:t.size.width}}}}const{rotation:r,rect:a,unrotatedRect:s}=zd(i,o);return{...i,rotation:r,rect:a,unrotatedRect:s}}function Ld(e,t){const n=ko(e.rect.origin.x,0,t.width-e.rect.size.width),o=ko(e.rect.origin.y,0,t.height-e.rect.size.height),i=n-e.rect.origin.x,r=o-e.rect.origin.y;return 0===i&&0===r?e:{...e,rect:{origin:{x:n,y:o},size:e.rect.size},...e.unrotatedRect?{unrotatedRect:{origin:{x:e.unrotatedRect.origin.x+i,y:e.unrotatedRect.origin.y+r},size:e.unrotatedRect.size}}:{}}}const Od=Object.freeze(Object.defineProperty({__proto__:null,LINE_ENDING_HANDLERS:Cd,PatchRegistry:Pd,applyInsertUpright:Nd,calculateAABBFromVertices:function(e,t=0){if(0===e.length)return{origin:{x:0,y:0},size:{width:0,height:0}};const n=Je(e);return t>0?et(n,t):n},calculateRotatedRectAABB:ut,calculateRotatedRectAABBAroundPoint:dt,clampAnnotationToPage:Ld,compensateRotatedVertexEdit:Md,createEnding:function(e,t,n,o,i){if(!e)return null;const r=Cd[e];if(!r)return null;const a=r.getRotation(n);return{d:r.getSvgPath(t),transform:`translate(${o} ${i}) rotate(${(e=>180*e/Math.PI)(a)})`,filled:r.filled}},getRectCenter:st,lineRectWithEndings:kd,patchRegistry:Dd,resolveAnnotationRotationCenter:Sd,resolveRotateRects:Ad,resolveVertexEditRects:Id,rotatePointAroundCenter:lt,rotateVertices:ct},Symbol.toStringTag,{value:"Module"})),$d={annotationType:Ot.TEXT,create(e){const{onCommit:t,getTool:n,pageSize:o}=e;return{onPointerDown:i=>{const r=n();if(!r)return;const a={origin:{x:i.x-12,y:i.y-12},size:{width:24,height:24}};let s={...r.defaults,rect:a,type:Ot.TEXT,icon:r.defaults.icon??jt.Comment,contents:r.defaults.contents??"",flags:r.defaults.flags??["print","noRotate","noZoom"],pageIndex:e.pageIndex,id:_n(),created:new Date};s=Ld(s,o),t(s)}}}};function jd({threshold:e=5,getTool:t,onClickDetected:n}){const[o,i]=fd(null),[r,a]=fd(!1);return{onStart:e=>{i(e),a(!1)},onMove:t=>{const n=o();if(!n||r())return;Math.sqrt(Math.pow(t.x-n.x,2)+Math.pow(t.y-n.y,2))>e&&a(!0)},onEnd:e=>{var s;if(o()&&!r()){const o=t();o&&"clickBehavior"in o&&(null==(s=o.clickBehavior)?void 0:s.enabled)&&n(e,o)}i(null),a(!1)},hasMoved:r,reset:()=>{i(null),a(!1)}}}const Fd={annotationType:Ot.FREETEXT,create(e){const{onCommit:t,onPreview:n,getTool:o,pageSize:i,pageIndex:r,pageRotation:a}=e,[s,l]=fd(null),c=e=>({x:ko(e.x,0,i.width),y:ko(e.y,0,i.height)}),d=()=>{const e=o();return e?{...e.defaults,fontColor:e.defaults.fontColor??"#000000",opacity:e.defaults.opacity??1,fontSize:e.defaults.fontSize??12,fontFamily:e.defaults.fontFamily??Pt.Helvetica,color:e.defaults.color??e.defaults.backgroundColor??"transparent",textAlign:e.defaults.textAlign??Dt.Left,verticalAlign:e.defaults.verticalAlign??Rt.Top,contents:e.defaults.contents??"Insert text here",flags:e.defaults.flags??["print"]}:null},u=jd({threshold:5,getTool:o,onClickDetected:(e,n)=>{var o;const s=d();if(!s)return;const l=n.clickBehavior;if(!(null==l?void 0:l.enabled))return;const{width:c,height:u}=l.defaultSize,h={origin:{x:e.x-c/2,y:e.y-u/2},size:{width:c,height:u}},m=l.defaultContent??s.contents;let g={...s,contents:m,type:Ot.FREETEXT,rect:h,pageIndex:r,id:_n(),created:new Date};(null==(o=n.behavior)?void 0:o.insertUpright)&&(g=Nd(g,a,!1)),g=Ld(g,i),t(g)}}),h=e=>{const t=s();if(!t)return null;const n=d();if(!n)return null;const o={origin:{x:Math.min(t.x,e.x),y:Math.min(t.y,e.y)},size:{width:Math.abs(t.x-e.x),height:Math.abs(t.y-e.y)}};return{type:Ot.FREETEXT,bounds:o,data:{...n,rect:o}}};return{onPointerDown:(e,t)=>{var o;const i=c(e);l(i),u.onStart(i),n(h(i)),null==(o=t.setPointerCapture)||o.call(t)},onPointerMove:e=>{const t=c(e);u.onMove(t),s()&&u.hasMoved()&&n(h(t))},onPointerUp:(i,r)=>{var h,m;const g=s();if(!g)return;const p=d();if(!p)return;const f=c(i);if(u.hasMoved()){const n={origin:{x:Math.min(g.x,f.x),y:Math.min(g.y,f.y)},size:{width:Math.abs(g.x-f.x),height:Math.abs(g.y-f.y)}},i=o();let r={...p,type:Ot.FREETEXT,rect:n,pageIndex:e.pageIndex,id:_n(),created:new Date};(null==(h=null==i?void 0:i.behavior)?void 0:h.insertUpright)&&(r=Nd(r,a,!0)),t(r)}else u.onEnd(f);l(null),n(null),u.reset(),null==(m=r.releasePointerCapture)||m.call(r)},onPointerLeave:(e,t)=>{var o;l(null),n(null),u.reset(),null==(o=t.releasePointerCapture)||o.call(t)},onPointerCancel:(e,t)=>{var o;l(null),n(null),u.reset(),null==(o=t.releasePointerCapture)||o.call(t)}}}},Ud={annotationType:Ot.LINE,create(e){const{pageIndex:t,onCommit:n,onPreview:o,getTool:i,pageSize:r}=e,[a,s]=fd(null),l=e=>({x:ko(e.x,0,r.width),y:ko(e.y,0,r.height)}),c=()=>{const e=i();return e?{...e.defaults,strokeWidth:e.defaults.strokeWidth??1,lineEndings:e.defaults.lineEndings??{start:Ft.None,end:Ft.None},color:e.defaults.color??"#000000",opacity:e.defaults.opacity??1,strokeStyle:e.defaults.strokeStyle??Bt.SOLID,strokeDashArray:e.defaults.strokeDashArray??[],strokeColor:e.defaults.strokeColor??"#000000",flags:e.defaults.flags??["print"]}:null},d=jd({threshold:5,getTool:i,onClickDetected:(e,o)=>{const i=c();if(!i)return;const r=o.clickBehavior;if(!(null==r?void 0:r.enabled))return;const a=r.defaultAngle??0,s=r.defaultLength/2,d=e.x-s*Math.cos(a),u=e.y-s*Math.sin(a),h=e.x+s*Math.cos(a),m=e.y+s*Math.sin(a),g=l({x:d,y:u}),p=l({x:h,y:m}),f=kd([g,p],i.strokeWidth,i.lineEndings);n({...i,rect:f,linePoints:{start:g,end:p},pageIndex:t,id:_n(),created:new Date,type:Ot.LINE})}}),u=e=>{const t=a();if(!t)return null;const n=c();if(!n)return null;const o=kd([t,e],n.strokeWidth,n.lineEndings);return{type:Ot.LINE,bounds:o,data:{...n,rect:o,linePoints:{start:t,end:e}}}};return{onPointerDown:(e,t)=>{var n;const i=l(e);s(i),d.onStart(i),o(u(i)),null==(n=t.setPointerCapture)||n.call(t)},onPointerMove:e=>{const t=l(e);d.onMove(t),a()&&d.hasMoved()&&o(u(t))},onPointerUp:(e,i)=>{var r;const u=a();if(!u)return;const h=l(e);if(d.hasMoved()){const e=c();if(!e)return;if(Math.abs(h.x-u.x)>2||Math.abs(h.y-u.y)>2){const o=kd([u,h],e.strokeWidth,e.lineEndings);n({...e,rect:o,linePoints:{start:u,end:h},pageIndex:t,id:_n(),flags:["print"],created:new Date,type:Ot.LINE})}}else d.onEnd(h);s(null),o(null),d.reset(),null==(r=i.releasePointerCapture)||r.call(i)},onPointerLeave:(e,t)=>{var n;s(null),o(null),d.reset(),null==(n=t.releasePointerCapture)||n.call(t)},onPointerCancel:(e,t)=>{var n;s(null),o(null),d.reset(),null==(n=t.releasePointerCapture)||n.call(t)}}}},Hd={annotationType:Ot.POLYLINE,create(e){const{onCommit:t,onPreview:n,getTool:o,pageSize:i}=e,[r,a]=fd([]),[s,l]=fd(null),c=e=>({x:ko(e.x,0,i.width),y:ko(e.y,0,i.height)}),d=()=>{const e=o();return e?{...e.defaults,strokeWidth:e.defaults.strokeWidth??1,lineEndings:e.defaults.lineEndings??{start:Ft.None,end:Ft.None},color:e.defaults.color??"#000000",opacity:e.defaults.opacity??1,strokeColor:e.defaults.strokeColor??"#000000",strokeStyle:e.defaults.strokeStyle??Bt.SOLID,strokeDashArray:e.defaults.strokeDashArray??[],flags:e.defaults.flags??["print"]}:null},u=()=>{const e=r(),t=s();if(0===e.length||!t)return null;const n=d();if(!n)return null;const o=[...e,t],i=kd(o,n.strokeWidth,n.lineEndings);return{type:Ot.POLYLINE,bounds:i,data:{...n,rect:i,vertices:o,currentVertex:t}}};return{onClick:(e,t)=>{if(t.metaKey||t.ctrlKey)return;const o=c(e),i=r(),s=i[i.length-1];s&&Math.abs(s.x-o.x)<1&&Math.abs(s.y-o.y)<1||(a([...i,o]),l(o),n(u()))},onDoubleClick:()=>{(()=>{const o=r();if(o.length<2)return;const i=d();if(!i)return;const s=kd(o,i.strokeWidth,i.lineEndings),c={...i,vertices:o,rect:s,type:Ot.POLYLINE,pageIndex:e.pageIndex,id:_n(),created:new Date};t(c),a([]),l(null),n(null)})()},onPointerMove:e=>{if(r().length>0){const t=c(e);l(t),n(u())}},onPointerCancel:()=>{a([]),l(null),n(null)}}}},Wd={annotationType:Ot.POLYGON,create(e){const{onCommit:t,onPreview:n,getTool:o,scale:i,pageSize:r}=e,[a,s]=fd([]),[l,c]=fd(null),d=e=>({x:ko(e.x,0,r.width),y:ko(e.y,0,r.height)}),u=()=>{const e=o();return e?{...e.defaults,color:e.defaults.color??"#000000",opacity:e.defaults.opacity??1,strokeWidth:e.defaults.strokeWidth??1,strokeColor:e.defaults.strokeColor??"#000000",strokeStyle:e.defaults.strokeStyle??Bt.SOLID,strokeDashArray:e.defaults.strokeDashArray??[],flags:e.defaults.flags??["print"]}:null},h=()=>{const o=a();if(o.length<3)return;const i=u();if(!i)return;const r=et(Je(o),i.strokeWidth/2),l={...i,vertices:o,rect:r,type:Ot.POLYGON,pageIndex:e.pageIndex,id:_n(),created:new Date};t(l),s([]),c(null),n(null)},m=()=>{const e=a(),t=l();if(0===e.length||!t)return null;const n=u();if(!n)return null;const o=et(Je([...e,t]),n.strokeWidth/2);return{type:Ot.POLYGON,bounds:o,data:{...n,rect:o,vertices:e,currentVertex:t}}};return{onClick:(e,t)=>{if(t.metaKey||t.ctrlKey)return;const o=d(e);if((e=>{const t=a();if(t.length<2)return!1;const n=14/i/2,o=t[0];return e.x>=o.x-n&&e.x<=o.x+n&&e.y>=o.y-n&&e.y<=o.y+n})(o)&&a().length>=3)return void h();const r=a(),l=r[r.length-1];l&&Math.abs(l.x-o.x)<1&&Math.abs(l.y-o.y)<1||(s([...r,o]),c(o),n(m()))},onDoubleClick:e=>{h()},onPointerMove:e=>{if(a().length>0){const t=d(e);c(t),n(m())}},onPointerCancel:e=>{s([]),c(null),n(null)}}}},Bd={annotationType:Ot.SQUARE,create(e){const{pageIndex:t,onCommit:n,onPreview:o,getTool:i,pageSize:r}=e,[a,s]=fd(null),l=e=>({x:ko(e.x,0,r.width),y:ko(e.y,0,r.height)}),c=()=>{const e=i();return e?{...e.defaults,flags:e.defaults.flags??["print"],strokeWidth:e.defaults.strokeWidth??2,strokeColor:e.defaults.strokeColor??"#000000",strokeStyle:e.defaults.strokeStyle??Bt.SOLID,strokeDashArray:e.defaults.strokeDashArray??[],color:e.defaults.color??"#000000",opacity:e.defaults.opacity??1}:null},d=jd({threshold:5,getTool:i,onClickDetected:(e,o)=>{const i=c();if(!i)return;const a=o.clickBehavior;if(!(null==a?void 0:a.enabled))return;const{width:s,height:l}=a.defaultSize,d=s/2,u=l/2,h=ko(e.x-d,0,r.width-s),m=ko(e.y-u,0,r.height-l),g=i.strokeWidth,p=g/2,f={origin:{x:h-p,y:m-p},size:{width:s+g,height:l+g}},v={...i,type:Ot.SQUARE,created:new Date,id:_n(),pageIndex:t,rect:f};n(v)}}),u=e=>{const t=a();if(!t)return null;const n=Math.min(t.x,e.x),o=Math.min(t.y,e.y),i=Math.abs(t.x-e.x),r=Math.abs(t.y-e.y),s=c();if(!s)return null;const l=s.strokeWidth,d=l/2,u={origin:{x:n-d,y:o-d},size:{width:i+l,height:r+l}};return{type:Ot.SQUARE,bounds:u,data:{rect:u,...s}}};return{onPointerDown:(e,t)=>{var n;const i=l(e);s(i),d.onStart(i),o(u(i)),null==(n=t.setPointerCapture)||n.call(t)},onPointerMove:e=>{const t=l(e);d.onMove(t),a()&&d.hasMoved()&&o(u(t))},onPointerUp:(e,i)=>{var r;if(!a())return;if(!c())return;const h=l(e);if(d.hasMoved()){const e=c();if(!e)return;const o=u(h);if(o){const i={...e,type:Ot.SQUARE,created:new Date,id:_n(),pageIndex:t,rect:o.data.rect};n(i)}}else d.onEnd(h);s(null),o(null),d.reset(),null==(r=i.releasePointerCapture)||r.call(i)},onPointerLeave:(e,t)=>{var n;s(null),o(null),d.reset(),null==(n=t.releasePointerCapture)||n.call(t)},onPointerCancel:(e,t)=>{var n;s(null),o(null),d.reset(),null==(n=t.releasePointerCapture)||n.call(t)}}}},qd={annotationType:Ot.STAMP,create(e){const{services:t,onCommit:n,getTool:o,pageSize:i,pageRotation:r}=e;return{onPointerDown:a=>{const s=o();if(!s)return;const{imageSrc:l,imageSize:c}=s.defaults,d=(t,o,l)=>{var c;const d={origin:{x:a.x-o/2,y:a.y-l/2},size:{width:o,height:l}};let u={...s.defaults,rect:d,type:Ot.STAMP,icon:s.defaults.icon??jt.Draft,subject:s.defaults.subject??"Stamp",flags:s.defaults.flags??["print"],pageIndex:e.pageIndex,id:_n(),created:new Date};(null==(c=s.behavior)?void 0:c.insertUpright)&&(u=Nd(u,r,!1)),u=Ld(u,i),n(u,{imageData:t})};l?t.processImage({source:l,maxWidth:i.width,maxHeight:i.height,onComplete:e=>d(e.imageData,(null==c?void 0:c.width)??e.width,(null==c?void 0:c.height)??e.height)}):t.requestFile({accept:"image/png,image/jpeg",onFile:e=>{t.processImage({source:e,maxWidth:i.width,maxHeight:i.height,onComplete:e=>d(e.imageData,e.width,e.height)})}})}}}},Gd={annotationType:Ot.CIRCLE,create(e){const{pageIndex:t,onCommit:n,onPreview:o,getTool:i,pageSize:r}=e,[a,s]=fd(null),l=e=>({x:ko(e.x,0,r.width),y:ko(e.y,0,r.height)}),c=()=>{const e=i();return e?{...e.defaults,strokeWidth:e.defaults.strokeWidth??2,strokeColor:e.defaults.strokeColor??"#000000",strokeStyle:e.defaults.strokeStyle??Bt.SOLID,strokeDashArray:e.defaults.strokeDashArray??[],color:e.defaults.color??"#000000",opacity:e.defaults.opacity??1,flags:e.defaults.flags??["print"]}:null},d=jd({threshold:5,getTool:i,onClickDetected:(e,o)=>{const i=c();if(!i)return;const a=o.clickBehavior;if(!(null==a?void 0:a.enabled))return;const{width:s,height:l}=a.defaultSize,d=s/2,u=l/2,h=ko(e.x-d,0,r.width-s),m=ko(e.y-u,0,r.height-l),g=i.strokeWidth,p=g/2,f={origin:{x:h-p,y:m-p},size:{width:s+g,height:l+g}},v={...i,type:Ot.CIRCLE,created:new Date,id:_n(),pageIndex:t,rect:f};n(v)}}),u=e=>{const t=a();if(!t)return null;const n=Math.min(t.x,e.x),o=Math.min(t.y,e.y),i=Math.abs(t.x-e.x),r=Math.abs(t.y-e.y),s=c();if(!s)return null;const l=s.strokeWidth,d=l/2,u={origin:{x:n-d,y:o-d},size:{width:i+l,height:r+l}};return{type:Ot.CIRCLE,bounds:u,data:{rect:u,...s}}};return{onPointerDown:(e,t)=>{var n;const i=l(e);s(i),d.onStart(i),o(u(i)),null==(n=t.setPointerCapture)||n.call(t)},onPointerMove:e=>{const t=l(e);d.onMove(t),a()&&d.hasMoved()&&o(u(t))},onPointerUp:(e,i)=>{var r;if(!a())return;if(!c())return;const h=l(e);if(d.hasMoved()){const e=c();if(!e)return;const o=u(h);if(o){const i={...e,type:Ot.CIRCLE,flags:["print"],created:new Date,id:_n(),pageIndex:t,rect:o.data.rect};n(i)}}else d.onEnd(h);s(null),o(null),d.reset(),null==(r=i.releasePointerCapture)||r.call(i)},onPointerLeave:(e,t)=>{var n;s(null),o(null),d.reset(),null==(n=t.releasePointerCapture)||n.call(t)},onPointerCancel:(e,t)=>{var n;s(null),o(null),d.reset(),null==(n=t.releasePointerCapture)||n.call(t)}}}},Vd={toolId:"__textMarkup__",handle(e,t,n){const o=e.getTool();if(o)for(const i of t){const t=_n();n().then(n=>{var r;e.createAnnotation(i.pageIndex,{...o.defaults,rect:i.rect,segmentRects:i.segmentRects,pageIndex:i.pageIndex,created:new Date,id:t,...null!=n&&{custom:{text:n}}}),(null==(r=o.behavior)?void 0:r.selectAfterCreate)&&e.selectAnnotation(i.pageIndex,t)})}}};function Kd(e){const t=e.size.height,n=t/2,o=n;return{origin:{x:e.origin.x+e.size.width-o/2,y:e.origin.y+t/2},size:{width:o,height:n}}}const Zd={toolId:"insertText",handle(e,t,n){const o=e.getTool();if(!o)return;const i=()=>({strokeColor:o.defaults.strokeColor??"#E44234",opacity:o.defaults.opacity??1,flags:o.defaults.flags??["print"]});for(const r of t){const t=r.segmentRects[r.segmentRects.length-1];if(!t)continue;const a=Kd(t),s=_n(),l=i();n().then(t=>{var n;e.createAnnotation(r.pageIndex,{type:Ot.CARET,id:s,pageIndex:r.pageIndex,rect:a,strokeColor:l.strokeColor,opacity:l.opacity,intent:"Insert",rectangleDifferences:{left:.5,top:.5,right:.5,bottom:.5},created:new Date,flags:l.flags,...null!=t&&{custom:{text:t}}}),(null==(n=o.behavior)?void 0:n.selectAfterCreate)&&e.selectAnnotation(r.pageIndex,s)})}}},Yd={toolId:"replaceText",handle(e,t,n){const o=e.getTool();if(!o)return;const i=()=>({strokeColor:o.defaults.strokeColor??"#E44234",opacity:o.defaults.opacity??1,flags:o.defaults.flags??["print"]});for(const r of t){const t=r.segmentRects[r.segmentRects.length-1];if(!t)continue;const a=Kd(t),s=_n(),l=_n(),c=i();n().then(t=>{var n;e.createAnnotation(r.pageIndex,{type:Ot.CARET,id:s,pageIndex:r.pageIndex,rect:a,strokeColor:c.strokeColor,opacity:c.opacity,intent:"Replace",rectangleDifferences:{left:.5,top:.5,right:.5,bottom:.5},created:new Date,flags:c.flags}),e.createAnnotation(r.pageIndex,{type:Ot.STRIKEOUT,id:l,pageIndex:r.pageIndex,rect:r.rect,segmentRects:r.segmentRects,strokeColor:c.strokeColor,opacity:c.opacity,intent:"StrikeOutTextEdit",inReplyToId:s,replyType:Ut.Group,created:new Date,flags:c.flags,...null!=t&&{custom:{text:t}}}),(null==(n=o.behavior)?void 0:n.selectAfterCreate)&&e.selectAnnotation(r.pageIndex,s)})}}},Xd=(e,t)=>{switch(t.type){case"vertex-edit":default:return t.changes;case"move":{if(!t.changes.rect)return t.changes;const{dx:n,dy:o,rects:i}=Td(e,t.changes.rect);return{...i,inkList:e.inkList.map(e=>({points:e.points.map(e=>({x:e.x+n,y:e.y+o}))}))}}case"resize":{if(!t.changes.rect)return t.changes;const{oldRect:n,resolvedRect:o,rects:i}=Ed(e,t.changes.rect,t.metadata),r=(e,t)=>({origin:{x:e.origin.x+t,y:e.origin.y+t},size:{width:Math.max(1,e.size.width-2*t),height:Math.max(1,e.size.height-2*t)}}),a=Math.min(o.size.width/n.size.width,o.size.height/n.size.height),s=Math.max(1,Math.round(e.strokeWidth*a)),l=r(n,e.strokeWidth/2),c=r(o,s/2),d=c.size.width/Math.max(l.size.width,1e-6),u=c.size.height/Math.max(l.size.height,1e-6);return{...i,inkList:e.inkList.map(e=>({points:e.points.map(e=>({x:c.origin.x+(e.x-l.origin.x)*d,y:c.origin.y+(e.y-l.origin.y)*u}))})),strokeWidth:s}}case"rotate":{const n=Rd(e,t);if(!n)return t.changes;const{dx:o,dy:i}=_d(e,n);return{...n,inkList:e.inkList.map(e=>({points:e.points.map(e=>({x:e.x+o,y:e.y+i}))}))}}case"property-update":{if(!(void 0!==t.changes.strokeWidth||void 0!==t.changes.rotation))return t.changes;const n={...e,...t.changes},o=n.inkList.flatMap(e=>e.points),i=et(Je(o),n.strokeWidth/2),r=t.changes.rotation??e.rotation??0;return e.unrotatedRect||void 0!==t.changes.rotation?{...t.changes,unrotatedRect:i,rect:dt(i,r,Sd(e))}:{...t.changes,rect:i}}}},Qd=(e,t)=>{switch(t.type){case"vertex-edit":if(t.changes.linePoints){const{start:n,end:o}=t.changes.linePoints,i=[n,o],r=Md(e,i,kd(i,e.strokeWidth,e.lineEndings));return{...Id(e,kd(r,e.strokeWidth,e.lineEndings)),linePoints:{start:r[0],end:r[1]}}}return t.changes;case"move":{if(!t.changes.rect)return t.changes;const{dx:n,dy:o,rects:i}=Td(e,t.changes.rect);return{...i,linePoints:{start:{x:e.linePoints.start.x+n,y:e.linePoints.start.y+o},end:{x:e.linePoints.end.x+n,y:e.linePoints.end.y+o}}}}case"resize":{if(!t.changes.rect)return t.changes;const{scaleX:n,scaleY:o,oldRect:i,resolvedRect:r,rects:a}=Ed(e,t.changes.rect,t.metadata);return{...a,linePoints:{start:{x:r.origin.x+(e.linePoints.start.x-i.origin.x)*n,y:r.origin.y+(e.linePoints.start.y-i.origin.y)*o},end:{x:r.origin.x+(e.linePoints.end.x-i.origin.x)*n,y:r.origin.y+(e.linePoints.end.y-i.origin.y)*o}}}}case"rotate":{const n=Rd(e,t);if(!n)return t.changes;const{dx:o,dy:i}=_d(e,n);return{...n,linePoints:{start:{x:e.linePoints.start.x+o,y:e.linePoints.start.y+i},end:{x:e.linePoints.end.x+o,y:e.linePoints.end.y+i}}}}case"property-update":{if(!(void 0!==t.changes.strokeWidth||void 0!==t.changes.lineEndings||void 0!==t.changes.rotation))return t.changes;const n={...e,...t.changes},o=kd([n.linePoints.start,n.linePoints.end],n.strokeWidth,n.lineEndings),i=t.changes.rotation??e.rotation??0;return e.unrotatedRect||void 0!==t.changes.rotation?{...t.changes,unrotatedRect:o,rect:dt(o,i,Sd(e))}:{...t.changes,rect:o}}default:return t.changes}},Jd=(e,t)=>{switch(t.type){case"vertex-edit":if(t.changes.vertices&&t.changes.vertices.length){const n=t.changes.vertices,o=Md(e,n,kd(n,e.strokeWidth,e.lineEndings));return{...Id(e,kd(o,e.strokeWidth,e.lineEndings)),vertices:o}}return t.changes;case"move":{if(!t.changes.rect)return t.changes;const{dx:n,dy:o,rects:i}=Td(e,t.changes.rect);return{...i,vertices:e.vertices.map(e=>({x:e.x+n,y:e.y+o}))}}case"resize":{if(!t.changes.rect)return t.changes;const{scaleX:n,scaleY:o,oldRect:i,resolvedRect:r,rects:a}=Ed(e,t.changes.rect,t.metadata);return{...a,vertices:e.vertices.map(e=>({x:r.origin.x+(e.x-i.origin.x)*n,y:r.origin.y+(e.y-i.origin.y)*o}))}}case"rotate":{const n=Rd(e,t);if(!n)return t.changes;const{dx:o,dy:i}=_d(e,n);return{...n,vertices:e.vertices.map(e=>({x:e.x+o,y:e.y+i}))}}case"property-update":{if(!(void 0!==t.changes.strokeWidth||void 0!==t.changes.lineEndings||void 0!==t.changes.rotation))return t.changes;const n={...e,...t.changes},o=kd(n.vertices,n.strokeWidth,n.lineEndings),i=t.changes.rotation??e.rotation??0;return e.unrotatedRect||void 0!==t.changes.rotation?{...t.changes,unrotatedRect:o,rect:dt(o,i,Sd(e))}:{...t.changes,rect:o}}default:return t.changes}},eu=(e,t)=>{switch(t.type){case"vertex-edit":if(t.changes.vertices&&t.changes.vertices.length){const n=e.strokeWidth/2,o=t.changes.vertices,i=Md(e,o,et(Je(o),n));return{...Id(e,et(Je(i),n)),vertices:i}}return t.changes;case"move":{if(!t.changes.rect)return t.changes;const{dx:n,dy:o,rects:i}=Td(e,t.changes.rect);return{...i,vertices:e.vertices.map(e=>({x:e.x+n,y:e.y+o}))}}case"resize":{if(!t.changes.rect)return t.changes;const{scaleX:n,scaleY:o,oldRect:i,resolvedRect:r,rects:a}=Ed(e,t.changes.rect,t.metadata);return{...a,vertices:e.vertices.map(e=>({x:r.origin.x+(e.x-i.origin.x)*n,y:r.origin.y+(e.y-i.origin.y)*o}))}}case"rotate":{const n=Rd(e,t);if(!n)return t.changes;const{dx:o,dy:i}=_d(e,n);return{...n,vertices:e.vertices.map(e=>({x:e.x+o,y:e.y+i}))}}case"property-update":{if(!(void 0!==t.changes.strokeWidth||void 0!==t.changes.rotation))return t.changes;const n={...e,...t.changes},o=n.strokeWidth/2,i=et(Je(n.vertices),o),r=t.changes.rotation??e.rotation??0;return e.unrotatedRect||void 0!==t.changes.rotation?{...t.changes,unrotatedRect:i,rect:dt(i,r,Sd(e))}:{...t.changes,rect:i}}default:return t.changes}},tu=(e,t)=>{switch(t.type){case"move":return t.changes.rect?Td(e,t.changes.rect).rects:t.changes;case"resize":return t.changes.rect?Ed(e,t.changes.rect,t.metadata).rects:t.changes;case"rotate":return Rd(e,t)??t.changes;case"property-update":return void 0!==t.changes.rotation?{...t.changes,...zd(e,t.changes.rotation)}:t.changes;default:return t.changes}},nu=(e,t)=>{switch(t.type){case"move":return t.changes.rect?Td(e,t.changes.rect).rects:t.changes;case"resize":return t.changes.rect?Ed(e,t.changes.rect,t.metadata).rects:t.changes;case"rotate":return Rd(e,t)??t.changes;case"property-update":return void 0!==t.changes.rotation?{...t.changes,...zd(e,t.changes.rotation)}:t.changes;default:return t.changes}},ou=(e,t)=>{switch(t.type){case"move":return t.changes.rect?Td(e,t.changes.rect).rects:t.changes;case"resize":return t.changes.rect?Ed(e,t.changes.rect,t.metadata).rects:t.changes;case"rotate":return Rd(e,t)??t.changes;case"property-update":return void 0!==t.changes.rotation?{...t.changes,...zd(e,t.changes.rotation)}:t.changes;default:return t.changes}},iu=(e,t)=>{switch(t.type){case"move":return t.changes.rect?Td(e,t.changes.rect).rects:t.changes;case"resize":return t.changes.rect?Ed(e,t.changes.rect,t.metadata).rects:t.changes;case"rotate":return Rd(e,t)??t.changes;case"property-update":return void 0!==t.changes.rotation?{...t.changes,...zd(e,t.changes.rotation)}:t.changes;default:return t.changes}};function ru(e,t,n,o){const i=o*Math.PI/180,r=Math.abs(Math.cos(i)),a=Math.abs(Math.sin(i)),s=r*r-a*a,l=e.size.width,c=e.size.height;let d,u;if(Math.abs(s)>1e-6)d=(r*l-a*c)/s,u=(r*c-a*l)/s,d=Math.max(d,1),u=Math.max(u,1);else{const e=t.size.width*t.size.height,o=l*c,i=e>0?Math.sqrt(o/e):1;d=n.size.width*i,u=n.size.height*i}return{origin:{x:e.origin.x+l/2-d/2,y:e.origin.y+c/2-u/2},size:{width:d,height:u}}}const au=class extends bo{constructor(e,t,n){var o,i,r;super(e,t),this.ANNOTATION_HISTORY_TOPIC="annotations",this.state$=Do(),this.pendingContexts=new Map,this.isInitialLoadComplete=new Map,this.importQueue=new Map,this.commitInProgress=new Map,this.handlerFactories=new Map,this.selectionHandlerFactories=new Map,this.activeTool$=Do(),this.events$=Do(),this.toolsChange$=Do(),this.patchRegistry=new Pd,this.appearanceCache=new Map,this.unifiedDragStates=new Map,this.unifiedDrag$=Do(),this.unifiedResizeStates=new Map,this.unifiedResize$=Do(),this.unifiedRotateStates=new Map,this.unifiedRotate$=Do(),this.config=n,this.selection=(null==(o=t.getPlugin("selection"))?void 0:o.provides())??null,this.history=(null==(i=t.getPlugin("history"))?void 0:i.provides())??null,this.interactionManager=(null==(r=t.getPlugin("interaction-manager"))?void 0:r.provides())??null,this.registerHandlerFactories(),this.registerSelectionHandlerFactories(),this.registerBuiltInPatches()}onDocumentLoadingStarted(e){this.dispatch(function(e,t){return{type:Ac,payload:{documentId:e,state:t}}}(e,{pages:{},byUid:{},selectedUids:[],selectedUid:null,activeToolId:null,hasPendingChanges:!1})),this.pendingContexts.set(e,new Map),this.isInitialLoadComplete.set(e,!1),this.importQueue.set(e,[]),this.logger.debug("AnnotationPlugin","DocumentOpened",`Initialized annotation state for document: ${e}`)}onDocumentLoaded(e){const t=this.getCoreDocument(e);if((null==t?void 0:t.document)&&this.getAllAnnotations(e,t.document),this.selection)for(const e of this.state.tools)e.interaction.textSelection&&this.selection.enableForMode(e.interaction.mode??e.id,{showSelectionRects:e.interaction.showSelectionRects??!1,enableSelection:!0,enableMarquee:!1})}onDocumentClosed(e){this.dispatch(function(e){return{type:Mc,payload:e}}(e)),this.pendingContexts.delete(e),this.isInitialLoadComplete.delete(e),this.importQueue.delete(e),this.appearanceCache.delete(e),this.logger.debug("AnnotationPlugin","DocumentClosed",`Cleaned up annotation state for document: ${e}`)}registerHandlerFactories(){this.handlerFactories.set(Ot.CIRCLE,Gd),this.handlerFactories.set(Ot.SQUARE,Bd),this.handlerFactories.set(Ot.STAMP,qd),this.handlerFactories.set(Ot.POLYGON,Wd),this.handlerFactories.set(Ot.POLYLINE,Hd),this.handlerFactories.set(Ot.LINE,Ud),this.handlerFactories.set(Ot.INK,vd),this.handlerFactories.set(Ot.FREETEXT,Fd),this.handlerFactories.set(Ot.TEXT,$d)}registerSelectionHandlerFactories(){this.selectionHandlerFactories.set("insertText",Zd),this.selectionHandlerFactories.set("replaceText",Yd)}registerBuiltInPatches(){this.patchRegistry.register(Ot.INK,Xd),this.patchRegistry.register(Ot.LINE,Qd),this.patchRegistry.register(Ot.POLYLINE,Jd),this.patchRegistry.register(Ot.POLYGON,eu),this.patchRegistry.register(Ot.CIRCLE,tu),this.patchRegistry.register(Ot.SQUARE,nu),this.patchRegistry.register(Ot.FREETEXT,ou),this.patchRegistry.register(Ot.STAMP,iu)}async initialize(){var e,t,n;this.state.tools.forEach(e=>this.registerInteractionForTool(e)),this.history&&this.history.onHistoryChange(e=>{e.topic===this.ANNOTATION_HISTORY_TOPIC&&!1!==this.config.autoCommit&&this.commit(e.documentId)}),null==(e=this.interactionManager)||e.onModeChange(e=>{var t,n;const o=(null==(t=this.state.tools.find(t=>(t.interaction.mode??t.id)===e.activeMode))?void 0:t.id)??null;o!==((null==(n=this.state.documents[e.documentId])?void 0:n.activeToolId)??null)&&e.documentId&&this.dispatch(Kc(e.documentId,o))}),null==(t=this.selection)||t.onMarqueeEnd(({documentId:e,pageIndex:t,rect:n,modeId:o})=>{if("pointerMode"!==o)return;const i=this.state.documents[e];if(!i)return;const r=(i.pages[t]??[]).map(e=>i.byUid[e]).filter(e=>void 0!==e).filter(e=>nd(e)).filter(e=>function(e,t){return!(e.origin.x+e.size.widthe.object.id);if(r.length>0){const t=new Set;for(const n of r)if(this.isInGroupMethod(n,e)){const o=this.getGroupMembersMethod(n,e);for(const e of o)t.add(e.object.id)}else t.add(n);this.setSelectionMethod([...t],e)}}),null==(n=this.selection)||n.onEndSelection(({documentId:e})=>{var t,n,o,i;if(!this.checkPermission(e,Qt.ModifyAnnotations))return;const r=this.getActiveTool(e);if(!r||!r.interaction.textSelection)return;const a=null==(t=this.selection)?void 0:t.getFormattedSelection(),s=null==(n=this.selection)?void 0:n.getSelectedText();if(!a||!s)return;const l={toolId:r.id,documentId:e,getTool:()=>this.getActiveTool(e)??null,createAnnotation:(t,n)=>this.createAnnotation(t,n,void 0,e),selectAnnotation:(t,n)=>this.selectAnnotation(t,n,e)};(this.selectionHandlerFactories.get(r.id)??Vd).handle(l,a,()=>new Promise(e=>{s.wait(t=>e(t.join("\n")),()=>e(void 0))})),(null==(o=r.behavior)?void 0:o.deactivateToolAfterCreate)&&this.setActiveTool(null,e),null==(i=this.selection)||i.clear()})}registerInteractionForTool(e){var t;null==(t=this.interactionManager)||t.registerMode({id:e.interaction.mode??e.id,scope:"page",exclusive:e.interaction.exclusive,cursor:e.interaction.cursor})}buildCapability(){return{getActiveTool:()=>this.getActiveTool(),setActiveTool:e=>this.setActiveTool(e),getState:()=>this.getDocumentState(),getPageAnnotations:e=>this.getPageAnnotations(e),getSelectedAnnotation:()=>this.getSelectedAnnotation(),getSelectedAnnotations:()=>this.getSelectedAnnotationsMethod(),getSelectedAnnotationIds:()=>this.getSelectedAnnotationIdsMethod(),getAnnotationById:e=>this.getAnnotationById(e),selectAnnotation:(e,t)=>this.selectAnnotation(e,t),toggleSelection:(e,t)=>this.toggleSelectionMethod(e,t),addToSelection:(e,t)=>this.addToSelectionMethod(e,t),removeFromSelection:e=>this.removeFromSelectionMethod(e),setSelection:e=>this.setSelectionMethod(e),deselectAnnotation:()=>this.deselectAnnotation(),importAnnotations:e=>this.importAnnotations(e),createAnnotation:(e,t,n)=>this.createAnnotation(e,t,n),updateAnnotation:(e,t,n)=>this.updateAnnotation(e,t,n),updateAnnotations:e=>this.updateAnnotationsMethod(e),moveAnnotation:(e,t,n,o,i)=>this.moveAnnotationMethod(e,t,n,o,i),deleteAnnotation:(e,t)=>this.deleteAnnotation(e,t),deleteAnnotations:(e,t)=>this.deleteAnnotationsMethod(e,t),purgeAnnotation:(e,t,n)=>this.purgeAnnotationMethod(e,t,n),renderAnnotation:e=>this.renderAnnotation(e),getPageAppearances:(e,t,n)=>this.getPageAppearances(e,t,n),invalidatePageAppearances:(e,t)=>this.invalidatePageAppearances(e,t),commit:()=>this.commit(),getAttachedLinks:(e,t)=>this.getAttachedLinksMethod(e,t),hasAttachedLinks:(e,t)=>this.hasAttachedLinksMethod(e,t),deleteAttachedLinks:(e,t)=>this.deleteAttachedLinksMethod(e,t),groupAnnotations:e=>this.groupAnnotationsMethod(e),ungroupAnnotations:(e,t)=>this.ungroupAnnotationsMethod(e,t),getGroupMembers:(e,t)=>this.getGroupMembersMethod(e,t),isInGroup:(e,t)=>this.isInGroupMethod(e,t),forDocument:e=>this.createAnnotationScope(e),getTools:()=>this.state.tools,getTool:e=>this.getTool(e),addTool:e=>{this.dispatch((e=>({type:Wc,payload:e}))(e)),this.registerInteractionForTool(e)},findToolForAnnotation:e=>this.findToolForAnnotation(e),setToolDefaults:(e,t)=>this.dispatch(((e,t)=>({type:Hc,payload:{toolId:e,patch:t}}))(e,t)),getColorPresets:()=>[...this.state.colorPresets],addColorPreset:e=>this.dispatch((e=>({type:Uc,payload:e}))(e)),transformAnnotation:(e,t)=>this.transformAnnotation(e,t),registerPatchFunction:(e,t)=>this.registerPatchFunction(e,t),onStateChange:this.state$.on,onActiveToolChange:this.activeTool$.on,onAnnotationEvent:this.events$.on,onToolsChange:this.toolsChange$.on}}createAnnotationScope(e){return{getState:()=>this.getDocumentState(e),getPageAnnotations:t=>this.getPageAnnotations(t,e),getSelectedAnnotation:()=>this.getSelectedAnnotation(e),getSelectedAnnotations:()=>this.getSelectedAnnotationsMethod(e),getSelectedAnnotationIds:()=>this.getSelectedAnnotationIdsMethod(e),getAnnotationById:t=>this.getAnnotationById(t,e),selectAnnotation:(t,n)=>this.selectAnnotation(t,n,e),toggleSelection:(t,n)=>this.toggleSelectionMethod(t,n,e),addToSelection:(t,n)=>this.addToSelectionMethod(t,n,e),removeFromSelection:t=>this.removeFromSelectionMethod(t,e),setSelection:t=>this.setSelectionMethod(t,e),deselectAnnotation:()=>this.deselectAnnotation(e),getActiveTool:()=>this.getActiveTool(e),setActiveTool:t=>this.setActiveTool(t,e),findToolForAnnotation:e=>this.findToolForAnnotation(e),importAnnotations:t=>this.importAnnotations(t,e),createAnnotation:(t,n,o)=>this.createAnnotation(t,n,o,e),updateAnnotation:(t,n,o)=>this.updateAnnotation(t,n,o,e),updateAnnotations:t=>this.updateAnnotationsMethod(t,e),moveAnnotation:(t,n,o,i)=>this.moveAnnotationMethod(t,n,o,i,e),deleteAnnotation:(t,n)=>this.deleteAnnotation(t,n,e),deleteAnnotations:t=>this.deleteAnnotationsMethod(t,e),purgeAnnotation:(t,n)=>this.purgeAnnotationMethod(t,n,e),renderAnnotation:t=>this.renderAnnotation(t,e),getPageAppearances:(t,n)=>this.getPageAppearances(t,n,e),invalidatePageAppearances:t=>this.invalidatePageAppearances(t,e),commit:()=>this.commit(e),getAttachedLinks:t=>this.getAttachedLinksMethod(t,e),hasAttachedLinks:t=>this.hasAttachedLinksMethod(t,e),deleteAttachedLinks:t=>this.deleteAttachedLinksMethod(t,e),groupAnnotations:()=>this.groupAnnotationsMethod(e),ungroupAnnotations:t=>this.ungroupAnnotationsMethod(t,e),getGroupMembers:t=>this.getGroupMembersMethod(t,e),isInGroup:t=>this.isInGroupMethod(t,e),getGroupingAction:()=>this.getGroupingActionMethod(e),onStateChange:t=>this.state$.on(n=>{n.documentId===e&&t(n.state)}),onAnnotationEvent:t=>this.events$.on(n=>{n.documentId===e&&t(n)}),onActiveToolChange:t=>this.activeTool$.on(n=>{n.documentId===e&&t(n.tool)})}}onStoreUpdated(e,t){for(const n in t.documents){const o=e.documents[n],i=t.documents[n];o!==i&&(this.state$.emit({documentId:n,state:i}),o&&o.activeToolId!==i.activeToolId&&this.activeTool$.emit({documentId:n,tool:this.getActiveTool(n)}),(null==o?void 0:o.selectedUids)!==i.selectedUids&&this.updateAnnotationSelectionActivity(n,i))}if(e.tools!==t.tools){for(const e in t.documents)this.activeTool$.emit({documentId:e,tool:this.getActiveTool(e)});this.toolsChange$.emit({tools:t.tools})}}registerPatchFunction(e,t){this.patchRegistry.register(e,t)}transformAnnotation(e,t){const n={type:t.type,changes:t.changes,metadata:t.metadata};return this.patchRegistry.transform(e,n)}registerPageHandlers(e,t,n,o){var i;const r=this.getCoreDocument(e),a=null==(i=null==r?void 0:r.document)?void 0:i.pages[t];if(!a)return()=>{};if(!this.interactionManager)return()=>{};const s=[],l=((a.rotation??0)+((null==r?void 0:r.rotation)??0))%4;for(const i of this.state.tools){if(!i.defaults.type)continue;const r=this.handlerFactories.get(i.defaults.type);if(!r)continue;const c={pageIndex:t,pageSize:a.size,pageRotation:l,scale:n,services:o.services,onPreview:e=>o.onPreview(i.id,e),onCommit:(n,o)=>{var r,a;this.createAnnotation(t,n,o,e),(null==(r=i.behavior)?void 0:r.deactivateToolAfterCreate)&&this.setActiveTool(null,e),(null==(a=i.behavior)?void 0:a.selectAfterCreate)&&this.selectAnnotation(t,n.id,e)},getTool:()=>this.state.tools.find(e=>e.id===i.id)},d=this.interactionManager.registerHandlers({documentId:e,modeId:i.interaction.mode??i.id,handlers:r.create(c),pageIndex:t});s.push(d)}return()=>s.forEach(e=>e())}getDocumentState(e){const t=e??this.getActiveDocumentId(),n=this.state.documents[t];if(!n)throw new Error(`Annotation state not found for document: ${t}`);return n}getAllAnnotations(e,t){this.engine.getAllAnnotations(t).wait(t=>{this.dispatch(((e,t)=>({type:Pc,payload:{documentId:e,annotations:t}}))(e,t)),this.isInitialLoadComplete.set(e,!0);const n=this.importQueue.get(e);n&&n.length>0&&this.processImportQueue(e),this.events$.emit({type:"loaded",documentId:e,total:Object.values(t).reduce((e,t)=>e+t.length,0)})},Ln)}getPageAnnotations(e,t){const{pageIndex:n}=e,o=t??this.getActiveDocumentId(),i=this.getCoreDocument(o),r=null==i?void 0:i.document;if(!r)return nn.reject({code:tn.NotFound,message:"Document not found"});const a=r.pages.find(e=>e.index===n);return a?this.engine.getPageAnnotations(r,a):nn.reject({code:tn.NotFound,message:"Page not found"})}getSelectedAnnotation(e){return(e=>e.selectedUids.length>0?e.byUid[e.selectedUids[0]]??null:null)(this.getDocumentState(e))}getAnnotationById(e,t){return((e,t)=>e.byUid[t]??null)(this.getDocumentState(t),e)}renderAnnotation({pageIndex:e,annotation:t,options:n},o){const i=o??this.getActiveDocumentId(),r=this.getCoreDocument(i),a=null==r?void 0:r.document;if(!a)return nn.reject({code:tn.NotFound,message:"Document not found"});const s=a.pages.find(t=>t.index===e);return s?this.engine.renderPageAnnotation(a,s,t,n):nn.reject({code:tn.NotFound,message:"Page not found"})}getPageAppearances(e,t,n){const o=n??this.getActiveDocumentId(),i=this.getCoreDocument(o),r=null==i?void 0:i.document;if(!r)return nn.reject({code:tn.NotFound,message:"Document not found"});const a=r.pages.find(t=>t.index===e);if(!a)return nn.reject({code:tn.NotFound,message:"Page not found"});let s=this.appearanceCache.get(o);s||(s=new Map,this.appearanceCache.set(o,s));const l=s.get(e);if(l&&!t){const e=new Ct;return e.resolve(l),e}const c=this.engine.renderPageAnnotations(r,a,t),d=new Ct;return c.wait(t=>{s.set(e,t),d.resolve(t)},e=>{d.fail(e)}),d}invalidatePageAppearances(e,t){const n=t??this.getActiveDocumentId(),o=this.appearanceCache.get(n);o&&o.delete(e)}invalidateAnnotationAppearance(e,t,n){const o=n??this.getActiveDocumentId(),i=this.appearanceCache.get(o);if(!i)return;const r=i.get(t);r&&delete r[e]}importAnnotations(e,t){const n=t??this.getActiveDocumentId();if(!this.isInitialLoadComplete.get(n)){const t=this.importQueue.get(n)||[];return t.push(...e),void this.importQueue.set(n,t)}this.processImportItems(n,e)}processImportQueue(e){const t=this.importQueue.get(e);if(!t||0===t.length)return;const n=[...t];this.importQueue.set(e,[]),this.processImportItems(e,n)}processImportItems(e,t){const n=this.pendingContexts.get(e);if(n){for(const o of t){const{annotation:t,ctx:i}=o,r=t.pageIndex,a=t.id;this.dispatch(Zc(e,r,t)),i&&n.set(a,i)}!1!==this.config.autoCommit&&this.commit(e)}}createAnnotation(e,t,n,o){const i=o??this.getActiveDocumentId();if(!this.checkPermission(i,Qt.ModifyAnnotations))return void this.logger.debug("AnnotationPlugin","CreateAnnotation",`Cannot create annotation: document ${i} lacks ModifyAnnotations permission`);const r=t.id,a=this.pendingContexts.get(i);if(!a)return;const s={...t,author:t.author??this.config.annotationAuthor},l=()=>{this.dispatch(Zc(i,e,s)),n&&a.set(r,n),this.events$.emit({type:"create",documentId:i,annotation:s,pageIndex:e,ctx:n,committed:!1})};if(!this.history)return l(),void(this.config.autoCommit&&this.commit(i));const c={execute:l,undo:()=>{a.delete(r),this.dispatch(Bc(i)),this.dispatch(Qc(i,e,r)),this.events$.emit({type:"delete",documentId:i,annotation:s,pageIndex:e,committed:!1})},metadata:{annotationIds:[r]}};this.history.forDocument(i).register(c,this.ANNOTATION_HISTORY_TOPIC)}buildPatch(e,t){return"rect"in t?t:this.transformAnnotation(e,{type:"property-update",changes:t})}updateAnnotation(e,t,n,o){const i=o??this.getActiveDocumentId();if(!this.checkPermission(i,Qt.ModifyAnnotations))return void this.logger.debug("AnnotationPlugin","UpdateAnnotation",`Cannot update annotation: document ${i} lacks ModifyAnnotations permission`);const r=this.getDocumentState(i).byUid[t].object,a=this.buildPatch(r,{...n,author:n.author??this.config.annotationAuthor}),s=()=>{this.dispatch(Yc(i,e,t,a)),this.events$.emit({type:"update",documentId:i,annotation:r,pageIndex:e,patch:a,committed:!1})};if(!this.history)return s(),void(!1!==this.config.autoCommit&&this.commit(i));const l=Object.fromEntries(Object.keys(n).map(e=>[e,r[e]])),c={execute:s,undo:()=>{this.dispatch(Yc(i,e,t,l)),this.events$.emit({type:"update",documentId:i,annotation:r,pageIndex:e,patch:l,committed:!1})},metadata:{annotationIds:[t]}};this.history.forDocument(i).register(c,this.ANNOTATION_HISTORY_TOPIC)}deleteAnnotation(e,t,n){var o;const i=n??this.getActiveDocumentId();if(!this.checkPermission(i,Qt.ModifyAnnotations))return void this.logger.debug("AnnotationPlugin","DeleteAnnotation",`Cannot delete annotation: document ${i} lacks ModifyAnnotations permission`);const r=this.getDocumentState(i),a=null==(o=r.byUid[t])?void 0:o.object;if(!a)return;const s=((e,t)=>{const n=[];for(const o of Object.values(e.pages))for(const i of o){const o=e.byUid[i];o&&"inReplyToId"in o.object&&o.object.inReplyToId===t&&n.push({id:o.object.id,pageIndex:o.object.pageIndex})}return n})(r,t),l=s.map(e=>{var t;return null==(t=r.byUid[e.id])?void 0:t.object}).filter(e=>void 0!==e),c=()=>{var n;for(const e of s){const t=null==(n=r.byUid[e.id])?void 0:n.object;t&&(this.dispatch(Qc(i,e.pageIndex,e.id)),this.events$.emit({type:"delete",documentId:i,annotation:t,pageIndex:e.pageIndex,committed:!1}))}this.dispatch(Bc(i)),this.dispatch(Qc(i,e,t)),this.events$.emit({type:"delete",documentId:i,annotation:a,pageIndex:e,committed:!1})};if(!this.history)return c(),void(!1!==this.config.autoCommit&&this.commit(i));const d={execute:c,undo:()=>{this.dispatch(Zc(i,e,a)),this.events$.emit({type:"create",documentId:i,annotation:a,pageIndex:e,committed:!1});for(const e of l)this.dispatch(Zc(i,e.pageIndex,e)),this.events$.emit({type:"create",documentId:i,annotation:e,pageIndex:e.pageIndex,committed:!1})},metadata:{annotationIds:[t,...s.map(e=>e.id)]}};this.history.forDocument(i).register(d,this.ANNOTATION_HISTORY_TOPIC)}deleteAnnotationsMethod(e,t){for(const{pageIndex:n,id:o}of e)this.deleteAnnotation(n,o,t)}purgeAnnotationMethod(e,t,n){const o=n??this.getActiveDocumentId();this.dispatch(Jc(o,e,t))}selectAnnotation(e,t,n){const o=n??this.getActiveDocumentId();if(this.isInGroupMethod(t,o)){const e=this.getGroupMembersMethod(t,o).map(e=>e.object.id);this.dispatch(Vc(o,e))}else this.dispatch(((e,t,n)=>({type:Dc,payload:{documentId:e,pageIndex:t,id:n}}))(o,e,t))}deselectAnnotation(e){const t=e??this.getActiveDocumentId();this.dispatch(Bc(t))}updateAnnotationSelectionActivity(e,t){var n,o;if(0===t.selectedUids.length)return void(null==(n=this.interactionManager)||n.releasePageActivity(e,"annotation-selection"));const i=t.selectedUids[0],r=t.byUid[i];r&&(null==(o=this.interactionManager)||o.claimPageActivity(e,"annotation-selection",r.object.pageIndex))}getSelectedAnnotationsMethod(e){return id(this.getDocumentState(e))}getSelectedAnnotationIdsMethod(e){return rd(this.getDocumentState(e))}toggleSelectionMethod(e,t,n){const o=n??this.getActiveDocumentId(),i=this.getDocumentState(o);if(i.selectedUids.includes(t))this.dispatch(Gc(o,t));else if(this.isInGroupMethod(t,o)){const e=this.getGroupMembersMethod(t,o);for(const t of e)i.selectedUids.includes(t.object.id)||this.dispatch(qc(o,t.object.pageIndex,t.object.id))}else this.dispatch(qc(o,e,t))}addToSelectionMethod(e,t,n){const o=n??this.getActiveDocumentId();this.dispatch(qc(o,e,t))}removeFromSelectionMethod(e,t){const n=t??this.getActiveDocumentId();this.dispatch(Gc(n,e))}setSelectionMethod(e,t){const n=t??this.getActiveDocumentId();this.dispatch(Vc(n,e))}getAttachedLinksMethod(e,t){return sd(this.getDocumentState(t),e)}hasAttachedLinksMethod(e,t){return this.getAttachedLinksMethod(e,t).length>0}deleteAttachedLinksMethod(e,t){const n=this.getAttachedLinksMethod(e,t);for(const e of n)this.deleteAnnotation(e.object.pageIndex,e.object.id,t)}groupAnnotationsMethod(e){const t=e??this.getActiveDocumentId();if(!this.checkPermission(t,Qt.ModifyAnnotations))return void this.logger.debug("AnnotationPlugin","GroupAnnotations",`Cannot group annotations: document ${t} lacks ModifyAnnotations permission`);const n=this.getSelectedAnnotationsMethod(t);if(n.length<2)return void this.logger.debug("AnnotationPlugin","GroupAnnotations","Need at least 2 annotations to group");const o=n[0],i=n.slice(1).map(e=>({pageIndex:e.object.pageIndex,id:e.object.id,patch:{inReplyToId:o.object.id,replyType:Ut.Group}}));this.updateAnnotationsMethod(i,t)}ungroupAnnotationsMethod(e,t){const n=t??this.getActiveDocumentId();if(!this.checkPermission(n,Qt.ModifyAnnotations))return void this.logger.debug("AnnotationPlugin","UngroupAnnotations",`Cannot ungroup annotations: document ${n} lacks ModifyAnnotations permission`);const o=this.getGroupMembersMethod(e,n).filter(e=>e.object.inReplyToId&&e.object.replyType===Ut.Group).map(e=>({pageIndex:e.object.pageIndex,id:e.object.id,patch:{inReplyToId:void 0,replyType:void 0}}));o.length>0&&this.updateAnnotationsMethod(o,n)}getGroupMembersMethod(e,t){return cd(this.getDocumentState(t),e)}isInGroupMethod(e,t){return dd(this.getDocumentState(t),e)}getGroupingActionMethod(e){return(e=>{const t=id(e);if(0===t.length)return"disabled";const n=t[0].object.id;if(dd(e,n)){const o=cd(e,n),i=new Set(o.map(e=>e.object.id));if(t.every(e=>i.has(e.object.id)))return"ungroup"}return t.length>=2?"group":"disabled"})(this.getDocumentState(e))}computeCombinedConstraints(e){let t=1/0,n=1/0,o=1/0,i=1/0;for(const r of e){const e=r.rect.origin.y,a=r.pageSize.height-(r.rect.origin.y+r.rect.size.height),s=r.rect.origin.x,l=r.pageSize.width-(r.rect.origin.x+r.rect.size.width);t=Math.min(t,e),n=Math.min(n,a),o=Math.min(o,s),i=Math.min(i,l)}return isFinite(t)||(t=0),isFinite(n)||(n=0),isFinite(o)||(o=0),isFinite(i)||(i=0),{maxUp:t,maxDown:n,maxLeft:o,maxRight:i}}clampDelta(e,t){return{x:Math.max(-t.maxLeft,Math.min(t.maxRight,e.x)),y:Math.max(-t.maxUp,Math.min(t.maxDown,e.y))}}startDrag(e,t){const{annotationIds:n,pageSize:o}=t,i=[];for(const t of n){const n=this.getAttachedLinksMethod(t,e);for(const e of n)i.includes(e.object.id)||i.push(e.object.id)}const r=[...n,...i],a=new Map,s=[];for(const t of r){const n=this.getAnnotationById(t,e);n&&(a.set(t,{...n.object.rect}),s.push({id:t,rect:n.object.rect,pageIndex:n.object.pageIndex,pageSize:o}))}const l={documentId:e,isDragging:!0,primaryIds:n,attachedLinkIds:i,allParticipantIds:r,originalRects:a,delta:{x:0,y:0},combinedConstraints:this.computeCombinedConstraints(s)};this.unifiedDragStates.set(e,l),this.unifiedDrag$.emit({documentId:e,type:"start",state:l,previewPatches:{}})}computeDragPreviewPatches(e,t){const n={};for(const o of e.allParticipantIds){const i=this.getAnnotationById(o,t);if(!i)continue;const r=e.originalRects.get(o);if(!r)continue;const a={...r,origin:{x:r.origin.x+e.delta.x,y:r.origin.y+e.delta.y}};n[o]=this.transformAnnotation(i.object,{type:"move",changes:{rect:a}})}return n}updateDrag(e,t){const n=this.unifiedDragStates.get(e);if(!(null==n?void 0:n.isDragging))return{x:0,y:0};const o=this.clampDelta(t,n.combinedConstraints),i={...n,delta:o};this.unifiedDragStates.set(e,i);const r=this.computeDragPreviewPatches(i,e);return this.unifiedDrag$.emit({documentId:e,type:"update",state:i,previewPatches:r}),o}commitDrag(e){const t=this.unifiedDragStates.get(e);if(!t)return;const n=t.delta;if(0!==n.x||0!==n.y){const o=[];for(const i of t.allParticipantIds){const r=this.getAnnotationById(i,e);if(!r)continue;const a=t.originalRects.get(i)??r.object.rect,s={...a,origin:{x:a.origin.x+n.x,y:a.origin.y+n.y}},l=this.transformAnnotation(r.object,{type:"move",changes:{rect:s}});o.push({pageIndex:r.object.pageIndex,id:i,patch:l})}o.length>0&&this.moveAnnotationsMethod(o,e)}const o=this.computeDragPreviewPatches(t,e);this.unifiedDrag$.emit({documentId:e,type:"end",state:{...t,isDragging:!1},previewPatches:o}),this.unifiedDragStates.delete(e)}cancelDrag(e){const t=this.unifiedDragStates.get(e);t&&(this.unifiedDrag$.emit({documentId:e,type:"cancel",state:{...t,isDragging:!1,delta:{x:0,y:0}},previewPatches:{}}),this.unifiedDragStates.delete(e))}getDragState(e){return this.unifiedDragStates.get(e)??null}get onDragChange(){return this.unifiedDrag$.on}computeUnifiedGroupBoundingBox(e){if(0===e.length)return{origin:{x:0,y:0},size:{width:0,height:0}};let t=1/0,n=1/0,o=-1/0,i=-1/0;for(const r of e)t=Math.min(t,r.origin.x),n=Math.min(n,r.origin.y),o=Math.max(o,r.origin.x+r.size.width),i=Math.max(i,r.origin.y+r.size.height);return{origin:{x:t,y:n},size:{width:o-t,height:i-n}}}computeUnifiedRelativePositions(e,t){return e.map(e=>({id:e.id,originalRect:e.rect,originalUnrotatedRect:e.unrotatedRect,pageIndex:e.pageIndex,isAttachedLink:e.isAttachedLink,parentId:e.parentId,relativeX:t.size.width>0?(e.rect.origin.x-t.origin.x)/t.size.width:0,relativeY:t.size.height>0?(e.rect.origin.y-t.origin.y)/t.size.height:0,relativeWidth:t.size.width>0?e.rect.size.width/t.size.width:1,relativeHeight:t.size.height>0?e.rect.size.height/t.size.height:1}))}computeUnifiedResizedRects(e,t,n=10){const o=new Map;for(const i of e){const e=Math.max(n,i.relativeWidth*t.size.width),r=Math.max(n,i.relativeHeight*t.size.height);o.set(i.id,{origin:{x:t.origin.x+i.relativeX*t.size.width,y:t.origin.y+i.relativeY*t.size.height},size:{width:e,height:r}})}return o}computeResizePreviewPatches(e,t){const n={},o=this.unifiedResizeStates.get(t),i=o?new Map(o.participatingAnnotations.map(e=>[e.id,e])):void 0;for(const[r,a]of e){const e=this.getAnnotationById(r,t);if(!e)continue;let s=a;const l=null==i?void 0:i.get(r);(null==o?void 0:o.isGroupResize)&&(null==l?void 0:l.originalUnrotatedRect)&&(s=ru(a,l.originalRect,l.originalUnrotatedRect,e.object.rotation??0)),n[r]=this.transformAnnotation(e.object,{type:"resize",changes:{rect:s}})}return n}startResize(e,t){const{annotationIds:n,pageSize:o,resizeHandle:i}=t,r=[],a=[];for(const t of n){const n=this.getAnnotationById(t,e);if(n){a.push({id:t,rect:n.object.rect,unrotatedRect:n.object.unrotatedRect?this.cloneRect(n.object.unrotatedRect):void 0,pageIndex:n.object.pageIndex,isAttachedLink:!1});const o=this.getAttachedLinksMethod(t,e);for(const e of o)r.includes(e.object.id)||(r.push(e.object.id),a.push({id:e.object.id,rect:e.object.rect,unrotatedRect:e.object.unrotatedRect?this.cloneRect(e.object.unrotatedRect):void 0,pageIndex:e.object.pageIndex,isAttachedLink:!0,parentId:t}))}}const s=[...n,...r],l=a.map(e=>e.rect),c=this.computeUnifiedGroupBoundingBox(l),d=this.computeUnifiedRelativePositions(a,c),u=this.computeUnifiedResizedRects(d,c),h={documentId:e,isResizing:!0,isGroupResize:n.length>1,primaryIds:n,attachedLinkIds:r,allParticipantIds:s,originalGroupBox:c,currentGroupBox:c,participatingAnnotations:d,resizeHandle:i,computedRects:u};this.unifiedResizeStates.set(e,h);const m=this.computeResizePreviewPatches(u,e);this.unifiedResize$.emit({documentId:e,type:"start",state:h,computedRects:Object.fromEntries(u),previewPatches:m})}updateResize(e,t){const n=this.unifiedResizeStates.get(e);if(!(null==n?void 0:n.isResizing))return{};const o=this.computeUnifiedResizedRects(n.participatingAnnotations,t),i={...n,currentGroupBox:t,computedRects:o};this.unifiedResizeStates.set(e,i);const r=Object.fromEntries(o),a=this.computeResizePreviewPatches(o,e);return this.unifiedResize$.emit({documentId:e,type:"update",state:i,computedRects:r,previewPatches:a}),r}commitResize(e){const t=this.unifiedResizeStates.get(e);if(!t)return;const n=this.computeUnifiedResizedRects(t.participatingAnnotations,t.currentGroupBox),o=[],i=new Map(t.participatingAnnotations.map(e=>[e.id,e]));for(const[r,a]of n){const n=this.getAnnotationById(r,e);if(!n)continue;let s=a;const l=i.get(r);t.isGroupResize&&(null==l?void 0:l.originalUnrotatedRect)&&(s=ru(a,l.originalRect,l.originalUnrotatedRect,n.object.rotation??0));const c=this.transformAnnotation(n.object,{type:"resize",changes:{rect:s}});o.push({pageIndex:n.object.pageIndex,id:r,patch:c})}o.length>0&&this.updateAnnotationsMethod(o,e);const r=this.computeResizePreviewPatches(n,e);this.unifiedResize$.emit({documentId:e,type:"end",state:{...t,isResizing:!1},computedRects:Object.fromEntries(n),previewPatches:r}),this.unifiedResizeStates.delete(e)}cancelResize(e){const t=this.unifiedResizeStates.get(e);if(!t)return;const n=this.computeUnifiedResizedRects(t.participatingAnnotations,t.originalGroupBox);this.unifiedResize$.emit({documentId:e,type:"cancel",state:{...t,isResizing:!1,currentGroupBox:t.originalGroupBox},computedRects:Object.fromEntries(n),previewPatches:{}}),this.unifiedResizeStates.delete(e)}getResizeState(e){return this.unifiedResizeStates.get(e)??null}get onResizeChange(){return this.unifiedResize$.on}cloneRect(e){return{origin:{x:e.origin.x,y:e.origin.y},size:{width:e.size.width,height:e.size.height}}}translateRect(e,t){return{origin:{x:e.origin.x+t.x,y:e.origin.y+t.y},size:{...e.size}}}normalizeAngle(e){const t=e%360;return t<0?t+360:t}normalizeDelta(e){return(e+540)%360-180}buildRotationParticipants(e,t){const n=[],o=[];for(const i of e){const e=this.getAnnotationById(i,t);if(!e)continue;n.push({id:i,rect:this.cloneRect(e.object.rect),pageIndex:e.object.pageIndex,rotation:e.object.rotation??0,unrotatedRect:e.object.unrotatedRect?this.cloneRect(e.object.unrotatedRect):void 0,isAttachedLink:!1});const r=this.getAttachedLinksMethod(i,t);for(const e of r)o.includes(e.object.id)||(o.push(e.object.id),n.push({id:e.object.id,rect:this.cloneRect(e.object.rect),pageIndex:e.object.pageIndex,rotation:e.object.rotation??0,unrotatedRect:e.object.unrotatedRect?this.cloneRect(e.object.unrotatedRect):void 0,isAttachedLink:!0,parentId:i}))}return{participants:n,attachedLinkIds:o}}computeRotatePreviewPatches(e,t){const n={};for(const o of e.participants){const i=this.getAnnotationById(o.id,t);if(!i)continue;const r=Sd({rect:o.rect,unrotatedRect:o.unrotatedRect,rotation:o.rotation}),a=lt(r,e.rotationCenter,e.delta),s={x:a.x-r.x,y:a.y-r.y},l=this.normalizeAngle(o.rotation+e.delta),c=this.transformAnnotation(i.object,{type:"rotate",changes:{rotation:l,unrotatedRect:this.translateRect(o.unrotatedRect??o.rect,s)},metadata:{rotationAngle:l,rotationDelta:e.delta,rotationCenter:e.rotationCenter}});c.rect||0===s.x&&0===s.y||(c.rect={origin:{x:i.object.rect.origin.x+s.x,y:i.object.rect.origin.y+s.y},size:{...i.object.rect.size}}),n[o.id]=c}return n}startRotation(e,t){const{annotationIds:n,cursorAngle:o,rotationCenter:i}=t,{participants:r,attachedLinkIds:a}=this.buildRotationParticipants(n,e);if(0===r.length)return;const s=r.map(e=>e.rect),l=this.computeUnifiedGroupBoundingBox(s),c=i??{x:l.origin.x+l.size.width/2,y:l.origin.y+l.size.height/2},d={documentId:e,isRotating:!0,primaryIds:n,attachedLinkIds:a,allParticipantIds:r.map(e=>e.id),rotationCenter:c,cursorStartAngle:o,currentAngle:o,delta:0,participants:r};this.unifiedRotateStates.set(e,d);const u=this.computeRotatePreviewPatches(d,e);this.unifiedRotate$.emit({documentId:e,type:"start",state:d,previewPatches:u})}updateRotation(e,t,n){const o=this.unifiedRotateStates.get(e);if(!(null==o?void 0:o.isRotating))return;const i=void 0!==n?n:this.normalizeDelta(t-o.cursorStartAngle),r={...o,currentAngle:t,delta:i};this.unifiedRotateStates.set(e,r);const a=this.computeRotatePreviewPatches(r,e);this.unifiedRotate$.emit({documentId:e,type:"update",state:r,previewPatches:a})}commitRotation(e){const t=this.unifiedRotateStates.get(e);if(!t)return;const n=this.computeRotatePreviewPatches(t,e),o=[];for(const[t,i]of Object.entries(n)){const n=this.getAnnotationById(t,e);n&&o.push({pageIndex:n.object.pageIndex,id:t,patch:i})}o.length>0&&this.updateAnnotationsMethod(o,e),this.unifiedRotate$.emit({documentId:e,type:"end",state:{...t,isRotating:!1},previewPatches:n}),this.unifiedRotateStates.delete(e)}cancelRotation(e){const t=this.unifiedRotateStates.get(e);t&&(this.unifiedRotate$.emit({documentId:e,type:"cancel",state:{...t,isRotating:!1,delta:0,currentAngle:t.cursorStartAngle},previewPatches:{}}),this.unifiedRotateStates.delete(e))}getRotateState(e){return this.unifiedRotateStates.get(e)??null}get onRotateChange(){return this.unifiedRotate$.on}updateAnnotationsMethod(e,t){const n=t??this.getActiveDocumentId();if(!this.checkPermission(n,Qt.ModifyAnnotations))return void this.logger.debug("AnnotationPlugin","UpdateAnnotations",`Cannot update annotations: document ${n} lacks ModifyAnnotations permission`);const o=this.getDocumentState(n),i=e.map(({pageIndex:e,id:t,patch:n})=>{var i;const r=null==(i=o.byUid[t])?void 0:i.object;if(!r)return null;return{pageIndex:e,id:t,patch:this.buildPatch(r,{...n,author:n.author??this.config.annotationAuthor}),originalObject:r}}).filter(e=>null!==e);if(0===i.length)return;const r=()=>{for(const{pageIndex:e,id:t,patch:o,originalObject:r}of i)this.dispatch(Yc(n,e,t,o)),this.events$.emit({type:"update",documentId:n,annotation:r,pageIndex:e,patch:o,committed:!1})};if(!this.history)return r(),void(!1!==this.config.autoCommit&&this.commit(n));const a=i.map(({pageIndex:e,id:t,patch:n,originalObject:o})=>({pageIndex:e,id:t,originalPatch:Object.fromEntries(Object.keys(n).map(e=>[e,o[e]])),originalObject:o})),s={execute:r,undo:()=>{for(const{pageIndex:e,id:t,originalPatch:o,originalObject:i}of a)this.dispatch(Yc(n,e,t,o)),this.events$.emit({type:"update",documentId:n,annotation:i,pageIndex:e,patch:o,committed:!1})},metadata:{annotationIds:i.map(e=>e.id)}};this.history.forDocument(n).register(s,this.ANNOTATION_HISTORY_TOPIC)}moveAnnotationsMethod(e,t){const n=t??this.getActiveDocumentId();if(!this.checkPermission(n,Qt.ModifyAnnotations))return void this.logger.debug("AnnotationPlugin","MoveAnnotations",`Cannot move annotations: document ${n} lacks ModifyAnnotations permission`);const o=this.getDocumentState(n),i=e.map(({pageIndex:e,id:t,patch:n})=>{var i;const r=null==(i=o.byUid[t])?void 0:i.object;return r?{pageIndex:e,id:t,patch:n,originalObject:r}:null}).filter(e=>null!==e);if(0===i.length)return;const r=()=>{for(const{pageIndex:e,id:t,patch:o,originalObject:r}of i)this.dispatch(Xc(n,e,t,o)),this.events$.emit({type:"update",documentId:n,annotation:r,pageIndex:e,patch:o,committed:!1})};if(!this.history)return r(),void(!1!==this.config.autoCommit&&this.commit(n));const a=i.map(({pageIndex:e,id:t,patch:n,originalObject:o})=>({pageIndex:e,id:t,originalPatch:Object.fromEntries(Object.keys(n).map(e=>[e,o[e]])),originalObject:o})),s={execute:r,undo:()=>{for(const{pageIndex:e,id:t,originalPatch:o,originalObject:i}of a)this.dispatch(Xc(n,e,t,o)),this.events$.emit({type:"update",documentId:n,annotation:i,pageIndex:e,patch:o,committed:!1})},metadata:{annotationIds:i.map(e=>e.id)}};this.history.forDocument(n).register(s,this.ANNOTATION_HISTORY_TOPIC)}moveAnnotationMethod(e,t,n,o="delta",i){const r=i??this.getActiveDocumentId(),a=this.getAnnotationById(t,r);if(!a)return;const s=a.object.rect,l={...s,origin:"absolute"===o?{x:n.x,y:n.y}:{x:s.origin.x+n.x,y:s.origin.y+n.y}},c=this.transformAnnotation(a.object,{type:"move",changes:{rect:l}});this.moveAnnotationsMethod([{pageIndex:e,id:t,patch:c}],r)}getActiveTool(e){const t=this.getDocumentState(e);return t.activeToolId?this.state.tools.find(e=>e.id===t.activeToolId)??null:null}setActiveTool(e,t){var n,o;const i=t??this.getActiveDocumentId();if(null!==e&&!this.checkPermission(i,Qt.ModifyAnnotations))return void this.logger.debug("AnnotationPlugin","SetActiveTool",`Cannot activate tool: document ${i} lacks ModifyAnnotations permission`);const r=this.getDocumentState(i);if(e===r.activeToolId)return;this.dispatch(Kc(i,e));const a=this.state.tools.find(t=>t.id===e);a?null==(n=this.interactionManager)||n.forDocument(i).activate(a.interaction.mode??a.id):null==(o=this.interactionManager)||o.forDocument(i).activateDefaultMode()}getTool(e){return this.state.tools.find(t=>t.id===e)}findToolForAnnotation(e){let t=null,n=0;for(const o of this.state.tools){const i=o.matchScore(e);i>n&&(n=i,t=o)}return t}collectPendingChanges(e,t){const n=this.getDocumentState(e),o=this.pendingContexts.get(e),i={creations:[],updates:[],deletions:[],committedUids:[],isEmpty:!0};for(const[e,r]of Object.entries(n.byUid)){if("synced"===r.commitState)continue;const n=t.pages.find(e=>e.index===r.object.pageIndex);if(n)switch(i.committedUids.push(e),i.isEmpty=!1,r.commitState){case"new":i.creations.push({uid:e,ta:r,ctx:null==o?void 0:o.get(r.object.id)});break;case"moved":i.updates.push({uid:e,ta:r,moved:!0});break;case"dirty":i.updates.push({uid:e,ta:r});break;case"deleted":i.deletions.push({uid:e,ta:r})}}return i}executeCommitBatch(e,t,n){const o=new Ct,i=this.pendingContexts.get(e),r=[];for(const{uid:e,ta:o,ctx:i}of n.creations){const n=t.pages.find(e=>e.index===o.object.pageIndex);if(!n)continue;const a=this.engine.createPageAnnotation(t,n,o.object,i);r.push({type:"create",task:a,ta:o,uid:e,ctx:i})}for(const{uid:e,ta:o,moved:i}of n.updates){const n=t.pages.find(e=>e.index===o.object.pageIndex);if(!n)continue;const a=i?this.engine.updatePageAnnotation(t,n,o.object,{regenerateAppearance:!1}):this.engine.updatePageAnnotation(t,n,o.object);r.push({type:"update",task:a,ta:o,uid:e,moved:i})}for(const{uid:o,ta:i}of n.deletions){const n=t.pages.find(e=>e.index===i.object.pageIndex);if(n)if(i.object.id){const e=new Ct;this.engine.removePageAnnotation(t,n,i.object).wait(()=>e.resolve(!0),e.fail),r.push({type:"delete",task:e,ta:i,uid:o})}else this.dispatch(Jc(e,i.object.pageIndex,o))}const a=r.map(e=>e.task);return Ct.allSettled(a).wait(()=>{this.emitCommitEvents(e,r,i);for(const t of r)"update"===t.type&&t.moved||"create"!==t.type&&"update"!==t.type&&"delete"!==t.type||this.invalidateAnnotationAppearance(t.ta.object.id,t.ta.object.pageIndex,e);var t,a;this.dispatch((t=e,a=n.committedUids,{type:jc,payload:{documentId:t,committedUids:a}})),o.resolve(!0)},e=>o.fail(e)),o}emitCommitEvents(e,t,n){for(const o of t)if(o.task.state.stage===bt.Resolved)switch(o.type){case"create":this.events$.emit({type:"create",documentId:e,annotation:o.ta.object,pageIndex:o.ta.object.pageIndex,ctx:o.ctx,committed:!0}),null==n||n.delete(o.ta.object.id);break;case"update":this.events$.emit({type:"update",documentId:e,annotation:o.ta.object,pageIndex:o.ta.object.pageIndex,patch:o.ta.object,committed:!0});break;case"delete":this.dispatch(Jc(e,o.ta.object.pageIndex,o.uid)),this.events$.emit({type:"delete",documentId:e,annotation:o.ta.object,pageIndex:o.ta.object.pageIndex,committed:!0})}}acquireCommitLock(e){return!this.commitInProgress.get(e)&&(this.commitInProgress.set(e,!0),!0)}releaseCommitLock(e){this.commitInProgress.set(e,!1)}commit(e){const t=e??this.getActiveDocumentId();if(!this.getDocumentState(t).hasPendingChanges)return nn.resolve(!0);if(!this.acquireCommitLock(t))return nn.resolve(!0);const n=this.getCoreDocument(t),o=null==n?void 0:n.document;if(!o)return this.releaseCommitLock(t),nn.reject({code:tn.NotFound,message:"Document not found"});const i=this.collectPendingChanges(t,o);if(i.isEmpty)return this.releaseCommitLock(t),nn.resolve(!0);const r=new Ct;return this.executeCommitBatch(t,o,i).wait(()=>{this.releaseCommitLock(t);this.getDocumentState(t).hasPendingChanges?this.commit(t).wait(e=>r.resolve(e),e=>r.fail(e)):r.resolve(!0)},e=>{this.releaseCommitLock(t),r.fail(e)}),r}};au.id="annotation";let su=au;function lu(e,t,n){return void 0===e?n:"function"==typeof e?e(t):e}function cu(e){return t=>(null==t?void 0:t.id)===e}const du=cu("highlight"),uu=cu("squiggly"),hu=cu("underline"),mu=cu("strikeout"),gu={manifest:Sc,create:(e,t)=>new su(Ic,e,t),reducer:(e,t)=>{switch(t.type){case Ac:{const{documentId:n,state:o}=t.payload;return{...e,documents:{...e.documents,[n]:o},activeDocumentId:e.activeDocumentId??n}}case Mc:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i,activeDocumentId:e.activeDocumentId===n?null:e.activeDocumentId}}case"ANNOTATION/SET_ACTIVE_DOCUMENT":return{...e,activeDocumentId:t.payload};case Pc:{const{documentId:n,annotations:o}=t.payload,i=e.documents[n];if(!i)return e;const r={},a={};for(const[e,t]of Object.entries(o)){const n=Number(e),o=i.pages[n]||[];for(const e of o)delete a[e];const s=t.map(e=>{const t=e.id;return a[t]={commitState:"synced",object:e},t});r[n]=s}return{...e,documents:{...e.documents,[n]:{...i,pages:r,byUid:a}}}}case Dc:{const{documentId:n,id:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,selectedUids:[o],selectedUid:o}}}:e}case Rc:{const{documentId:n}=t.payload,o=e.documents[n];return o?{...e,documents:{...e.documents,[n]:{...o,selectedUids:[],selectedUid:null}}}:e}case zc:{const{documentId:n,id:o}=t.payload,i=e.documents[n];if(!i)return e;if(i.selectedUids.includes(o))return e;const r=[...i.selectedUids,o];return{...e,documents:{...e.documents,[n]:{...i,selectedUids:r,selectedUid:md(r)}}}}case Tc:{const{documentId:n,id:o}=t.payload,i=e.documents[n];if(!i)return e;const r=i.selectedUids.filter(e=>e!==o);return{...e,documents:{...e.documents,[n]:{...i,selectedUids:r,selectedUid:md(r)}}}}case Ec:{const{documentId:n,ids:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,selectedUids:o,selectedUid:md(o)}}}:e}case _c:{const{documentId:n,toolId:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,activeToolId:o}}}:e}case Nc:{const{documentId:n,pageIndex:o,annotation:i}=t.payload,r=e.documents[n];if(!r)return e;const a=i.id;return{...e,documents:{...e.documents,[n]:{...r,pages:{...r.pages,[o]:[...r.pages[o]??[],a]},byUid:{...r.byUid,[a]:{commitState:"new",object:i,dictMode:!0}},hasPendingChanges:!0}}}}case $c:{const{documentId:n,pageIndex:o,id:i}=t.payload,r=e.documents[n];return r&&r.byUid[i]?{...e,documents:{...e.documents,[n]:{...r,pages:{...r.pages,[o]:(r.pages[o]??[]).filter(e=>e!==i)},byUid:{...r.byUid,[i]:{...r.byUid[i],commitState:"deleted"}},hasPendingChanges:!0}}}:e}case Lc:{const{documentId:n,id:o,patch:i}=t.payload,r=e.documents[n];return r?{...e,documents:{...e.documents,[n]:gd(r,o,i)}}:e}case Oc:{const{documentId:n,id:o,patch:i}=t.payload,r=e.documents[n];return r?{...e,documents:{...e.documents,[n]:pd(r,o,i)}}:e}case jc:{const{documentId:n,committedUids:o}=t.payload,i=e.documents[n];if(!i)return e;const r=new Set(o),a={};let s=!1;for(const[e,t]of Object.entries(i.byUid))r.has(e)?a[e]={...t,commitState:"dirty"===t.commitState||"new"===t.commitState||"moved"===t.commitState?"synced":t.commitState}:(a[e]=t,"new"!==t.commitState&&"dirty"!==t.commitState&&"moved"!==t.commitState&&"deleted"!==t.commitState||(s=!0));return{...e,documents:{...e.documents,[n]:{...i,byUid:a,hasPendingChanges:s}}}}case Fc:{const{documentId:n,pageIndex:o,uid:i}=t.payload,r=e.documents[n];if(!r||!r.byUid[i])return e;const{[i]:a,...s}=r.byUid;return{...e,documents:{...e.documents,[n]:{...r,pages:{...r.pages,[o]:(r.pages[o]??[]).filter(e=>e!==i)},byUid:s}}}}case Wc:{const n=new Map(e.tools.map(e=>[e.id,e]));return n.set(t.payload.id,t.payload),{...e,tools:Array.from(n.values())}}case Hc:{const{toolId:n,patch:o}=t.payload;return{...e,tools:e.tools.map(e=>e.id===n?{...e,defaults:{...e.defaults,...o}}:e)}}case Uc:return e.colorPresets.includes(t.payload)?e:{...e,colorPresets:[...e.colorPresets,t.payload]};default:return e}},initialState:(e,t)=>(e=>{const t=new Map;ud.forEach(e=>t.set(e.id,e));const n=new Map(t);(e.tools||[]).forEach(e=>{const o=t.get(e.id);o?n.set(e.id,{...o,...e,defaults:{...o.defaults,...e.defaults},interaction:{...o.interaction,...e.interaction},behavior:{...o.behavior,...e.behavior},...o.clickBehavior||e.clickBehavior?{clickBehavior:{...o.clickBehavior,...e.clickBehavior}}:{}}):n.set(e.id,e)});const o=Array.from(n.values()).map(t=>{var n,o;return{...t,behavior:{...t.behavior,deactivateToolAfterCreate:(null==(n=t.behavior)?void 0:n.deactivateToolAfterCreate)??e.deactivateToolAfterCreate??!1,selectAfterCreate:(null==(o=t.behavior)?void 0:o.selectAfterCreate)??e.selectAfterCreate??!0}}});return{documents:{},activeDocumentId:null,tools:o,colorPresets:e.colorPresets??hd}})(t)};function pu(e,t){for(var n in e)if("__source"!==n&&!(n in t))return!0;for(var o in t)if("__source"!==o&&e[o]!==t[o])return!0;return!1}function fu(e,t){this.props=e,this.context=t}(fu.prototype=new W).isPureReactComponent=!0,fu.prototype.shouldComponentUpdate=function(e,t){return pu(this.props,e)||pu(this.state,t)};var vu=k.__b;k.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),vu&&vu(e)};var yu=k.__e;k.__e=function(e,t,n,o){if(e.then)for(var i,r=t;r=r.__;)if((i=r.__c)&&i.__c)return null==t.__e&&(t.__e=n.__e,t.__k=n.__k),i.__c(e,t);yu(e,t,n,o)};var bu=k.unmount;function wu(e,t,n){return e&&(e.__c&&e.__c.__H&&(e.__c.__H.__.forEach(function(e){"function"==typeof e.__c&&e.__c()}),e.__c.__H=null),null!=(e=function(e,t){for(var n in t)e[n]=t[n];return e}({},e)).__c&&(e.__c.__P===n&&(e.__c.__P=t),e.__c.__e=!0,e.__c=null),e.__k=e.__k&&e.__k.map(function(e){return wu(e,t,n)})),e}function xu(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(e){return xu(e,t,n)}),e.__c&&e.__c.__P===t&&(e.__e&&n.appendChild(e.__e),e.__c.__e=!0,e.__c.__P=n)),e}function Cu(){this.__u=0,this.o=null,this.__b=null}function ku(e){if(!e.__)return null;var t=e.__.__c;return t&&t.__a&&t.__a(e)}function Iu(){this.i=null,this.l=null}k.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),bu&&bu(e)},(Cu.prototype=new W).__c=function(e,t){var n=t.__c,o=this;null==o.o&&(o.o=[]),o.o.push(n);var i=ku(o.__v),r=!1,a=function(){r||o.__z||(r=!0,n.__R=null,i?i(l):l())};n.__R=a;var s=n.__P;n.__P=null;var l=function(){if(! --o.__u){if(o.state.__a){var e=o.state.__a;o.__v.__k[0]=xu(e,e.__c.__P,e.__c.__O)}var t;for(o.setState({__a:o.__b=null});t=o.o.pop();)t.__P=s,t.forceUpdate()}};o.__u++||32&t.__u||o.setState({__a:o.__b=o.__v.__k[0]}),e.then(a,a)},Cu.prototype.componentWillUnmount=function(){this.o=[]},Cu.prototype.render=function(e,t){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),o=this.__v.__k[0].__c;this.__v.__k[0]=wu(this.__b,n,o.__O=o.__P)}this.__b=null}var i=t.__a&&F(H,null,e.fallback);return i&&(i.__u&=-33),[F(H,null,t.__a?null:e.children),i]};var Su=function(e,t,n){if(++n[1]===n[0]&&e.l.delete(t),e.props.revealOrder&&("t"!==e.props.revealOrder[0]||!e.l.size))for(n=e.i;n;){for(;n.length>3;)n.pop()();if(n[1]>>1,1),t.h.removeChild(e)}}}ce(F(Au,{context:t.context},e.__v),t.v)}function Pu(e,t){var n=F(Mu,{__v:e,h:t});return n.containerInfo=t,n}(Iu.prototype=new W).__a=function(e){var t=this,n=ku(t.__v),o=t.l.get(e);return o[0]++,function(i){var r=function(){t.props.revealOrder?(o.push(i),Su(t,e,o)):i()};n?n(r):r()}},Iu.prototype.render=function(e){this.i=null,this.l=new Map;var t=Y(e.children);e.revealOrder&&"b"===e.revealOrder[0]&&t.reverse();for(var n=t.length;n--;)this.l.set(t[n],this.i=[1,0,this.i]);return e.children},Iu.prototype.componentDidUpdate=Iu.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){Su(e,n,t)})};var Du="undefined"!=typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103,Ru=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,zu=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Tu=/[A-Z0-9]/g,Eu="undefined"!=typeof document,_u=function(e){return("undefined"!=typeof Symbol&&"symbol"==typeof Symbol()?/fil|che|rad/:/fil|che|ra/).test(e)};W.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(W.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var Nu=k.event;function Lu(){}function Ou(){return this.cancelBubble}function $u(){return this.defaultPrevented}k.event=function(e){return Nu&&(e=Nu(e)),e.persist=Lu,e.isPropagationStopped=Ou,e.isDefaultPrevented=$u,e.nativeEvent=e};var ju={enumerable:!1,configurable:!0,get:function(){return this.class}},Fu=k.vnode;k.vnode=function(e){"string"==typeof e.type&&function(e){var t=e.props,n=e.type,o={},i=-1===n.indexOf("-");for(var r in t){var a=t[r];if(!("value"===r&&"defaultValue"in t&&null==a||Eu&&"children"===r&&"noscript"===n||"class"===r||"className"===r)){var s=r.toLowerCase();"defaultValue"===r&&"value"in t&&null==t.value?r="value":"download"===r&&!0===a?a="":"translate"===s&&"no"===a?a=!1:"o"===s[0]&&"n"===s[1]?"ondoubleclick"===s?r="ondblclick":"onchange"!==s||"input"!==n&&"textarea"!==n||_u(t.type)?"onfocus"===s?r="onfocusin":"onblur"===s?r="onfocusout":zu.test(r)&&(r=s):s=r="oninput":i&&Ru.test(r)?r=r.replace(Tu,"-$&").toLowerCase():null===a&&(a=void 0),"oninput"===s&&o[r=s]&&(r="oninputCapture"),o[r]=a}}"select"==n&&o.multiple&&Array.isArray(o.value)&&(o.value=Y(t.children).forEach(function(e){e.props.selected=-1!=o.value.indexOf(e.props.value)})),"select"==n&&null!=o.defaultValue&&(o.value=Y(t.children).forEach(function(e){e.props.selected=o.multiple?-1!=o.defaultValue.indexOf(e.props.value):o.defaultValue==e.props.value})),t.class&&!t.className?(o.class=t.class,Object.defineProperty(o,"className",ju)):(t.className&&!t.class||t.class&&t.className)&&(o.class=o.className=t.className),e.props=o}(e),e.$$typeof=Du,Fu&&Fu(e)};var Uu=k.__r;k.__r=function(e){Uu&&Uu(e),e.__c};var Hu=k.diffed;k.diffed=function(e){Hu&&Hu(e);var t=e.props,n=e.__e;null!=n&&"textarea"===e.type&&"value"in t&&t.value!==n.value&&(n.value=null==t.value?"":t.value)};const Wu="INTERACTION/INIT_STATE",Bu="INTERACTION/CLEANUP_STATE",qu="INTERACTION/ACTIVATE_MODE",Gu="INTERACTION/PAUSE",Vu="INTERACTION/RESUME",Ku="INTERACTION/SET_CURSOR",Zu="INTERACTION/SET_DEFAULT_MODE",Yu="INTERACTION/SET_EXCLUSION_RULES",Xu="INTERACTION/ADD_EXCLUSION_CLASS",Qu="INTERACTION/REMOVE_EXCLUSION_CLASS",Ju="INTERACTION/ADD_EXCLUSION_ATTRIBUTE",eh="INTERACTION/REMOVE_EXCLUSION_ATTRIBUTE";function th(e){return{type:Zu,payload:{mode:e}}}function nh(e){return{type:Yu,payload:{rules:e}}}const oh="pointerMode",ih=class extends bo{constructor(e,t,n){super(e,t),this.modes=new Map,this.cursorClaims=new Map,this.buckets=new Map,this.alwaysGlobal=new Map,this.alwaysPage=new Map,this.pageActivities=new Map,this.onModeChange$=Po(),this.onHandlerChange$=Po(),this.onCursorChange$=Po(),this.onStateChange$=Do(),this.onPageActivityChange$=Po(),this.registerMode({id:oh,scope:"page",exclusive:!1,cursor:"auto"}),this.dispatch(th(oh)),n.exclusionRules&&this.dispatch(nh(n.exclusionRules))}onDocumentLoadingStarted(e){const t={activeMode:this.state.defaultMode,cursor:"auto",paused:!1};this.dispatch(function(e,t){return{type:Wu,payload:{documentId:e,state:t}}}(e,t)),this.cursorClaims.set(e,new Map),this.buckets.set(e,new Map),this.alwaysGlobal.set(e,new Set),this.alwaysPage.set(e,new Map),this.pageActivities.set(e,new Map);const n=this.buckets.get(e);for(const e of this.modes.keys())n.set(e,{global:new Set,page:new Map});this.logger.debug("InteractionManagerPlugin","DocumentOpened",`Initialized interaction state for document: ${e}`)}onDocumentClosed(e){const t=this.pageActivities.get(e);if(t){const n=new Set(t.values());t.clear();for(const t of n)this.onPageActivityChange$.emit({documentId:e,pageIndex:t,hasActivity:!1})}this.cursorClaims.delete(e),this.buckets.delete(e),this.alwaysGlobal.delete(e),this.alwaysPage.delete(e),this.pageActivities.delete(e),this.dispatch(function(e){return{type:Bu,payload:e}}(e)),this.logger.debug("InteractionManagerPlugin","DocumentClosed",`Cleaned up interaction state for document: ${e}`)}buildCapability(){return{getActiveMode:()=>this.getActiveMode(),getActiveInteractionMode:()=>this.getActiveInteractionMode(),activate:e=>this.activate(e),activateDefaultMode:()=>this.activateDefaultMode(),setCursor:(e,t,n)=>this.setCursor(e,t,n),getCurrentCursor:()=>this.getCurrentCursor(),removeCursor:e=>this.removeCursor(e),getHandlersForScope:e=>this.getHandlersForScope(e),activeModeIsExclusive:()=>this.activeModeIsExclusive(),pause:()=>this.pause(),resume:()=>this.resume(),isPaused:()=>this.registry.isDestroyed()||this.isPaused(),getState:()=>this.getDocumentStateOrThrow(),forDocument:e=>this.createInteractionScope(e),registerMode:e=>this.registerMode(e),registerHandlers:e=>this.registerHandlers(e),registerAlways:e=>this.registerAlways(e),setDefaultMode:e=>this.setDefaultMode(e),getDefaultMode:()=>this.state.defaultMode,getExclusionRules:()=>this.state.exclusionRules,setExclusionRules:e=>this.dispatch(nh(e)),addExclusionClass:e=>this.dispatch(function(e){return{type:Xu,payload:{className:e}}}(e)),removeExclusionClass:e=>this.dispatch(function(e){return{type:Qu,payload:{className:e}}}(e)),addExclusionAttribute:e=>this.dispatch(function(e){return{type:Ju,payload:{attribute:e}}}(e)),removeExclusionAttribute:e=>this.dispatch(function(e){return{type:eh,payload:{attribute:e}}}(e)),claimPageActivity:(e,t,n)=>this.claimPageActivity(e,t,n),releasePageActivity:(e,t)=>this.releasePageActivity(e,t),hasPageActivity:(e,t)=>this.hasPageActivity(e,t),onModeChange:this.onModeChange$.on,onCursorChange:this.onCursorChange$.on,onHandlerChange:this.onHandlerChange$.on,onStateChange:this.onStateChange$.on,onPageActivityChange:this.onPageActivityChange$.on}}createInteractionScope(e){return{getActiveMode:()=>this.getActiveMode(e),getActiveInteractionMode:()=>this.getActiveInteractionMode(e),activate:t=>this.activate(t,e),activateDefaultMode:()=>this.activateDefaultMode(e),setCursor:(t,n,o)=>this.setCursor(t,n,o,e),getCurrentCursor:()=>this.getCurrentCursor(e),removeCursor:t=>this.removeCursor(t,e),getHandlersForScope:e=>this.getHandlersForScope(e),activeModeIsExclusive:()=>this.activeModeIsExclusive(e),pause:()=>this.pause(e),resume:()=>this.resume(e),isPaused:()=>this.isPaused(e),getState:()=>this.getDocumentStateOrThrow(e),claimPageActivity:(t,n)=>this.claimPageActivity(e,t,n),releasePageActivity:t=>this.releasePageActivity(e,t),hasPageActivity:t=>this.hasPageActivity(e,t),onModeChange:t=>this.onModeChange$.on(n=>{n.documentId===e&&t(n.activeMode)}),onCursorChange:t=>this.onCursorChange$.on(n=>{n.documentId===e&&t(n.cursor)}),onStateChange:t=>this.onStateChange$.on(n=>{n.documentId===e&&t(n.state)}),onPageActivityChange:t=>this.onPageActivityChange$.on(n=>{n.documentId===e&&t({pageIndex:n.pageIndex,hasActivity:n.hasActivity})})}}getDocumentState(e){const t=e??this.getActiveDocumentId();return this.state.documents[t]??null}getDocumentStateOrThrow(e){const t=this.getDocumentState(e);if(!t)throw new Error(`Interaction state not found for document: ${e??"active"}`);return t}activate(e,t){var n;const o=t??this.getActiveDocumentId(),i=this.getDocumentStateOrThrow(o);if(!this.modes.has(e))throw new Error(`[interaction] unknown mode '${e}'`);if(e===i.activeMode)return;const r=i.activeMode;null==(n=this.cursorClaims.get(o))||n.clear(),this.notifyHandlersInactive(o,r),this.dispatch(function(e,t){return{type:qu,payload:{documentId:e,mode:t}}}(o,e)),this.emitCursor(o),this.notifyHandlersActive(o,e),this.onModeChange$.emit({documentId:o,activeMode:e,previousMode:r})}activateDefaultMode(e){const t=e??this.getActiveDocumentIdOrNull();t&&this.activate(this.state.defaultMode,t)}setDefaultMode(e){if(!this.modes.has(e))throw new Error(`[interaction] cannot set unknown mode '${e}' as default`);this.dispatch(th(e))}getActiveMode(e){return this.getDocumentStateOrThrow(e).activeMode}getActiveInteractionMode(e){const t=this.getDocumentState(e);return t?this.modes.get(t.activeMode)??null:null}activeModeIsExclusive(e){const t=this.getActiveInteractionMode(e);return!!(null==t?void 0:t.exclusive)}pause(e){const t=e??this.getActiveDocumentId();this.dispatch(function(e){return{type:Gu,payload:e}}(t))}resume(e){const t=e??this.getActiveDocumentId();this.dispatch(function(e){return{type:Vu,payload:e}}(t))}isPaused(e){return this.getDocumentStateOrThrow(e).paused}registerMode(e){this.modes.set(e.id,e);for(const t of this.buckets.keys()){const n=this.buckets.get(t);n.has(e.id)||n.set(e.id,{global:new Set,page:new Map})}}registerHandlers({documentId:e,modeId:t,handlers:n,pageIndex:o}){const i=Array.isArray(t)?t:[t],r=[],a=this.buckets.get(e);if(!a)throw new Error(`No buckets found for document: ${e}`);for(const e of i){const t=a.get(e);if(!t)throw new Error(`unknown mode '${e}'`);if(null==o)t.global.add(n);else{const e=t.page.get(o)??new Set;e.add(n),t.page.set(o,e)}r.push(()=>{if(null==o)t.global.delete(n);else{const e=t.page.get(o);e&&(e.delete(n),0===e.size&&t.page.delete(o))}})}return this.onHandlerChange$.emit({...this.state}),()=>{r.forEach(e=>e()),this.onHandlerChange$.emit({...this.state})}}registerAlways({scope:e,handlers:t}){if("global"===e.type){const n=this.alwaysGlobal.get(e.documentId)??new Set;return n.add(t),this.alwaysGlobal.set(e.documentId,n),this.onHandlerChange$.emit({...this.state}),()=>{n.delete(t),this.onHandlerChange$.emit({...this.state})}}const n=this.alwaysPage.get(e.documentId)??new Map,o=n.get(e.pageIndex)??new Set;return o.add(t),n.set(e.pageIndex,o),this.alwaysPage.set(e.documentId,n),this.onHandlerChange$.emit({...this.state}),()=>{o.delete(t),this.onHandlerChange$.emit({...this.state})}}getHandlersForScope(e){var t;const n=this.getDocumentState(e.documentId);if(!n)return null;const o=this.modes.get(n.activeMode);if(!o)return null;const i=this.buckets.get(e.documentId);if(!i)return null;const r=i.get(o.id);if(!r)return null;const a=(e,t)=>e.size||t.size?function(e){const t=["onPointerDown","onPointerUp","onPointerMove","onPointerEnter","onPointerLeave","onPointerCancel","onMouseDown","onMouseUp","onMouseMove","onMouseEnter","onMouseLeave","onMouseCancel","onClick","onDoubleClick"],n={};for(const o of t)n[o]=(t,n,i)=>{var r;for(const a of e){if(n.isImmediatePropagationStopped())break;null==(r=a[o])||r.call(a,t,n,i)}};return n}([...e,...t]):null;if("global"===e.type){return a(this.alwaysGlobal.get(e.documentId)??new Set,"global"===o.scope?r.global:new Set)}return a((null==(t=this.alwaysPage.get(e.documentId))?void 0:t.get(e.pageIndex))??new Set,"page"===o.scope?r.page.get(e.pageIndex)??new Set:new Set)}setCursor(e,t,n=0,o){const i=o??this.getActiveDocumentId(),r=this.cursorClaims.get(i);r&&(r.set(e,{cursor:t,priority:n}),this.emitCursor(i))}removeCursor(e,t){const n=t??this.getActiveDocumentId(),o=this.cursorClaims.get(n);o&&(o.delete(e),this.emitCursor(n))}getCurrentCursor(e){return this.getDocumentStateOrThrow(e).cursor}emitCursor(e){var t;const n=this.cursorClaims.get(e);if(!n)return;const o=this.getDocumentState(e);if(!o)return;const i=[...n.values()].sort((e,t)=>t.priority-e.priority)[0]??{cursor:(null==(t=this.modes.get(o.activeMode))?void 0:t.cursor)??"auto"};i.cursor!==o.cursor&&(this.dispatch(function(e,t){return{type:Ku,payload:{documentId:e,cursor:t}}}(e,i.cursor)),this.onCursorChange$.emit({documentId:e,cursor:i.cursor}))}claimPageActivity(e,t,n){let o=this.pageActivities.get(e);o||(o=new Map,this.pageActivities.set(e,o));const i=o.get(t);i!==n&&(o.set(t,n),void 0===i||this.pageHasAnyTopic(e,i)||this.onPageActivityChange$.emit({documentId:e,pageIndex:i,hasActivity:!1}),1===this.countTopicsOnPage(e,n)&&this.onPageActivityChange$.emit({documentId:e,pageIndex:n,hasActivity:!0}))}releasePageActivity(e,t){const n=this.pageActivities.get(e);if(!n)return;const o=n.get(t);void 0!==o&&(n.delete(t),this.pageHasAnyTopic(e,o)||this.onPageActivityChange$.emit({documentId:e,pageIndex:o,hasActivity:!1}))}hasPageActivity(e,t){return this.pageHasAnyTopic(e,t)}pageHasAnyTopic(e,t){const n=this.pageActivities.get(e);if(!n)return!1;for(const e of n.values())if(e===t)return!0;return!1}countTopicsOnPage(e,t){const n=this.pageActivities.get(e);if(!n)return 0;let o=0;for(const e of n.values())e===t&&o++;return o}notifyHandlersActive(e,t){var n,o;null==(n=this.alwaysGlobal.get(e))||n.forEach(e=>{var n;null==(n=e.onHandlerActiveStart)||n.call(e,t)}),null==(o=this.alwaysPage.get(e))||o.forEach(e=>{e.forEach(e=>{var n;null==(n=e.onHandlerActiveStart)||n.call(e,t)})});const i=this.modes.get(t);if(!i)return;const r=this.buckets.get(e);if(!r)return;const a=r.get(t);a&&("global"===i.scope&&a.global.forEach(e=>{var n;null==(n=e.onHandlerActiveStart)||n.call(e,t)}),"page"===i.scope&&a.page.forEach(e=>{e.forEach(e=>{var n;null==(n=e.onHandlerActiveStart)||n.call(e,t)})}))}notifyHandlersInactive(e,t){var n,o;null==(n=this.alwaysGlobal.get(e))||n.forEach(e=>{var n;null==(n=e.onHandlerActiveEnd)||n.call(e,t)}),null==(o=this.alwaysPage.get(e))||o.forEach(e=>{e.forEach(e=>{var n;null==(n=e.onHandlerActiveEnd)||n.call(e,t)})});const i=this.modes.get(t);if(!i)return;const r=this.buckets.get(e);if(!r)return;const a=r.get(t);a&&("global"===i.scope&&a.global.forEach(e=>{var n;null==(n=e.onHandlerActiveEnd)||n.call(e,t)}),"page"===i.scope&&a.page.forEach(e=>{e.forEach(e=>{var n;null==(n=e.onHandlerActiveEnd)||n.call(e,t)})}))}onStoreUpdated(e,t){for(const n in t.documents){const o=e.documents[n],i=t.documents[n];o!==i&&this.onStateChange$.emit({documentId:n,state:i})}}async initialize(e){this.logger.info("InteractionManagerPlugin","Initialize","Interaction Manager Plugin initialized")}async destroy(){this.pageActivities.clear(),this.onModeChange$.clear(),this.onCursorChange$.clear(),this.onHandlerChange$.clear(),this.onStateChange$.clear(),this.onPageActivityChange$.clear(),await super.destroy()}};ih.id="interaction-manager";let rh=ih;const ah="interaction-manager",sh={defaultMode:"pointerMode",exclusionRules:{classes:[],dataAttributes:["data-no-interaction"]},documents:{},activeDocumentId:null},lh={manifest:{id:ah,name:"Interaction Manager Plugin",version:"1.0.0",provides:["interaction-manager"],requires:[],optional:[],defaultConfig:{exclusionRules:{classes:[],dataAttributes:["data-no-interaction"]}}},create:(e,t)=>new rh(ah,e,t),reducer:(e=sh,t)=>{switch(t.type){case Wu:{const{documentId:n,state:o}=t.payload;return{...e,documents:{...e.documents,[n]:o},activeDocumentId:e.activeDocumentId??n}}case Bu:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i,activeDocumentId:e.activeDocumentId===n?null:e.activeDocumentId}}case"INTERACTION/SET_ACTIVE_DOCUMENT":return{...e,activeDocumentId:t.payload};case qu:{const{documentId:n,mode:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,activeMode:o}}}:e}case Ku:{const{documentId:n,cursor:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,cursor:o}}}:e}case Gu:{const n=t.payload,o=e.documents[n];return o?{...e,documents:{...e.documents,[n]:{...o,paused:!0}}}:e}case Vu:{const n=t.payload,o=e.documents[n];return o?{...e,documents:{...e.documents,[n]:{...o,paused:!1}}}:e}case Zu:return{...e,defaultMode:t.payload.mode};case Yu:return{...e,exclusionRules:t.payload.rules};case Xu:return{...e,exclusionRules:{...e.exclusionRules,classes:[...e.exclusionRules.classes||[],t.payload.className].filter((e,t,n)=>n.indexOf(e)===t)}};case Qu:return{...e,exclusionRules:{...e.exclusionRules,classes:(e.exclusionRules.classes||[]).filter(e=>e!==t.payload.className)}};case Ju:return{...e,exclusionRules:{...e.exclusionRules,dataAttributes:[...e.exclusionRules.dataAttributes||[],t.payload.attribute].filter((e,t,n)=>n.indexOf(e)===t)}};case eh:return{...e,exclusionRules:{...e.exclusionRules,dataAttributes:(e.exclusionRules.dataAttributes||[]).filter(e=>e!==t.payload.attribute)}};default:return e}},initialState:sh},ch=()=>Oo(rh.id);const dh={pointerdown:"onPointerDown",pointerup:"onPointerUp",pointermove:"onPointerMove",pointerenter:"onPointerEnter",pointerleave:"onPointerLeave",pointercancel:"onPointerCancel",mousedown:"onMouseDown",mouseup:"onMouseUp",mousemove:"onMouseMove",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",mousecancel:"onMouseCancel",click:"onClick",dblclick:"onDoubleClick",touchstart:"onPointerDown",touchend:"onPointerUp",touchmove:"onPointerMove",touchcancel:"onPointerCancel"},uh=["pointerdown","pointerup","pointermove","pointerenter","pointerleave","pointercancel","mousedown","mouseup","mousemove","mouseenter","mouseleave","mousecancel","click","dblclick"],hh="undefined"!=typeof PointerEvent?uh:[...uh,"touchstart","touchend","touchmove","touchcancel"];function mh(e){return"undefined"!=typeof TouchEvent&&e instanceof TouchEvent}function gh(e,t,n,o){const i=e.forDocument(t.documentId);let r=e.getHandlersForScope(t);const a=()=>{var e;return!1!==(null==(e=i.getActiveInteractionMode())?void 0:e.wantsRawTouch)},s={};let l=a();const c=e=>{hh.forEach(t=>{const o=s[t]??(s[t]=v);var i;n.addEventListener(t,o,(i=e,t.startsWith("touch")?{passive:!i}:{passive:!1}))})},d=()=>{hh.forEach(e=>{const t=s[e];t&&n.removeEventListener(e,t)})};c(l),n.style.touchAction=l?"none":"";const u=i.onModeChange(()=>{if("global"===t.type){const e=i.getActiveInteractionMode();n.style.cursor="global"===(null==e?void 0:e.scope)?e.cursor??"auto":"auto"}r=e.getHandlersForScope(t);const o=a();o!==l&&(d(),c(o),l=o,n.style.touchAction=l?"none":"")}),h=e.onHandlerChange(()=>{r=e.getHandlersForScope(t)}),m=i.getActiveInteractionMode(),g=i.getCurrentCursor();n.style.cursor="global"===t.type&&"global"!==(null==m?void 0:m.scope)?"auto":g;const p=i.onCursorChange(e=>{var o;"global"===t.type&&"global"!==(null==(o=i.getActiveInteractionMode())?void 0:o.scope)||(n.style.cursor=e)}),f=(e,t)=>{if(o)return o(e,t);const n=t.getBoundingClientRect();return{x:e.clientX-n.left,y:e.clientY-n.top}};function v(t){var o;if(e.isPaused())return;const a=e.getExclusionRules();if(t.target&&function(e,t){var n,o,i;if(!e)return!1;let r=e;for(;r;){if(null==(n=t.classes)?void 0:n.length)for(const e of t.classes)if(null==(o=r.classList)?void 0:o.contains(e))return!0;if(null==(i=t.dataAttributes)?void 0:i.length)for(const e of t.dataAttributes)if(r.hasAttribute(e))return!0;r=r.parentElement}return!1}(t.target,a))return;const s=dh[t.type];if(!s||!(null==r?void 0:r[s]))return;let c,d;mh(t)&&l&&("touchmove"===t.type||"touchcancel"===t.type)&&t.preventDefault();let u=!1;if(mh(t)){const e="touchend"===t.type||"touchcancel"===t.type?t.changedTouches[0]:t.touches[0];if(!e)return;c=f(e,n),d={clientX:e.clientX,clientY:e.clientY,ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,target:t.target,currentTarget:t.currentTarget,setPointerCapture:()=>{},releasePointerCapture:()=>{},stopImmediatePropagation:()=>{u=!0},isImmediatePropagationStopped:()=>u}}else{const e=t;c=f(e,n),d={clientX:e.clientX,clientY:e.clientY,ctrlKey:e.ctrlKey,shiftKey:e.shiftKey,altKey:e.altKey,metaKey:e.metaKey,target:e.target,currentTarget:e.currentTarget,setPointerCapture:()=>{var t,n;null==(n=null==(t=e.target)?void 0:t.setPointerCapture)||n.call(t,e.pointerId)},releasePointerCapture:()=>{var t,n;null==(n=null==(t=e.target)?void 0:t.releasePointerCapture)||n.call(t,e.pointerId)},stopImmediatePropagation:()=>{u=!0},isImmediatePropagationStopped:()=>u}}null==(o=r[s])||o.call(r,c,d,i.getActiveMode())}return()=>{d(),u(),p(),h()}}const ph=({children:e,documentId:t,style:n,...o})=>{const i=De(null),{provides:r}=ch();return Me(()=>{if(r&&i.current)return gh(r,{type:"global",documentId:t},i.current)},[r,t]),He("div",{ref:i,style:{width:"100%",height:"100%",...n},...o,children:e})},fh=({documentId:e,pageIndex:t,children:n,rotation:o,scale:i,convertEventToPoint:r,style:a,...s})=>{var l,c;const d=De(null),{provides:u}=ch(),h=function(e){const{provides:t}=ch(),[n,o]=Se(()=>{if(!t)return!1;const n=t.forDocument(e).getActiveInteractionMode();return"page"===(null==n?void 0:n.scope)&&!!n.exclusive});return Me(()=>{if(!t)return;const n=t.forDocument(e);return n.onModeChange(()=>{const e=n.getActiveInteractionMode();o("page"===(null==e?void 0:e.scope)&&!!(null==e?void 0:e.exclusive))})},[t,e]),n}(e),m=jo(e),g=null==(c=null==(l=null==m?void 0:m.document)?void 0:l.pages)?void 0:c[t],p=(null==g?void 0:g.size)??{width:0,height:0},f=(null==g?void 0:g.rotation)??0,v=(null==m?void 0:m.rotation)??0,y=void 0!==o?o:(f+v)%4,b=i??(null==m?void 0:m.scale)??1,w=Ke(p,0,b),x=ze((e,t)=>{const n=t.getBoundingClientRect(),o={x:e.clientX-n.left,y:e.clientY-n.top};return function(e,t,n,o){return Qe(Xe(e,t,(4-n)%4),1/o)}(Ke({width:w.width,height:w.height},y,1),o,y,b)},[p,y,b]);return Me(()=>{if(u&&d.current)return gh(u,{type:"page",documentId:e,pageIndex:t},d.current,r||x)},[u,e,t,r,x]),He("div",{ref:d,style:{position:"relative",width:w.width,height:w.height,...a},...s,children:[n,h&&He("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10}})]})},vh={},yh=de(null),bh=de([]);const wh=()=>Lo(su.id),xh=()=>Oo(su.id),Ch=e=>{var t;const{provides:n}=xh(),[o,i]=Se((null==(t=null==n?void 0:n.forDocument(e))?void 0:t.getState())??{pages:{},byUid:{},selectedUids:[],selectedUid:null,activeToolId:null,hasPendingChanges:!1});return Me(()=>{if(!n)return;const t=n.forDocument(e);return i(t.getState()),t.onStateChange(e=>{i(e)})},[n,e]),{state:o,provides:(null==n?void 0:n.forDocument(e))??null}};function kh({appearance:e,style:t}){const[n,o]=Se(null),i=De(null);Me(()=>{const t=URL.createObjectURL(e.data);return o(t),i.current=t,()=>{i.current&&(URL.revokeObjectURL(i.current),i.current=null)}},[e.data]);return n?He("img",{src:n,onLoad:()=>{i.current&&(URL.revokeObjectURL(i.current),i.current=null)},style:{position:"absolute",width:"100%",height:"100%",display:"block",pointerEvents:"none",userSelect:"none",...t}}):null}function Ih({scale:e,documentId:t,pageIndex:n,rotation:o,pageWidth:i,pageHeight:r,trackedAnnotation:a,children:s,isSelected:l,isEditing:c=!1,isMultiSelected:d=!1,isDraggable:u,isResizable:h,isRotatable:m=!0,lockAspectRatio:g=!1,style:p={},vertexConfig:f,selectionMenu:v,outlineOffset:y=1,onDoubleClick:b,onSelect:w,appearance:x,zIndex:C=1,resizeUI:k,vertexUI:I,rotationUI:S,selectionOutlineColor:A,selectionOutline:M,customAnnotationRenderer:P,groupSelectionMenu:D,groupSelectionOutline:R,annotationRenderers:z,...T}){var E,_,N;const[L,O]=Se(a.object),[$,j]=Se(null),[F,U]=Se(null),[W,B]=Se(!1),[q,G]=Se(!1),{provides:V}=xh(),{plugin:K}=wh(),{canModifyAnnotations:Z}=Bo(t),Y=De(null),X=Z&&u&&!d,Q=Z&&h&&!d,J=Z&&m&&!d,ee=Re(()=>V?V.forDocument(t):null,[V,t]),te=L?{...a.object,...L}:a.object,ne=a.object.flags??[],oe=ne.includes("noZoom"),ie=ne.includes("noRotate"),re=oe?1:e,ae=ie?0:o,se=(null==k?void 0:k.color)??"#007ACC",le=(null==I?void 0:I.color)??"#007ACC",ce=(null==S?void 0:S.color)??"white",de=(null==S?void 0:S.connectorColor)??"#007ACC",ue=(null==k?void 0:k.size)??12,he=(null==I?void 0:I.size)??12,me=(null==S?void 0:S.size)??32,ge=null==S?void 0:S.margin,pe=(null==S?void 0:S.iconColor)??"#007ACC",fe=(null==S?void 0:S.showConnector)??!1,ve=(null==(E=null==S?void 0:S.border)?void 0:E.color)??"#007ACC",ye=(null==(_=null==S?void 0:S.border)?void 0:_.width)??1,be=(null==(N=null==S?void 0:S.border)?void 0:N.style)??"solid",we=(null==M?void 0:M.color)??A??"#007ACC",xe=(null==M?void 0:M.style)??"solid",Ce=(null==M?void 0:M.width)??1,ke=(null==M?void 0:M.offset)??y??1,Ie=$??te.rotation??0,Ae=$??te.rotation??0,Pe=Number.isFinite(Ae)?Math.round(10*Ae)/10:0,Te=null!==$,Ee=De(null),_e=ze(e=>{var o;if(!(null==(o=e.transformData)?void 0:o.type)||d||!K)return;const{type:s,changes:l,metadata:c}=e.transformData,u=a.object.id,h={width:i,height:r};if("start"===e.state&&(Ee.current=a.object.unrotatedRect??a.object.rect,Y.current=a.object,"resize"!==s&&"vertex-edit"!==s||G(!0),"move"===s?K.startDrag(t,{annotationIds:[u],pageSize:h}):"resize"===s&&K.startResize(t,{annotationIds:[u],pageSize:h,resizeHandle:(null==c?void 0:c.handle)??"se"})),l.rect&&Ee.current)if("move"===s){const e={x:l.rect.origin.x-Ee.current.origin.x,y:l.rect.origin.y-Ee.current.origin.y};K.updateDrag(t,e)}else"resize"===s&&K.updateResize(t,l.rect);if("vertex-edit"===s&&l.vertices&&f){const t=Y.current??a.object,o=f.transformAnnotation(t,l.vertices),i=null==V?void 0:V.transformAnnotation(t,{type:s,changes:o,metadata:c});i&&(O(e=>({...e,...i})),"end"===e.state&&(null==ee||ee.updateAnnotation(n,u,i)))}if("rotate"===s){const n=(null==c?void 0:c.rotationAngle)??Ie,o=null==c?void 0:c.cursorPosition;return o&&U({x:o.clientX,y:o.clientY}),void("start"===e.state?(j(n),K.startRotation(t,{annotationIds:[u],cursorAngle:n,rotationCenter:null==c?void 0:c.rotationCenter})):"move"===e.state?(j(n),K.updateRotation(t,n,null==c?void 0:c.rotationDelta)):"end"===e.state&&(j(null),U(null),K.commitRotation(t)))}"end"===e.state&&(Ee.current=null,Y.current=null,G(!1),"move"===s?K.commitDrag(t):"resize"===s&&K.commitResize(t))},[K,t,a.object,i,r,n,d,f,V,ee,Ie]),Ne=te.unrotatedRect,Le=Ne??te.rect,Oe=Ne&&0!==Ie?ht(Le,te.rect,Ie):void 0,$e=Le,{dragProps:je,vertices:Fe,resize:Ue,rotation:We}=Fl({controller:{element:$e,vertices:null==f?void 0:f.extractVertices(te),constraints:{minWidth:10,minHeight:10,boundingBox:{width:i,height:r}},maintainAspectRatio:g,pageRotation:o,annotationRotation:Ie,rotationCenter:Oe,rotationElement:te.rect,scale:e,enabled:l&&!d,onUpdate:_e},resizeUI:{handleSize:ue,spacing:ke,offsetMode:"outside",includeSides:!g,zIndex:C+1},vertexUI:{vertexSize:he,zIndex:C+2},rotationUI:{handleSize:me,margin:ge,zIndex:C+3,showConnector:fe},includeVertices:!!f,includeRotation:J,currentRotation:Ie}),Be=function(e,{delay:t=300,tolerancePx:n=18}={}){const o=De({t:0,x:0,y:0}),i=ze(i=>{if(!e)return;if("mouse"===i.pointerType||!1===i.isPrimary)return;const r=performance.now(),a=i.clientX,s=i.clientY,l=r-o.current.t<=t,c=a-o.current.x,d=s-o.current.y;l&&c*c+d*d<=n*n&&(null==e||e(i)),o.current={t:r,x:a,y:s}},[e,t,n]),r=ze(t=>{null==e||e(t)},[e]);return e?{[Rl]:r,onPointerUpCapture:i}:{}}(Re(()=>{if(Z&&b)return b},[Z,b]));Me(()=>{O(a.object)},[a.object]),Me(()=>{if(!K)return;const e=a.object.id,n=n=>{var o;if(n.documentId!==t)return;"end"!==n.type&&"cancel"!==n.type||j(null);const i=null==(o=n.previewPatches)?void 0:o[e];"update"===n.type&&i?O(e=>({...e,...i})):"cancel"===n.type&&O(a.object)},o=[K.onDragChange(n),K.onResizeChange(n),K.onRotateChange(n)];return()=>o.forEach(e=>e())},[K,t,a.object]);const qe=l&&!d,Ge=te.rect.size.width*re,Ve=te.rect.size.height*re,Ke=Le.size.width*re,Ze=Le.size.height*re,Ye=Boolean(Ne)&&0!==Ie,Xe=Ye?(Le.origin.x-te.rect.origin.x)*re:(Ge-Ke)/2,Qe=Ye?(Le.origin.y-te.rect.origin.y)*re:(Ve-Ze)/2,Je=Ye&&Oe?`${(Oe.x-Le.origin.x)*re}px ${(Oe.y-Le.origin.y)*re}px`:"center center",et=Oe?(Oe.x-te.rect.origin.x)*re:Ge/2,tt=Oe?(Oe.y-te.rect.origin.y)*re:Ve/2,nt=Math.max(300,Math.max(Ge,Ve)+80),ot=ie?Dl({size:{width:Ge,height:Ve}},o):null,it=Re(()=>Ne?{...te,rect:Ne}:te,[te,Ne]),rt=!(!(null==x?void 0:x.normal)||q||c||a.dictMode);return He("div",{"data-no-interaction":!0,children:[He("div",{style:{position:"absolute",left:te.rect.origin.x*e,top:te.rect.origin.y*e,width:ot?ot.width:Ge,height:ot?ot.height:Ve,pointerEvents:"none",zIndex:C,...ot&&{transform:ot.matrix,transformOrigin:"0 0"},...p},...T,children:[Te&&He(H,{children:[He("div",{style:{position:"absolute",left:et-nt/2,top:tt,width:nt,height:1,backgroundColor:de,opacity:.35,pointerEvents:"none"}}),He("div",{style:{position:"absolute",left:et,top:tt-nt/2,width:1,height:nt,backgroundColor:de,opacity:.35,pointerEvents:"none"}}),He("div",{style:{position:"absolute",left:et-nt/2,top:tt,width:nt,height:1,transformOrigin:"center center",transform:`rotate(${Ie}deg)`,backgroundColor:de,opacity:.8,pointerEvents:"none"}})]}),l&&J&&We&&((null==S?void 0:S.component)?He("div",{onPointerEnter:()=>B(!0),onPointerLeave:()=>{B(!1),U(null)},onPointerMove:e=>{Te||U({x:e.clientX,y:e.clientY})},style:{display:"contents"},children:S.component({...We.handle,backgroundColor:ce,iconColor:pe,connectorStyle:{...We.connector.style,backgroundColor:de,opacity:Te?0:1},showConnector:fe,opacity:Te?0:1,border:{color:ve,width:ye,style:be}})}):He("div",{onPointerEnter:()=>B(!0),onPointerLeave:()=>{B(!1),U(null)},onPointerMove:e=>{Te||U({x:e.clientX,y:e.clientY})},style:{display:"contents"},children:[fe&&He("div",{style:{...We.connector.style,backgroundColor:de,opacity:Te?0:1}}),He("div",{...We.handle,style:{...We.handle.style,backgroundColor:ce,border:`${ye}px ${be} ${ve}`,boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"auto",opacity:Te?0:1},children:He("svg",{width:Math.round(.6*me),height:Math.round(.6*me),viewBox:"0 0 24 24",fill:"none",stroke:pe,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[He("path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}),He("path",{d:"M21 3v5h-5"})]})})]})),He("div",{...X&&l?je:{},...Be,style:{position:"absolute",left:Xe,top:Qe,width:Ke,height:Ze,transform:0!==Ie?`rotate(${Ie}deg)`:void 0,transformOrigin:Je,outline:qe?`${Ce}px ${xe} ${we}`:"none",outlineOffset:qe?`${ke}px`:"0px",pointerEvents:l&&!d?"auto":"none",touchAction:"none",cursor:l&&X?"move":"default"},children:[(()=>{const t="function"==typeof s?s(it,{appearanceActive:rt}):s;return(null==P?void 0:P({annotation:it,children:t,isSelected:l,scale:e,rotation:o,pageWidth:i,pageHeight:r,pageIndex:n,onSelect:w}))??t})(),(null==x?void 0:x.normal)&&He(kh,{appearance:x.normal,style:{display:rt?"block":"none"}}),l&&Q&&!Te&&Ue.map(({key:e,...t})=>(null==k?void 0:k.component)?k.component({key:e,...t,backgroundColor:se}):He("div",{...t,style:{...t.style,backgroundColor:se}},e)),l&&Z&&!d&&!Te&&Fe.map(({key:e,...t})=>(null==I?void 0:I.component)?I.component({key:e,...t,backgroundColor:le}):He("div",{...t,style:{...t.style,backgroundColor:le}},e))]})]}),v&&!d&&!Te&&He(zl,{rect:{origin:{x:te.rect.origin.x*e,y:te.rect.origin.y*e},size:{width:te.rect.size.width*re,height:te.rect.size.height*re}},rotation:o,children:e=>{const t=((Ie+90*ae)%360+360)%360;return v({...e,context:{type:"annotation",annotation:a,pageIndex:n},selected:l,placement:{suggestTop:J&&t>90&&t<270}})}}),(Te||W)&&F&&Pu(He("div",{style:{position:"fixed",left:F.x+16,top:F.y-16,background:"rgba(0,0,0,0.8)",color:"#fff",padding:"4px 8px",borderRadius:4,fontSize:12,fontFamily:"monospace",pointerEvents:"none",zIndex:1e4,whiteSpace:"nowrap"},children:[Pe.toFixed(0),"°"]}),document.body)]})}function Sh(e,t,n,o,i){switch(i){case 1:return{x:t,y:o-e};case 2:return{x:n-e,y:o-t};case 3:return{x:n-t,y:e};default:return{x:e,y:t}}}function Ah(e,t,n){const o=e.object.flags??[],i=o.includes("noZoom"),r=o.includes("noRotate"),a=e.object.rect.origin.x*t,s=e.object.rect.origin.y*t,l=e.object.rect.size.width*(i?1:t),c=e.object.rect.size.height*(i?1:t);if(!r||0===n)return{left:a,top:s,right:a+l,bottom:s+c};const d=[Sh(0,0,l,c,n),Sh(l,0,l,c,n),Sh(0,c,l,c,n),Sh(l,c,l,c,n)];let u=1/0,h=1/0,m=-1/0,g=-1/0;for(const e of d)e.xm&&(m=e.x),e.y>g&&(g=e.y);return{left:a+u,top:s+h,right:a+m,bottom:s+g}}function Mh({documentId:e,pageIndex:t,scale:n,rotation:o,pageWidth:i,pageHeight:r,selectedAnnotations:a,isDraggable:s,isResizable:l,isRotatable:c=!0,lockAspectRatio:d=!1,resizeUI:u,rotationUI:h,selectionOutlineColor:m,outlineOffset:g,selectionOutline:p,zIndex:f=2,groupSelectionMenu:v}){var y,b,w;const{plugin:x}=wh(),{canModifyAnnotations:C}=Bo(e),k=De(null),I=De(!1),S=De(!1),[A,M]=Se(null),[P,D]=Se(null),[R,z]=Se(!1),T=C&&s,E=C&&l,_=C&&c,N=Re(()=>function(e){return rt(e)??it}(a.map(e=>e.object.rect)),[a]),[L,O]=Se(N);Me(()=>{I.current||S.current||O(N)},[N]),Me(()=>{if(!x)return;return x.onRotateChange(t=>{t.documentId===e&&("end"!==t.type&&"cancel"!==t.type||M(null))})},[x,e]);const $=ze(t=>{var n,o,s,l,d,u;if(!(null==(n=t.transformData)?void 0:n.type))return;if(!x)return;const h=t.transformData.type,m="move"===h,g="resize"===h;if(m&&!T)return;if("start"===t.state&&(k.current=N,m?(I.current=!0,x.startDrag(e,{annotationIds:a.map(e=>e.object.id),pageSize:{width:i,height:r}})):g&&(S.current=!0,x.startResize(e,{annotationIds:a.map(e=>e.object.id),pageSize:{width:i,height:r},resizeHandle:(null==(o=t.transformData.metadata)?void 0:o.handle)??"se"}))),"rotate"===h){if(!c)return;const n=a.map(e=>e.object.id),o=(null==(s=t.transformData.metadata)?void 0:s.rotationAngle)??0,i=null==(l=t.transformData.metadata)?void 0:l.cursorPosition;return i&&D({x:i.clientX,y:i.clientY}),void("start"===t.state?(M(o),x.startRotation(e,{annotationIds:n,cursorAngle:o,rotationCenter:null==(d=t.transformData.metadata)?void 0:d.rotationCenter})):"move"===t.state?(M(o),x.updateRotation(e,o,null==(u=t.transformData.metadata)?void 0:u.rotationDelta)):"end"===t.state&&(M(null),D(null),x.commitRotation(e)))}const p=k.current??N;if(m&&t.transformData.changes.rect){const n=t.transformData.changes.rect,o={x:n.origin.x-p.origin.x,y:n.origin.y-p.origin.y},i=x.updateDrag(e,o);O({...p,origin:{x:p.origin.x+i.x,y:p.origin.y+i.y}})}else if(g&&t.transformData.changes.rect){const n=t.transformData.changes.rect;x.updateResize(e,n),O(n)}"end"===t.state&&(k.current=null,m&&I.current?(I.current=!1,x.commitDrag(e)):g&&S.current&&(S.current=!1,x.commitResize(e)))},[x,e,i,r,N,T,a,c]),j=A??0,F=null!==A,U=Number.isFinite(j)?Math.round(10*j)/10:0,W=(null==u?void 0:u.color)??"#007ACC",B=(null==u?void 0:u.size)??12,q=(null==h?void 0:h.color)??"white",G=(null==h?void 0:h.connectorColor)??"#007ACC",V=(null==h?void 0:h.size)??32,K=null==h?void 0:h.margin,Z=(null==h?void 0:h.iconColor)??"#007ACC",Y=(null==h?void 0:h.showConnector)??!1,X=(null==(y=null==h?void 0:h.border)?void 0:y.color)??"#007ACC",Q=(null==(b=null==h?void 0:h.border)?void 0:b.width)??1,J=(null==(w=null==h?void 0:h.border)?void 0:w.style)??"solid",ee=(null==p?void 0:p.color)??m??"#007ACC",te=(null==p?void 0:p.style)??"dashed",ne=(null==p?void 0:p.width)??2,oe=(null==p?void 0:p.offset)??g??2,{dragProps:ie,resize:re,rotation:ae}=Fl({controller:{element:L,constraints:{minWidth:20,minHeight:20,boundingBox:{width:i,height:r}},maintainAspectRatio:d,pageRotation:o,scale:n,enabled:!0,onUpdate:$},resizeUI:{handleSize:B,spacing:oe,offsetMode:"outside",includeSides:!d,zIndex:f+1},vertexUI:{vertexSize:0,zIndex:f},rotationUI:{handleSize:V,margin:K,zIndex:f+2,showConnector:Y},includeVertices:!1,includeRotation:_,currentRotation:A??0});if(a.length<2)return null;let se=1/0,le=1/0,ce=-1/0,de=-1/0;for(const e of a){const t=Ah(e,n,o);se=Math.min(se,t.left),le=Math.min(le,t.top),ce=Math.max(ce,t.right),de=Math.max(de,t.bottom)}const ue=se-N.origin.x*n,he=le-N.origin.y*n,me=ce-(N.origin.x+N.size.width)*n,ge=de-(N.origin.y+N.size.height)*n,pe=L.origin.x*n+ue,fe=L.origin.y*n+he,ve=L.size.width*n+(me-ue),ye=L.size.height*n+(ge-he),be=ve/2,we=ye/2,xe=Math.max(300,Math.max(ve,ye)+80);return He("div",{"data-group-selection-box":!0,"data-no-interaction":!0,children:[He("div",{style:{position:"absolute",left:pe,top:fe,width:ve,height:ye,pointerEvents:"none",zIndex:f},children:[F&&He(H,{children:[He("div",{style:{position:"absolute",left:be-xe/2,top:we,width:xe,height:1,backgroundColor:W,opacity:.35,pointerEvents:"none"}}),He("div",{style:{position:"absolute",left:be,top:we-xe/2,width:1,height:xe,backgroundColor:W,opacity:.35,pointerEvents:"none"}}),He("div",{style:{position:"absolute",left:be-xe/2,top:we,width:xe,height:1,transformOrigin:"center center",transform:`rotate(${j}deg)`,backgroundColor:W,opacity:.8,pointerEvents:"none"}})]}),_&&ae&&((null==h?void 0:h.component)?He("div",{onPointerEnter:()=>z(!0),onPointerLeave:()=>{z(!1),D(null)},onPointerMove:e=>{F||D({x:e.clientX,y:e.clientY})},style:{display:"contents"},children:h.component({...ae.handle,backgroundColor:q,iconColor:Z,connectorStyle:{...ae.connector.style,backgroundColor:G,opacity:F?0:1},showConnector:Y,opacity:F?0:1,border:{color:X,width:Q,style:J}})}):He("div",{onPointerEnter:()=>z(!0),onPointerLeave:()=>{z(!1),D(null)},onPointerMove:e=>{F||D({x:e.clientX,y:e.clientY})},style:{display:"contents"},children:[Y&&He("div",{style:{...ae.connector.style,backgroundColor:G,opacity:F?0:1}}),He("div",{...ae.handle,style:{...ae.handle.style,backgroundColor:q,border:`${Q}px ${J} ${X}`,boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"auto",opacity:F?0:1},children:He("svg",{width:Math.round(.6*V),height:Math.round(.6*V),viewBox:"0 0 24 24",fill:"none",stroke:Z,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[He("path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}),He("path",{d:"M21 3v5h-5"})]})})]})),He("div",{...T?ie:{onPointerDown:e=>e.stopPropagation()},style:{position:"absolute",left:0,top:0,width:ve,height:ye,outline:F?"none":`${ne}px ${te} ${ee}`,outlineOffset:oe-1,cursor:T?"move":"default",touchAction:"none",pointerEvents:"auto"},children:E&&!F&&re.map(({key:e,...t})=>(null==u?void 0:u.component)?u.component({key:e,...t,backgroundColor:W}):He("div",{...t,style:{...t.style,backgroundColor:W}},e))})]}),(F||R)&&P&&Pu(He("div",{style:{position:"fixed",left:P.x+16,top:P.y-16,background:"rgba(0,0,0,0.8)",color:"#fff",padding:"4px 8px",borderRadius:4,fontSize:12,fontFamily:"monospace",pointerEvents:"none",zIndex:1e4,whiteSpace:"nowrap"},children:[U.toFixed(0),"°"]}),document.body),v&&He(zl,{rect:{origin:{x:pe,y:fe},size:{width:ve,height:ye}},rotation:o,children:e=>{const n=((j+90*o)%360+360)%360;return v({...e,context:{type:"group",annotations:a,pageIndex:t},selected:!0,placement:{suggestTop:_&&n>90&&n<270}})}})]})}function Ph(e){return{id:e.id,matches:t=>e.matches(t),render:t=>e.render(t),vertexConfig:e.vertexConfig,zIndex:e.zIndex,containerStyle:e.containerStyle,interactionDefaults:e.interactionDefaults,useAppearanceStream:e.useAppearanceStream,isDraggable:e.isDraggable,onDoubleClick:e.onDoubleClick,selectOverride:e.selectOverride,hideSelectionMenu:e.hideSelectionMenu}}function Dh({isSelected:e,strokeColor:t,opacity:n=1,strokeWidth:o,inkList:i,rect:r,scale:a,onClick:s,appearanceActive:l=!1}){const c=t??"#000000",d=Re(()=>i.map(({points:e})=>{let t="";return e.forEach(({x:e,y:n},o)=>{const i=e-r.origin.x,a=n-r.origin.y;t+=(0===o?"M":"L")+i+" "+a+" "}),t.trim()}),[i,r]),u=r.size.width*a,h=r.size.height*a,m=Math.max(o,20/a);return He("svg",{style:{position:"absolute",width:u,height:h,pointerEvents:"none",zIndex:2,overflow:"visible"},width:u,height:h,viewBox:`0 0 ${r.size.width} ${r.size.height}`,children:[d.map((t,n)=>He("path",{d:t,fill:"none",stroke:"transparent",strokeWidth:m,onPointerDown:s,style:{cursor:e?"move":"pointer",pointerEvents:e?"none":"visibleStroke",strokeLinecap:"round",strokeLinejoin:"round"}},`hit-${n}`)),!l&&d.map((e,t)=>He("path",{d:e,fill:"none",opacity:n,style:{pointerEvents:"none",stroke:c,strokeWidth:o,strokeLinecap:"round",strokeLinejoin:"round"}},`vis-${t}`))]})}function Rh({isSelected:e,color:t="#000000",strokeColor:n,opacity:o=1,strokeWidth:i,strokeStyle:r=Bt.SOLID,strokeDashArray:a,rect:s,scale:l,onClick:c,appearanceActive:d=!1}){const{width:u,height:h,x:m,y:g}=Re(()=>{const e=s.size.width,t=s.size.height;return{width:Math.max(e-i,0),height:Math.max(t-i,0),x:i/2,y:i/2}},[s,i]),p=(u+i)*l,f=(h+i)*l,v=Math.max(i,20/l);return He("svg",{style:{position:"absolute",width:p,height:f,pointerEvents:"none",zIndex:2},width:p,height:f,viewBox:`0 0 ${u+i} ${h+i}`,overflow:"visible",children:[He("rect",{x:m,y:g,width:u,height:h,fill:"transparent",stroke:"transparent",strokeWidth:v,onPointerDown:c,style:{cursor:e?"move":"pointer",pointerEvents:e?"none":"transparent"===t?"visibleStroke":"visible"}}),!d&&He("rect",{x:m,y:g,width:u,height:h,fill:t,opacity:o,style:{pointerEvents:"none",stroke:n??t,strokeWidth:i,...r===Bt.DASHED&&{strokeDasharray:null==a?void 0:a.join(",")}}})]})}function zh({color:e="#000000",strokeColor:t,opacity:n=1,strokeWidth:o,strokeStyle:i=Bt.SOLID,strokeDashArray:r,rect:a,scale:s,onClick:l,isSelected:c,appearanceActive:d=!1}){const{width:u,height:h,cx:m,cy:g,rx:p,ry:f}=Re(()=>{const e=a.size.width,t=a.size.height,n=Math.max(e-o,0),i=Math.max(t-o,0);return{width:e,height:t,cx:o/2+n/2,cy:o/2+i/2,rx:n/2,ry:i/2}},[a,o]),v=u*s,y=h*s;return He("svg",{style:{position:"absolute",width:v,height:y,pointerEvents:"none",zIndex:2},width:v,height:y,viewBox:`0 0 ${u} ${h}`,overflow:"visible",children:[He("ellipse",{cx:m,cy:g,rx:p,ry:f,fill:"transparent",stroke:"transparent",strokeWidth:Math.max(o,20/s),onPointerDown:l,style:{cursor:c?"move":"pointer",pointerEvents:c?"none":"transparent"===e?"visibleStroke":"visible"}}),!d&&He("ellipse",{cx:m,cy:g,rx:p,ry:f,fill:e,opacity:n,style:{pointerEvents:"none",stroke:t??e,strokeWidth:o,...i===Bt.DASHED&&{strokeDasharray:null==r?void 0:r.join(",")}}})]})}function Th({color:e="transparent",opacity:t=1,strokeWidth:n,strokeColor:o="#000000",strokeStyle:i=Bt.SOLID,strokeDashArray:r,rect:a,linePoints:s,lineEndings:l,scale:c,onClick:d,isSelected:u,appearanceActive:h=!1}){const{x1:m,y1:g,x2:p,y2:f}=Re(()=>({x1:s.start.x-a.origin.x,y1:s.start.y-a.origin.y,x2:s.end.x-a.origin.x,y2:s.end.y-a.origin.y}),[s,a]),v=Re(()=>{const e=Math.atan2(f-g,p-m);return{start:Od.createEnding(null==l?void 0:l.start,n,e+Math.PI,m,g),end:Od.createEnding(null==l?void 0:l.end,n,e,p,f)}},[l,n,m,g,p,f]),y=a.size.width*c,b=a.size.height*c,w=Math.max(n,20/c);return He("svg",{style:{position:"absolute",width:y,height:b,pointerEvents:"none",zIndex:2,overflow:"visible"},width:y,height:b,viewBox:`0 0 ${a.size.width} ${a.size.height}`,children:[He("line",{x1:m,y1:g,x2:p,y2:f,stroke:"transparent",strokeWidth:w,onPointerDown:d,style:{cursor:u?"move":"pointer",pointerEvents:u?"none":"visibleStroke",strokeLinecap:"butt"}}),v.start&&He("path",{d:v.start.d,transform:v.start.transform,fill:"transparent",stroke:"transparent",strokeWidth:w,onPointerDown:d,style:{cursor:u?"move":"pointer",pointerEvents:u?"none":v.start.filled?"visible":"visibleStroke",strokeLinecap:"butt"}}),v.end&&He("path",{d:v.end.d,transform:v.end.transform,fill:"transparent",stroke:"transparent",strokeWidth:w,onPointerDown:d,style:{cursor:u?"move":"pointer",pointerEvents:u?"none":v.end.filled?"visible":"visibleStroke",strokeLinecap:"butt"}}),!h&&He(H,{children:[He("line",{x1:m,y1:g,x2:p,y2:f,opacity:t,style:{pointerEvents:"none",stroke:o,strokeWidth:n,strokeLinecap:"butt",...i===Bt.DASHED&&{strokeDasharray:null==r?void 0:r.join(",")}}}),v.start&&He("path",{d:v.start.d,transform:v.start.transform,stroke:o,fill:v.start.filled?e:"none",style:{pointerEvents:"none",strokeWidth:n,strokeLinecap:"butt",...i===Bt.DASHED&&{strokeDasharray:null==r?void 0:r.join(",")}}}),v.end&&He("path",{d:v.end.d,transform:v.end.transform,stroke:o,fill:v.end.filled?e:"none",style:{pointerEvents:"none",strokeWidth:n,strokeLinecap:"butt",...i===Bt.DASHED&&{strokeDasharray:null==r?void 0:r.join(",")}}})]})]})}function Eh({rect:e,vertices:t,color:n="transparent",strokeColor:o="#000000",opacity:i=1,strokeWidth:r,strokeStyle:a=Bt.SOLID,strokeDashArray:s,scale:l,isSelected:c,onClick:d,lineEndings:u,appearanceActive:h=!1}){const m=Re(()=>t.map(({x:t,y:n})=>({x:t-e.origin.x,y:n-e.origin.y})),[t,e]),g=Re(()=>{if(!m.length)return"";const[e,...t]=m;return`M ${e.x} ${e.y} `+t.map(e=>`L ${e.x} ${e.y} `).join("").trim()},[m]),p=Re(()=>{if(m.length<2)return{start:null,end:null};const e=(e,t)=>Math.atan2(t.y-e.y,t.x-e.x),t=e(m[0],m[1]),n=e(m[m.length-2],m[m.length-1]);return{start:Od.createEnding(null==u?void 0:u.start,r,t+Math.PI,m[0].x,m[0].y),end:Od.createEnding(null==u?void 0:u.end,r,n,m[m.length-1].x,m[m.length-1].y)}},[m,u,r]),f=e.size.width*l,v=e.size.height*l,y=Math.max(r,20/l);return He("svg",{style:{position:"absolute",width:f,height:v,pointerEvents:"none",zIndex:2,overflow:"visible"},width:f,height:v,viewBox:`0 0 ${e.size.width} ${e.size.height}`,children:[He("path",{d:g,fill:"none",stroke:"transparent",strokeWidth:y,onPointerDown:d,style:{cursor:c?"move":"pointer",pointerEvents:c?"none":"visibleStroke",strokeLinecap:"butt",strokeLinejoin:"miter"}}),p.start&&He("path",{d:p.start.d,transform:p.start.transform,fill:"transparent",stroke:"transparent",strokeWidth:y,onPointerDown:d,style:{cursor:c?"move":"pointer",pointerEvents:c?"none":p.start.filled?"visible":"visibleStroke",strokeLinecap:"butt"}}),p.end&&He("path",{d:p.end.d,transform:p.end.transform,fill:"transparent",stroke:"transparent",strokeWidth:y,onPointerDown:d,style:{cursor:c?"move":"pointer",pointerEvents:c?"none":p.end.filled?"visible":"visibleStroke",strokeLinecap:"butt"}}),!h&&He(H,{children:[He("path",{d:g,opacity:i,style:{fill:"none",stroke:o??n,strokeWidth:r,pointerEvents:"none",strokeLinecap:"butt",strokeLinejoin:"miter",...a===Bt.DASHED&&{strokeDasharray:null==s?void 0:s.join(",")}}}),p.start&&He("path",{d:p.start.d,transform:p.start.transform,stroke:o,fill:p.start.filled?n:"none",style:{pointerEvents:"none",strokeWidth:r,strokeLinecap:"butt",...a===Bt.DASHED&&{strokeDasharray:null==s?void 0:s.join(",")}}}),p.end&&He("path",{d:p.end.d,transform:p.end.transform,stroke:o,fill:p.end.filled?n:"none",style:{pointerEvents:"none",strokeWidth:r,strokeLinecap:"butt",...a===Bt.DASHED&&{strokeDasharray:null==s?void 0:s.join(",")}}})]})]})}function _h({rect:e,vertices:t,color:n="transparent",strokeColor:o="#000000",opacity:i=1,strokeWidth:r,strokeStyle:a=Bt.SOLID,strokeDashArray:s,scale:l,isSelected:c,onClick:d,currentVertex:u,handleSize:h=14,appearanceActive:m=!1}){const g=u?[...t,u]:t,p=Re(()=>g.map(({x:t,y:n})=>({x:t-e.origin.x,y:n-e.origin.y})),[g,e]),f=Re(()=>{if(!p.length)return"";const[e,...t]=p,n=!!u;return(`M ${e.x} ${e.y} `+t.map(e=>`L ${e.x} ${e.y}`).join(" ")+(n?"":" Z")).trim()},[p,u]),v=u&&t.length>0,y=e.size.width*l,b=e.size.height*l,w=Math.max(r,20/l);return He("svg",{style:{position:"absolute",width:y,height:b,pointerEvents:"none",zIndex:2,overflow:"visible"},width:y,height:b,viewBox:`0 0 ${e.size.width} ${e.size.height}`,children:[He("path",{d:f,fill:"transparent",stroke:"transparent",strokeWidth:w,onPointerDown:d,style:{cursor:c?"move":"pointer",pointerEvents:c?"none":"transparent"===n?"visibleStroke":"visible",strokeLinecap:"butt",strokeLinejoin:"miter"}}),!m&&He(H,{children:[He("path",{d:f,opacity:i,style:{fill:u?"none":n,stroke:o??n,strokeWidth:r,pointerEvents:"none",strokeLinecap:"butt",strokeLinejoin:"miter",...a===Bt.DASHED&&{strokeDasharray:null==s?void 0:s.join(",")}}}),v&&t.length>1&&He("path",{d:`M ${p[p.length-1].x} ${p[p.length-1].y} L ${p[0].x} ${p[0].y}`,fill:"none",style:{stroke:o,strokeWidth:r,strokeDasharray:"4,4",opacity:.7,pointerEvents:"none"}}),v&&t.length>=2&&He("rect",{x:p[0].x-h/l/2,y:p[0].y-h/l/2,width:h/l,height:h/l,fill:o,opacity:.4,stroke:o,strokeWidth:r/2,style:{pointerEvents:"none"}})]})]})}function Nh({isSelected:e,color:t="#facc15",opacity:n=1,onClick:o,appearanceActive:i=!1}){const r=function(e){try{const{red:t,green:n,blue:o}=rn(e);return(.299*t+.587*n+.114*o)/255<.45?"#fff":"#000"}catch{return"#000"}}(t);return He("div",{style:{position:"absolute",inset:0,zIndex:2,pointerEvents:e?"none":"auto",cursor:e?"move":"pointer"},onPointerDown:o,children:!i&&He("svg",{style:{position:"absolute",inset:0,pointerEvents:"none"},viewBox:"0 0 20 20",width:"100%",height:"100%",children:[He("path",{d:"M 0.5 15.5 L 0.5 0.5 L 19.5 0.5 L 19.5 15.5 L 8.5 15.5 L 6.5 19.5 L 4.5 15.5 Z",fill:t,opacity:n,stroke:r,strokeWidth:"1",strokeLinejoin:"miter"}),He("line",{x1:"2.5",y1:"4.25",x2:"17.5",y2:"4.25",stroke:r,strokeWidth:"1"}),He("line",{x1:"2.5",y1:"8",x2:"17.5",y2:"8",stroke:r,strokeWidth:"1"}),He("line",{x1:"2.5",y1:"11.75",x2:"17.5",y2:"11.75",stroke:r,strokeWidth:"1"})]})})}function Lh({documentId:e,isSelected:t,isEditing:n,annotation:o,pageIndex:i,scale:r,onClick:a,appearanceActive:s=!1}){const l=De(null),c=De(!1),{provides:d}=xh(),u=(null==d?void 0:d.forDocument(e))??null,[h,m]=Se(!1);Me(()=>{if(n&&l.current){c.current=!0;const e=l.current;e.focus();const t=window.getSelection();if(t){const n=document.createRange();n.selectNodeContents(e),n.collapse(!1),t.removeAllRanges(),t.addRange(n)}}},[n]),Pe(()=>{try{const e=navigator,t=/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&(null==e?void 0:e.maxTouchPoints)>1;m(t)}catch{m(!1)}},[]);const g=o.object.fontSize*r,p=h&&n&&g>0&&g<16,f=p?16:g,v=p?g/16:1,y=p?100/v:100;return He("div",{style:{position:"absolute",width:o.object.rect.size.width*r,height:o.object.rect.size.height*r,cursor:t&&!n?"move":"default",pointerEvents:t&&!n?"none":"auto",zIndex:2,opacity:s?0:1},onPointerDown:a,children:He("span",{ref:l,onBlur:()=>{c.current&&(c.current=!1,u&&l.current&&u.updateAnnotation(i,o.object.id,{contents:l.current.innerText}))},tabIndex:0,style:{color:o.object.fontColor,fontSize:f,...In(o.object.fontFamily),textAlign:hn(o.object.textAlign),flexDirection:"column",justifyContent:o.object.verticalAlign===Rt.Top?"flex-start":o.object.verticalAlign===Rt.Middle?"center":"flex-end",display:"flex",backgroundColor:o.object.color??o.object.backgroundColor,opacity:o.object.opacity,width:p?`${y}%`:"100%",height:p?`${y}%`:"100%",lineHeight:"1.18",overflow:"hidden",cursor:n?"text":"pointer",outline:"none",transform:p?`scale(${v})`:void 0,transformOrigin:"top left"},contentEditable:n,...vh,children:o.object.contents})})}function Oh({documentId:e,pageIndex:t,annotation:n,scaleFactor:o=1,unrotated:i,style:r,...a}){const{provides:s}=xh(),[l,c]=Se(null),d=De(null),{width:u,height:h}=n.rect.size;Me(()=>{if(s){const r=s.forDocument(e).renderAnnotation({pageIndex:t,annotation:n,options:{scaleFactor:o,dpr:window.devicePixelRatio,unrotated:i}});return r.wait(e=>{const t=URL.createObjectURL(e);c(t),d.current=t},Ln),()=>{d.current?(URL.revokeObjectURL(d.current),d.current=null):r.abort({code:tn.Cancelled,message:"canceled render task"})}}},[t,o,i,s,e,n.id,u,h]);return He(H,{children:l&&He("img",{src:l,onLoad:()=>{d.current&&(URL.revokeObjectURL(d.current),d.current=null)},...a,style:{width:"100%",height:"100%",display:"block",...r||{}}})})}function $h({isSelected:e,annotation:t,documentId:n,pageIndex:o,scale:i,onClick:r}){const a=!!t.object.rotation&&!!t.object.unrotatedRect;return He("div",{style:{position:"absolute",width:"100%",height:"100%",zIndex:2,pointerEvents:e?"none":"auto",cursor:"pointer"},onPointerDown:r,children:He(Oh,{documentId:n,pageIndex:o,annotation:{...t.object,id:t.object.id},scaleFactor:i,unrotated:a})})}function jh({isSelected:e,strokeColor:t="#0000FF",strokeWidth:n=2,strokeStyle:o=Bt.UNDERLINE,strokeDashArray:i,rect:r,scale:a,onClick:s,hasIRT:l=!1}){const{width:c,height:d}=Re(()=>({width:r.size.width,height:r.size.height}),[r]),u=c*a,h=d*a,m=Re(()=>{if(o===Bt.DASHED)return(null==i?void 0:i.join(","))??`${3*n},${n}`},[o,i,n]),g=o===Bt.UNDERLINE;return He("svg",{style:{position:"absolute",width:u,height:h,pointerEvents:"none",zIndex:2},width:u,height:h,viewBox:`0 0 ${c} ${d}`,children:[He("rect",{x:0,y:0,width:c,height:d,fill:"transparent",onPointerDown:l?void 0:s,style:{cursor:l?"default":e?"move":"pointer",pointerEvents:l||e?"none":"visible"}}),g?He("line",{x1:1,y1:d-1,x2:c-1,y2:d-1,stroke:t,strokeWidth:n,strokeDasharray:m,style:{pointerEvents:"none"}}):He("rect",{x:n/2,y:n/2,width:Math.max(c-n,0),height:Math.max(d-n,0),fill:"transparent",stroke:t,strokeWidth:n,strokeDasharray:m,style:{pointerEvents:"none"}})]})}function Fh({strokeColor:e,opacity:t=.5,segmentRects:n,rect:o,scale:i,onClick:r,style:a,appearanceActive:s=!1}){const l=e??"#FFFF00";return He(H,{children:n.map((e,n)=>He("div",{onPointerDown:r,style:{position:"absolute",left:(o?e.origin.x-o.origin.x:e.origin.x)*i,top:(o?e.origin.y-o.origin.y:e.origin.y)*i,width:e.size.width*i,height:e.size.height*i,background:s?"transparent":l,opacity:s?void 0:t,pointerEvents:r?"auto":"none",cursor:r?"pointer":"default",zIndex:r?1:void 0,...a}},n))})}function Uh({strokeColor:e,opacity:t=.5,segmentRects:n,rect:o,scale:i,onClick:r,style:a,appearanceActive:s=!1}){const l=e??"#FFFF00",c=2*i;return He(H,{children:n.map((e,n)=>He("div",{onPointerDown:r,style:{position:"absolute",left:(o?e.origin.x-o.origin.x:e.origin.x)*i,top:(o?e.origin.y-o.origin.y:e.origin.y)*i,width:e.size.width*i,height:e.size.height*i,background:"transparent",pointerEvents:r?"auto":"none",cursor:r?"pointer":"default",zIndex:r?1:0,...a},children:!s&&He("div",{style:{position:"absolute",left:0,bottom:0,width:"100%",height:c,background:l,opacity:t,pointerEvents:"none"}})},n))})}function Hh({strokeColor:e,opacity:t=.5,segmentRects:n,rect:o,scale:i,onClick:r,style:a,appearanceActive:s=!1}){const l=e??"#FFFF00",c=2*i;return He(H,{children:n.map((e,n)=>He("div",{onPointerDown:r,style:{position:"absolute",left:(o?e.origin.x-o.origin.x:e.origin.x)*i,top:(o?e.origin.y-o.origin.y:e.origin.y)*i,width:e.size.width*i,height:e.size.height*i,background:"transparent",pointerEvents:r?"auto":"none",cursor:r?"pointer":"default",zIndex:r?1:0,...a},children:!s&&He("div",{style:{position:"absolute",left:0,top:"50%",width:"100%",height:c,background:l,opacity:t,transform:"translateY(-50%)",pointerEvents:"none"}})},n))})}function Wh({strokeColor:e,opacity:t=.5,segmentRects:n,rect:o,scale:i,onClick:r,style:a,appearanceActive:s=!1}){const l=2*i,c=6*i,d=`url("data:image/svg+xml;utf8,${encodeURIComponent(`\n \n `)}")`;return He(H,{children:n.map((e,n)=>He("div",{onPointerDown:r,style:{position:"absolute",left:(o?e.origin.x-o.origin.x:e.origin.x)*i,top:(o?e.origin.y-o.origin.y:e.origin.y)*i,width:e.size.width*i,height:e.size.height*i,background:"transparent",pointerEvents:r?"auto":"none",cursor:r?"pointer":"default",zIndex:r?1:0,...a},children:!s&&He("div",{style:{position:"absolute",left:0,bottom:0,width:"100%",height:2*l,backgroundImage:d,backgroundRepeat:"repeat-x",backgroundSize:`${c}px ${2*l}px`,opacity:t,pointerEvents:"none"}})},n))})}function Bh({isSelected:e,strokeColor:t="#000000",opacity:n=1,rect:o,scale:i,onClick:r,appearanceActive:a=!1}){const{width:s,height:l,path:c}=Re(()=>{const e=o.size.width,t=o.size.height,n=e/2;return{width:e,height:t,path:[`M 0 ${t}`,`C ${.27*e} ${t} ${n} ${t-.44*t} ${n} 0`,`C ${n} ${t-.44*t} ${e-.27*e} ${t} ${e} ${t}`,"Z"].join(" ")}},[o]),d=s*i,u=l*i;return He("svg",{style:{position:"absolute",width:d,height:u,pointerEvents:"none",zIndex:2},width:d,height:u,viewBox:`0 0 ${s} ${l}`,overflow:"visible",children:[He("path",{d:c,fill:"transparent",stroke:"transparent",strokeWidth:4,onPointerDown:r,style:{cursor:e?"move":"pointer",pointerEvents:e?"none":"visible"}}),!a&&He("path",{d:c,fill:t,stroke:t,strokeWidth:.5,opacity:n,fillRule:"evenodd",style:{pointerEvents:"none"}})]})}const qh=[Ph({id:"ink",matches:e=>e.type===Ot.INK,render:({currentObject:e,isSelected:t,scale:n,onClick:o,appearanceActive:i})=>He(Dh,{...e,isSelected:t,scale:n,onClick:o,appearanceActive:i}),interactionDefaults:{isDraggable:!0,isResizable:!0,isRotatable:!0}}),Ph({id:"square",matches:e=>e.type===Ot.SQUARE,render:({currentObject:e,isSelected:t,scale:n,onClick:o,appearanceActive:i})=>He(Rh,{...e,isSelected:t,scale:n,onClick:o,appearanceActive:i}),interactionDefaults:{isDraggable:!0,isResizable:!0,isRotatable:!0}}),Ph({id:"circle",matches:e=>e.type===Ot.CIRCLE,render:({currentObject:e,isSelected:t,scale:n,onClick:o,appearanceActive:i})=>He(zh,{...e,isSelected:t,scale:n,onClick:o,appearanceActive:i}),interactionDefaults:{isDraggable:!0,isResizable:!0,isRotatable:!0}}),Ph({id:"line",matches:e=>e.type===Ot.LINE,render:({currentObject:e,isSelected:t,scale:n,onClick:o,appearanceActive:i})=>He(H,{children:He(Th,{...e,isSelected:t,scale:n,onClick:o,appearanceActive:i})}),vertexConfig:{extractVertices:e=>[e.linePoints.start,e.linePoints.end],transformAnnotation:(e,t)=>({...e,linePoints:{start:t[0],end:t[1]}})},interactionDefaults:{isDraggable:!0,isResizable:!1,isRotatable:!0}}),Ph({id:"polyline",matches:e=>e.type===Ot.POLYLINE,render:({currentObject:e,isSelected:t,scale:n,onClick:o,appearanceActive:i})=>He(H,{children:He(Eh,{...e,isSelected:t,scale:n,onClick:o,appearanceActive:i})}),vertexConfig:{extractVertices:e=>e.vertices,transformAnnotation:(e,t)=>({...e,vertices:t})},interactionDefaults:{isDraggable:!0,isResizable:!1,isRotatable:!0}}),Ph({id:"polygon",matches:e=>e.type===Ot.POLYGON,render:({currentObject:e,isSelected:t,scale:n,onClick:o,appearanceActive:i})=>He(H,{children:He(_h,{...e,isSelected:t,scale:n,onClick:o,appearanceActive:i})}),vertexConfig:{extractVertices:e=>e.vertices,transformAnnotation:(e,t)=>({...e,vertices:t})},interactionDefaults:{isDraggable:!0,isResizable:!1,isRotatable:!0}}),Ph({id:"highlight",matches:e=>e.type===Ot.HIGHLIGHT,render:({currentObject:e,scale:t,onClick:n,appearanceActive:o})=>He(Fh,{...e,scale:t,onClick:n,appearanceActive:o}),zIndex:0,interactionDefaults:{isDraggable:!1,isResizable:!1,isRotatable:!1},containerStyle:e=>({mixBlendMode:Dn(e.blendMode??zt.Multiply)})}),Ph({id:"underline",matches:e=>e.type===Ot.UNDERLINE,render:({currentObject:e,scale:t,onClick:n,appearanceActive:o})=>He(Uh,{...e,scale:t,onClick:n,appearanceActive:o}),zIndex:0,interactionDefaults:{isDraggable:!1,isResizable:!1,isRotatable:!1}}),Ph({id:"strikeout",matches:e=>e.type===Ot.STRIKEOUT,render:({currentObject:e,scale:t,onClick:n,appearanceActive:o})=>He(Hh,{...e,scale:t,onClick:n,appearanceActive:o}),zIndex:0,interactionDefaults:{isDraggable:!1,isResizable:!1,isRotatable:!1}}),Ph({id:"squiggly",matches:e=>e.type===Ot.SQUIGGLY,render:({currentObject:e,scale:t,onClick:n,appearanceActive:o})=>He(Wh,{...e,scale:t,onClick:n,appearanceActive:o}),zIndex:0,interactionDefaults:{isDraggable:!1,isResizable:!1,isRotatable:!1}}),Ph({id:"text",matches:e=>e.type===Ot.TEXT&&!e.inReplyToId,render:({currentObject:e,isSelected:t,onClick:n,appearanceActive:o})=>He(Nh,{isSelected:t,color:e.strokeColor??e.color,opacity:e.opacity,onClick:n,appearanceActive:o}),interactionDefaults:{isDraggable:!0,isResizable:!1,isRotatable:!1}}),Ph({id:"caret",matches:e=>e.type===Ot.CARET,render:({currentObject:e,isSelected:t,scale:n,onClick:o,appearanceActive:i})=>He(Bh,{...e,isSelected:t,scale:n,onClick:o,appearanceActive:i}),interactionDefaults:{isDraggable:!1,isResizable:!1,isRotatable:!1}}),Ph({id:"freeText",matches:e=>e.type===Ot.FREETEXT,render:({annotation:e,currentObject:t,isSelected:n,isEditing:o,scale:i,pageIndex:r,documentId:a,onClick:s,appearanceActive:l})=>He(Lh,{documentId:a,isSelected:n,isEditing:o,annotation:{...e,object:t},pageIndex:r,scale:i,onClick:s,appearanceActive:l}),interactionDefaults:{isDraggable:!0,isResizable:!0,isRotatable:!0},isDraggable:(e,{isEditing:t})=>e&&!t,onDoubleClick:(e,t)=>t(e)}),Ph({id:"stamp",matches:e=>e.type===Ot.STAMP,render:({annotation:e,isSelected:t,documentId:n,pageIndex:o,scale:i,onClick:r})=>He($h,{isSelected:t,annotation:e,documentId:n,pageIndex:o,scale:i,onClick:r}),useAppearanceStream:!1,interactionDefaults:{isDraggable:!0,isResizable:!0,isRotatable:!0}}),Ph({id:"link",matches:e=>e.type===Ot.LINK,render:({currentObject:e,isSelected:t,scale:n,onClick:o})=>He(jh,{...e,isSelected:t,scale:n,onClick:o,hasIRT:!!e.inReplyToId}),interactionDefaults:{isDraggable:!1,isResizable:!1,isRotatable:!1},useAppearanceStream:!1,selectOverride:(e,t,n)=>{if(e.stopPropagation(),n.clearSelection(),t.object.inReplyToId){const e=n.allAnnotations.find(e=>e.object.id===t.object.inReplyToId);if(e)return void n.selectAnnotation(e.object.pageIndex,e.object.id)}n.selectAnnotation(n.pageIndex,t.object.id)},hideSelectionMenu:e=>!!e.inReplyToId})];function Gh(e){const{documentId:t,pageIndex:n,scale:o,pageWidth:i,pageHeight:r,selectionMenu:a}=e,{provides:s}=xh(),{provides:l}=Ul(),[c,d]=Se([]),{register:u}=function({modeId:e,pageIndex:t,documentId:n}){const{provides:o}=ch();return{register:(i,r)=>{const a=(null==r?void 0:r.modeId)??e,s=(null==r?void 0:r.pageIndex)??t,l=(null==r?void 0:r.documentId)??n;return a?null==o?void 0:o.registerHandlers({modeId:a,handlers:i,pageIndex:s,documentId:l}):null==o?void 0:o.registerAlways({scope:void 0!==s?{type:"page",documentId:l,pageIndex:s}:{type:"global",documentId:l},handlers:i})}}}({documentId:t,pageIndex:n}),[h,m]=Se([]),[g,p]=Se(null),[f,v]=Se({}),y=De(o),b=Re(()=>s?s.forDocument(t):null,[s,t]),w=h.length>1;Me(()=>{if(b){const e=b.getState();return d(od(e,n)),m(rd(e)),b.onStateChange(e=>{d(od(e,n)),m(rd(e))})}},[b,n]),Me(()=>{if(!b)return;y.current!==o&&(b.invalidatePageAppearances(n),y.current=o);b.getPageAppearances(n,{scaleFactor:o,dpr:"undefined"!=typeof window?window.devicePixelRatio:1}).wait(e=>v(e),()=>v({}))},[b,n,o]);const x=Re(()=>({onPointerDown:(e,t)=>{t.target===t.currentTarget&&b&&(b.deselectAnnotation(),p(null))}}),[b]),C=ze((e,t)=>{if(e.stopPropagation(),b&&l){l.clear();"metaKey"in e&&(e.metaKey||e.ctrlKey)?b.toggleSelection(n,t.object.id):b.selectAnnotation(n,t.object.id),t.object.id!==g&&p(null)}},[b,l,g,n]);Me(()=>u(x,{documentId:t}),[u,x]);const k=Re(()=>c.filter(e=>h.includes(e.object.id)),[c,h]),I=Re(()=>!(k.length<2)&&k.every(e=>{const t=null==b?void 0:b.findToolForAnnotation(e.object),n=lu(null==t?void 0:t.interaction.isGroupDraggable,e.object,!0),o=lu(null==t?void 0:t.interaction.isDraggable,e.object,!0);return void 0!==(null==t?void 0:t.interaction.isGroupDraggable)?n:o}),[k,b]),S=Re(()=>!(k.length<2)&&k.every(e=>{const t=null==b?void 0:b.findToolForAnnotation(e.object),n=lu(null==t?void 0:t.interaction.isGroupResizable,e.object,!0),o=lu(null==t?void 0:t.interaction.isResizable,e.object,!0);return void 0!==(null==t?void 0:t.interaction.isGroupResizable)?n:o}),[k,b]),A=Re(()=>!(k.length<2)&&k.every(e=>{const t=null==b?void 0:b.findToolForAnnotation(e.object),n=lu(null==t?void 0:t.interaction.isGroupRotatable,e.object,!0),o=lu(null==t?void 0:t.interaction.isRotatable,e.object,!0);return void 0!==(null==t?void 0:t.interaction.isGroupRotatable)?n:o}),[k,b]),M=Re(()=>!(k.length<2)&&k.some(e=>{const t=null==b?void 0:b.findToolForAnnotation(e.object),n=lu(null==t?void 0:t.interaction.lockGroupAspectRatio,e.object,!1),o=lu(null==t?void 0:t.interaction.lockAspectRatio,e.object,!1);return void 0!==(null==t?void 0:t.interaction.lockGroupAspectRatio)?n:o}),[k,b]),P=Re(()=>{if(!b)return!1;const e=b.getSelectedAnnotations();return e.length>1&&e.every(e=>e.object.pageIndex===n)},[b,n,h]),D=ze(e=>{if(e.dictMode)return null;if(e.object.rotation&&e.object.unrotatedRect)return null;const t=f[e.object.id];return(null==t?void 0:t.normal)?t:null},[f]),R=Re(()=>{const t=e.annotationRenderers??[],n=new Set(t.map(e=>e.id));return[...t,...qh.filter(e=>!n.has(e.id))]},[e.annotationRenderers]),z=ze(e=>R.find(t=>t.matches(e.object))??null,[R]),T=Re(()=>({defaultSelect:C,selectAnnotation:(e,t)=>null==b?void 0:b.selectAnnotation(e,t),clearSelection:()=>null==l?void 0:l.clear(),allAnnotations:c,pageIndex:n}),[C,b,l,c,n]);return He(H,{children:[c.map(i=>{var r,s,l;const c=z(i);if(!c)return null;const d=null==b?void 0:b.findToolForAnnotation(i.object),u=h.includes(i.object.id),m=g===i.object.id,f=c.interactionDefaults,v=lu(null==d?void 0:d.interaction.isDraggable,i.object,(null==f?void 0:f.isDraggable)??!0),y=c.isDraggable?c.isDraggable(v,{isEditing:m}):v,x=(null==(r=null==d?void 0:d.behavior)?void 0:r.useAppearanceStream)??c.useAppearanceStream??!0,k=c.selectOverride?e=>c.selectOverride(e,i,T):e=>C(e,i);return He(Ih,{trackedAnnotation:i,isSelected:u,isEditing:m,isMultiSelected:w,isDraggable:y,isResizable:lu(null==d?void 0:d.interaction.isResizable,i.object,(null==f?void 0:f.isResizable)??!1),lockAspectRatio:lu(null==d?void 0:d.interaction.lockAspectRatio,i.object,(null==f?void 0:f.lockAspectRatio)??!1),isRotatable:lu(null==d?void 0:d.interaction.isRotatable,i.object,(null==f?void 0:f.isRotatable)??!1),vertexConfig:c.vertexConfig,selectionMenu:(null==(s=c.hideSelectionMenu)?void 0:s.call(c,i.object))?void 0:a,onSelect:k,onDoubleClick:c.onDoubleClick?e=>{e.stopPropagation(),c.onDoubleClick(i.object.id,p)}:void 0,zIndex:c.zIndex,style:(null==(l=c.containerStyle)?void 0:l.call(c,i.object))??{mixBlendMode:Dn(i.object.blendMode??zt.Normal)},appearance:x?D(i):void 0,...e,children:(e,{appearanceActive:r})=>c.render({annotation:i,currentObject:e,isSelected:u,isEditing:m,scale:o,pageIndex:n,documentId:t,onClick:k,appearanceActive:r})},i.object.id)}),P&&k.length>=2&&He(Mh,{documentId:t,pageIndex:n,scale:o,rotation:e.rotation,pageWidth:i,pageHeight:r,selectedAnnotations:k,isDraggable:I,isResizable:S,isRotatable:A,lockAspectRatio:M,resizeUI:e.resizeUI,rotationUI:e.rotationUI,selectionOutlineColor:e.selectionOutlineColor,selectionOutline:e.groupSelectionOutline??e.selectionOutline,groupSelectionMenu:e.groupSelectionMenu})]})}function Vh({documentId:e,pageIndex:t,scale:n}){var o,i,r,a,s,l,c,d,u,h,m,g;const{provides:p}=Ul(),{provides:f}=xh(),[v,y]=Se([]),[b,w]=Se(null),[x,C]=Se(null);if(Me(()=>{if(p)return p.forDocument(e).onSelectionChange(()=>{y(p.forDocument(e).getHighlightRectsForPage(t)),w(p.forDocument(e).getBoundingRectForPage(t))})},[p,e,t]),Me(()=>{if(f)return C(f.forDocument(e).getActiveTool()),f.forDocument(e).onActiveToolChange(e=>C(e))},[f,e]),!b)return null;if(!x||!x.defaults)return null;switch(x.defaults.type){case Ot.UNDERLINE:return He("div",{style:{mixBlendMode:Dn((null==(o=x.defaults)?void 0:o.blendMode)??zt.Normal),pointerEvents:"none",position:"absolute",inset:0},children:He(Uh,{strokeColor:null==(i=x.defaults)?void 0:i.strokeColor,opacity:null==(r=x.defaults)?void 0:r.opacity,segmentRects:v,scale:n})});case Ot.HIGHLIGHT:return He("div",{style:{mixBlendMode:Dn((null==(a=x.defaults)?void 0:a.blendMode)??zt.Multiply),pointerEvents:"none",position:"absolute",inset:0},children:He(Fh,{strokeColor:null==(s=x.defaults)?void 0:s.strokeColor,opacity:null==(l=x.defaults)?void 0:l.opacity,segmentRects:v,scale:n})});case Ot.STRIKEOUT:return He("div",{style:{mixBlendMode:Dn((null==(c=x.defaults)?void 0:c.blendMode)??zt.Normal),pointerEvents:"none",position:"absolute",inset:0},children:He(Hh,{strokeColor:null==(d=x.defaults)?void 0:d.strokeColor,opacity:null==(u=x.defaults)?void 0:u.opacity,segmentRects:v,scale:n})});case Ot.SQUIGGLY:return He("div",{style:{mixBlendMode:Dn((null==(h=x.defaults)?void 0:h.blendMode)??zt.Normal),pointerEvents:"none",position:"absolute",inset:0},children:He(Wh,{strokeColor:null==(m=x.defaults)?void 0:m.strokeColor,opacity:null==(g=x.defaults)?void 0:g.opacity,segmentRects:v,scale:n})});case Ot.CARET:default:return null}}function Kh({preview:e,scale:t}){const{bounds:n}=e,o={position:"absolute",left:n.origin.x*t,top:n.origin.y*t,width:n.size.width*t,height:n.size.height*t,pointerEvents:"none",zIndex:10};return e.type===Ot.CIRCLE?He("div",{style:o,children:He(zh,{isSelected:!1,scale:t,...e.data})}):e.type===Ot.SQUARE?He("div",{style:o,children:He(Rh,{isSelected:!1,scale:t,...e.data})}):e.type===Ot.POLYGON?He("div",{style:o,children:He(_h,{isSelected:!1,scale:t,...e.data})}):e.type===Ot.POLYLINE?He("div",{style:o,children:He(Eh,{isSelected:!1,scale:t,...e.data})}):e.type===Ot.LINE?He("div",{style:o,children:He(Th,{isSelected:!1,scale:t,...e.data})}):e.type===Ot.INK?He("div",{style:o,children:He(Dh,{isSelected:!1,scale:t,...e.data})}):e.type===Ot.FREETEXT?He("div",{style:o,children:He("div",{style:{width:"100%",height:"100%",border:`1px dashed ${e.data.fontColor||"#000000"}`,backgroundColor:"transparent"}})}):null}function Zh({documentId:e,pageIndex:t,scale:n}){const{plugin:o}=wh(),[i,r]=Se(new Map),a=De(null),s=De(null),l=Re(()=>({requestFile:({accept:e,onFile:t})=>{if(!a.current)return;const n=a.current;n.accept=e,n.onchange=e=>{var o;const i=null==(o=e.target.files)?void 0:o[0];i&&(t(i),n.value="")},n.click()},processImage:({source:e,maxWidth:t,maxHeight:n,onComplete:o})=>{const i=s.current;if(!i||!i.getContext)return;const r=i.getContext("2d");if(!r)return;const a=new Image;a.crossOrigin="Anonymous",a.onload=()=>{let{naturalWidth:s,naturalHeight:l}=a;const c=t?t/s:1,d=n?n/l:1,u=Math.min(c,d,1),h=s*u,m=l*u;i.width=h,i.height=m,r.drawImage(a,0,0,h,m);const g=r.getImageData(0,0,h,m);"string"!=typeof e&&URL.revokeObjectURL(a.src),o({imageData:g,width:h,height:m})},a.src="string"==typeof e?e:URL.createObjectURL(e)}}),[]);return Me(()=>{if(o)return o.registerPageHandlers(e,t,n,{services:l,onPreview:(e,t)=>{r(n=>{const o=new Map(n);return t?o.set(e,t):o.delete(e),o})}})},[e,t,n,o,l]),He(H,{children:[He("input",{ref:a,type:"file",style:{display:"none"}}),He("canvas",{ref:s,style:{display:"none"}}),Array.from(i.entries()).map(([e,t])=>He(Kh,{preview:t,scale:n},e))]})}function Yh({style:e,documentId:t,pageIndex:n,scale:o,rotation:i,selectionMenu:r,groupSelectionMenu:a,resizeUI:s,vertexUI:l,rotationUI:c,selectionOutlineColor:d,selectionOutline:u,groupSelectionOutline:h,customAnnotationRenderer:m,annotationRenderers:g,...p}){var f,v,y,b;const w=jo(t),x=null==(v=null==(f=null==w?void 0:w.document)?void 0:f.pages)?void 0:v[n],C=(null==(y=null==x?void 0:x.size)?void 0:y.width)??0,k=(null==(b=null==x?void 0:x.size)?void 0:b.height)??0,I=Te(bh),S=Re(()=>{const e=[...I];for(const t of g??[]){const n=e.findIndex(e=>e.id===t.id);n>=0?e[n]=t:e.push(t)}return e},[I,g]),A=Re(()=>void 0!==o?o:(null==w?void 0:w.scale)??1,[o,null==w?void 0:w.scale]);return He("div",{style:{...e},...p,children:[He(Gh,{documentId:t,selectionMenu:r,groupSelectionMenu:a,pageIndex:n,scale:A,rotation:Re(()=>{if(void 0!==i)return i;return(((null==x?void 0:x.rotation)??0)+((null==w?void 0:w.rotation)??0))%4},[i,null==x?void 0:x.rotation,null==w?void 0:w.rotation]),pageWidth:C,pageHeight:k,resizeUI:s,vertexUI:l,rotationUI:c,selectionOutlineColor:d,selectionOutline:u,groupSelectionOutline:h,customAnnotationRenderer:m,annotationRenderers:S}),He(Vh,{documentId:t,pageIndex:n,scale:A}),He(Zh,{documentId:t,pageIndex:n,scale:A})]})}const Xh=To(gu).addWrapper(function({children:e}){const[t,n]=Se([]),o=ze(e=>(n(t=>{const n=new Set(e.map(e=>e.id));return[...t.filter(e=>!n.has(e.id)),...e]}),()=>n(t=>t.filter(t=>!e.some(e=>e.id===t.id)))),[]);return He(yh.Provider,{value:o,children:He(bh.Provider,{value:t,children:e})})}).build(),Qh="print",Jh={id:Qh,name:"Print Plugin",version:"1.0.0",provides:["print"],requires:[],optional:[],defaultConfig:{}},em=class extends bo{constructor(e,t,n){super(e,t),this.printReady$=Po()}buildCapability(){return{print:e=>this.print(e),forDocument:e=>this.createPrintScope(e)}}createPrintScope(e){return{print:t=>this.print(t,e)}}print(e,t){const n=t??this.getActiveDocumentId();if(!this.checkPermission(n,Qt.Print))return this.logger.debug("PrintPlugin","Print",`Cannot print: document ${n} lacks Print permission`),nn.reject({code:tn.Security,message:"Document lacks Print permission"});const o=e??{},i=new Ct;i.progress({stage:"preparing",message:"Preparing document..."});return this.preparePrintDocument(o,n).wait(e=>{i.progress({stage:"document-ready",message:"Document prepared successfully"}),this.printReady$.emit({documentId:n,options:o,buffer:e,task:i})},e=>i.fail(e)),i}preparePrintDocument(e,t){const n=this.coreState.core.documents[t];return(null==n?void 0:n.document)?this.engine.preparePrintDocument(n.document,e):nn.reject({code:tn.DocNotOpen,message:`Document ${t} not found`})}onPrintRequest(e){return this.printReady$.on(e)}async initialize(e){this.logger.info("PrintPlugin","Initialize","Print plugin initialized")}async destroy(){this.printReady$.clear(),await super.destroy()}};em.id="print";let tm=em;const nm=()=>Oo(tm.id);const om=To({manifest:Jh,create:(e,t)=>new tm(Qh,e,t),reducer:()=>{},initialState:{}}).addUtility(function(){const{provides:e}=nm(),{plugin:t}=Lo(tm.id),n=De(null),o=De(null);return Me(()=>{if(!e||!t)return;const i=t.onPrintRequest(({buffer:e,task:t})=>{const i=n.current;if(!i)return;o.current&&(URL.revokeObjectURL(o.current),o.current=null);const r=URL.createObjectURL(new Blob([e],{type:"application/pdf"}));o.current=r,i.onload=()=>{var n,o;i.src===r&&(t.progress({stage:"iframe-ready",message:"Ready to print"}),null==(n=i.contentWindow)||n.focus(),null==(o=i.contentWindow)||o.print(),t.progress({stage:"printing",message:"Print dialog opened"}),t.resolve(e))},i.src=r});return()=>{i(),o.current&&URL.revokeObjectURL(o.current)}},[e,t]),He("iframe",{ref:n,style:{position:"absolute",display:"none"},title:"Print Document",src:"about:blank"})}).build(),im="fullscreen",rm={id:im,name:"Fullscreen Plugin",version:"1.0.0",provides:["fullscreen"],requires:[],optional:[],defaultConfig:{}},am="SET_FULLSCREEN";const sm=class extends bo{constructor(e,t,n){super(e,t),this.onStateChange$=Do(),this.fullscreenRequest$=Po(),this.config=n}async initialize(e){}buildCapability(){return{isFullscreen:()=>this.state.isFullscreen,enableFullscreen:e=>this.enableFullscreen(e),exitFullscreen:()=>this.exitFullscreen(),toggleFullscreen:e=>this.toggleFullscreen(e),onRequest:this.fullscreenRequest$.on,onStateChange:this.onStateChange$.on}}getTargetSelector(){return this.currentTargetElement??this.config.targetElement}toggleFullscreen(e){this.state.isFullscreen?this.exitFullscreen():this.enableFullscreen(e)}enableFullscreen(e){this.currentTargetElement=e??this.config.targetElement,this.fullscreenRequest$.emit({action:"enter",targetElement:this.currentTargetElement})}exitFullscreen(){this.fullscreenRequest$.emit({action:"exit"}),this.currentTargetElement=void 0}onStoreUpdated(e,t){this.onStateChange$.emit(t)}setFullscreenState(e){this.dispatch({type:am,payload:e})}async destroy(){this.fullscreenRequest$.clear(),super.destroy()}};sm.id="fullscreen";let lm=sm;const cm=()=>Lo(lm.id);async function dm(e,t,n){if("enter"===e.action){const o=function(e,t,n){if(!t||"enter"!==e.action)return t;let o=null;return n&&(o=t.querySelector(n),o||console.warn(`Fullscreen: Could not find element with selector "${n}" within the wrapper. Falling back to wrapper element.`)),o||(o=t),o}(e,t,n);o&&!document.fullscreenElement&&await o.requestFullscreen()}else document.fullscreenElement&&await document.exitFullscreen()}const um=To({manifest:rm,create:(e,t)=>new lm(im,e,t),reducer:(e,t)=>t.type===am?{...e,isFullscreen:t.payload}:e,initialState:{isFullscreen:!1}}).addWrapper(function({children:e,...t}){const{provides:n}=Oo(lm.id),{plugin:o}=cm(),{plugin:i}=cm(),r=De(null);return Me(()=>{if(!n||!o)return;return n.onRequest(async e=>{const t=o.getTargetSelector();await dm(e,r.current,t)})},[n,o]),Me(()=>{if(!i)return;const e=()=>i.setFullscreenState(!!document.fullscreenElement);return document.addEventListener("fullscreenchange",e),()=>document.removeEventListener("fullscreenchange",e)},[i]),He("div",{...t,style:{position:"relative",width:"100%",height:"100%",...t.style},ref:r,children:e})}).build(),hm="bookmark",mm={id:hm,name:"Bookmark Plugin",version:"1.0.0",provides:["bookmark"],requires:[],optional:[],defaultConfig:{}},gm=class extends bo{constructor(e,t){super(e,t)}async initialize(e){}buildCapability(){return{getBookmarks:()=>this.getBookmarks(),forDocument:e=>this.createBookmarkScope(e)}}createBookmarkScope(e){return{getBookmarks:()=>this.getBookmarks(e)}}getBookmarks(e){const t=e??this.getActiveDocumentId(),n=this.coreState.core.documents[t];if(!(null==n?void 0:n.document))throw new Error(`Document ${t} not loaded`);return this.engine.getBookmarks(n.document)}};gm.id="bookmark";let pm=gm;const fm={manifest:mm,create:e=>new pm(hm,e),reducer:()=>{},initialState:{}},vm=class extends bo{constructor(e,t,n){super(e,t),this.downloadRequest$=Po(),this.config=n}buildCapability(){return{saveAsCopy:()=>this.saveAsCopy(),download:()=>this.download(),forDocument:e=>this.createExportScope(e)}}createExportScope(e){return{saveAsCopy:()=>this.saveAsCopy(e),download:()=>this.download(e)}}download(e){const t=e??this.getActiveDocumentId();this.downloadRequest$.emit({documentId:t})}saveAsCopy(e){const t=e??this.getActiveDocumentId(),n=this.coreState.core.documents[t];return(null==n?void 0:n.document)?this.engine.saveAsCopy(n.document):nn.reject({code:tn.DocNotOpen,message:`Document ${t} not found`})}saveAsCopyAndGetBufferAndName(e){const t=new Ct,n=this.coreState.core.documents[e];return(null==n?void 0:n.document)?(this.saveAsCopy(e).wait(e=>{t.resolve({buffer:e,name:n.name??this.config.defaultFileName})},e=>t.fail(e)),t):nn.reject({code:tn.DocNotOpen,message:`Document ${e} not found`})}onRequest(e){return this.downloadRequest$.on(e)}async initialize(e){this.logger.info("ExportPlugin","Initialize","Export plugin initialized")}async destroy(){this.downloadRequest$.clear(),await super.destroy()}};vm.id="export";let ym=vm;const bm="export";const wm=To({manifest:{id:bm,name:"Export Plugin",version:"1.0.0",provides:["export"],requires:[],optional:[],defaultConfig:{defaultFileName:"document.pdf"}},create:(e,t)=>new ym(bm,e,t),reducer:()=>{},initialState:{}}).addUtility(function(){const{plugin:e}=Lo(ym.id),t=De(null);return Me(()=>{if(!e)return;return e.onRequest(n=>{const o=t.current;if(!o)return;e.saveAsCopyAndGetBufferAndName(n.documentId).wait(({buffer:e,name:t})=>{const n=URL.createObjectURL(new Blob([e]));o.href=n,o.download=t,o.click(),URL.revokeObjectURL(n)},Ln)})},[e]),He("a",{style:{display:"none"},ref:t})}).build(),xm="PAN/INIT_STATE",Cm="PAN/CLEANUP_STATE",km="PAN/SET_PAN_MODE";const Im=class extends bo{constructor(e,t,n){var o,i,r;super(e,t),this.panMode$=Do(),this.documentHandlers=new Map,this.config=n,this.interactionManager=null==(o=t.getPlugin(rh.id))?void 0:o.provides(),this.viewport=null==(i=t.getPlugin(ci.id))?void 0:i.provides(),this.interactionManager&&(this.interactionManager.registerMode({id:"panMode",scope:"global",exclusive:!1,cursor:"grab",wantsRawTouch:!1}),null==(r=this.interactionManager)||r.onModeChange(e=>{const t="panMode"===e.activeMode,n=this.getDocumentState(e.documentId);n&&n.isPanMode!==t&&this.dispatch(function(e,t){return{type:km,payload:{documentId:e,isPanMode:t}}}(e.documentId,t))}))}onDocumentLoadingStarted(e){this.dispatch(function(e,t){return{type:xm,payload:{documentId:e,state:t}}}(e,{isPanMode:!1})),this.registerPanHandlersForDocument(e),"always"===this.config.defaultMode&&this.makePanDefault(!0),this.logger.debug("PanPlugin","DocumentOpened",`Initialized pan state for document: ${e}`)}onDocumentClosed(e){const t=this.documentHandlers.get(e);t&&(t(),this.documentHandlers.delete(e)),this.dispatch(function(e){return{type:Cm,payload:e}}(e)),this.logger.debug("PanPlugin","DocumentClosed",`Cleaned up pan state for document: ${e}`)}buildCapability(){return{enablePan:()=>this.enablePan(),disablePan:()=>this.disablePan(),togglePan:()=>this.togglePan(),makePanDefault:e=>this.makePanDefault(e),isPanMode:()=>this.isPanMode(),forDocument:e=>this.createPanScope(e),onPanModeChange:this.panMode$.on}}createPanScope(e){return{enablePan:()=>this.enablePan(e),disablePan:()=>this.disablePan(e),togglePan:()=>this.togglePan(e),isPanMode:()=>this.isPanMode(e),onPanModeChange:t=>this.panMode$.on(n=>{n.documentId===e&&t(n.isPanMode)})}}getDocumentState(e){const t=e??this.getActiveDocumentId();return this.state.documents[t]??null}getDocumentStateOrThrow(e){const t=this.getDocumentState(e);if(!t)throw new Error(`Pan state not found for document: ${e??"active"}`);return t}enablePan(e){const t=e??this.getActiveDocumentId();this.interactionManager.forDocument(t).activate("panMode")}disablePan(e){const t=e??this.getActiveDocumentId();this.interactionManager.forDocument(t).activateDefaultMode()}togglePan(e){const t=e??this.getActiveDocumentId(),n=this.interactionManager.forDocument(t);"panMode"===n.getActiveMode()?n.activateDefaultMode():n.activate("panMode")}makePanDefault(e=!0){this.interactionManager&&(this.interactionManager.setDefaultMode("panMode"),e&&this.interactionManager.activateDefaultMode())}isPanMode(e){return this.getDocumentStateOrThrow(e).isPanMode}registerPanHandlersForDocument(e){if(!this.interactionManager||!this.viewport)return;let t=null;const n=this.interactionManager.forDocument(e),o=this.viewport.forDocument(e),i={onMouseDown:(e,i)=>{const r=o.getMetrics();t={startX:i.clientX,startY:i.clientY,startLeft:r.scrollLeft,startTop:r.scrollTop},n.setCursor("panMode","grabbing",10)},onMouseMove:(e,n)=>{if(!t)return;const i=n.clientX-t.startX,r=n.clientY-t.startY;o.scrollTo({x:t.startLeft-i,y:t.startTop-r})},onMouseUp:()=>{t&&(t=null,n.removeCursor("panMode"))},onMouseLeave:()=>{t&&(t=null,n.removeCursor("panMode"))},onMouseCancel:()=>{t&&(t=null,n.removeCursor("panMode"))}},r=this.interactionManager.registerHandlers({documentId:e,modeId:"panMode",handlers:i});this.documentHandlers.set(e,r)}onStoreUpdated(e,t){for(const n in t.documents){const o=e.documents[n],i=t.documents[n];(null==o?void 0:o.isPanMode)!==i.isPanMode&&(this.panMode$.emit({documentId:n,isPanMode:i.isPanMode}),this.logger.debug("PanPlugin","PanModeChanged",`Pan mode changed for document ${n}: ${(null==o?void 0:o.isPanMode)??!1} -> ${i.isPanMode}`))}}async initialize(e){this.logger.info("PanPlugin","Initialize","Pan plugin initialized")}async destroy(){this.documentHandlers.forEach(e=>e()),this.documentHandlers.clear(),this.panMode$.clear(),await super.destroy()}};Im.id="pan";let Sm=Im;const Am={documents:{},activeDocumentId:null},Mm=To({manifest:{id:"pan",name:"Pan Plugin",version:"1.0.0",provides:["pan"],requires:["interaction-manager","viewport"],optional:[],defaultConfig:{defaultMode:"mobile"}},create:(e,t)=>new Sm("pan",e,t),reducer:(e=Am,t)=>{switch(t.type){case xm:{const{documentId:n,state:o}=t.payload;return{...e,documents:{...e.documents,[n]:o},activeDocumentId:e.activeDocumentId??n}}case Cm:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i,activeDocumentId:e.activeDocumentId===n?null:e.activeDocumentId}}case"PAN/SET_ACTIVE_DOCUMENT":return{...e,activeDocumentId:t.payload};case km:{const{documentId:n,isPanMode:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,isPanMode:o}}}:e}default:return e}},initialState:Am}).addUtility(()=>{const{provides:e}=Oo(Sm.id),{plugin:t}=Lo(Sm.id);return Me(()=>{var n;if(!e||!t)return;const o=(null==(n=t.config)?void 0:n.defaultMode)??"never",i="undefined"!=typeof window&&("ontouchstart"in window||navigator.maxTouchPoints>0);"mobile"===o&&i&&e.makePanDefault()},[e,t]),null}).build(),Pm="capture",Dm={id:Pm,name:"Capture Plugin",version:"1.0.0",provides:["capture"],requires:["render"],optional:["interaction-manager"],defaultConfig:{scale:1,imageType:"image/png",withAnnotations:!1}};const Rm="CAPTURE/INIT_STATE",zm="CAPTURE/CLEANUP_STATE",Tm="CAPTURE/SET_MARQUEE_CAPTURE_ACTIVE";const Em={isMarqueeCaptureActive:!1},_m={documents:{},activeDocumentId:null},Nm=class extends bo{constructor(e,t,n){var o;super(e,t),this.captureArea$=Po(),this.state$=Do(),this.config=n,this.renderCapability=this.registry.getPlugin("render").provides(),this.interactionManagerCapability=null==(o=this.registry.getPlugin("interaction-manager"))?void 0:o.provides(),this.interactionManagerCapability&&(this.interactionManagerCapability.registerMode({id:"marqueeCapture",scope:"page",exclusive:!0,cursor:"crosshair"}),this.interactionManagerCapability.onModeChange(e=>{const t="marqueeCapture"===e.activeMode,n=this.getDocumentState(e.documentId);var o;n&&n.isMarqueeCaptureActive!==t&&this.dispatch((o=e.documentId,{type:Tm,payload:{documentId:o,isActive:t}}))}))}onDocumentLoadingStarted(e){const t={...Em};this.dispatch(function(e,t){return{type:Rm,payload:{documentId:e,state:t}}}(e,t)),this.logger.debug("CapturePlugin","DocumentOpened",`Initialized capture state for document: ${e}`)}onDocumentClosed(e){this.dispatch(function(e){return{type:zm,payload:e}}(e)),this.logger.debug("CapturePlugin","DocumentClosed",`Cleaned up capture state for document: ${e}`)}async initialize(e){}buildCapability(){return{captureArea:(e,t)=>this.captureArea(e,t),enableMarqueeCapture:()=>this.enableMarqueeCapture(),disableMarqueeCapture:()=>this.disableMarqueeCapture(),toggleMarqueeCapture:()=>this.toggleMarqueeCapture(),isMarqueeCaptureActive:()=>this.isMarqueeCaptureActive(),getState:()=>this.getDocumentStateOrThrow(),forDocument:e=>this.createCaptureScope(e),registerMarqueeOnPage:e=>this.registerMarqueeOnPage(e),onCaptureArea:this.captureArea$.on,onStateChange:this.state$.on}}createCaptureScope(e){return{captureArea:(t,n)=>this.captureArea(t,n,e),enableMarqueeCapture:()=>this.enableMarqueeCapture(e),disableMarqueeCapture:()=>this.disableMarqueeCapture(e),toggleMarqueeCapture:()=>this.toggleMarqueeCapture(e),isMarqueeCaptureActive:()=>this.isMarqueeCaptureActive(e),getState:()=>this.getDocumentStateOrThrow(e),onCaptureArea:t=>this.captureArea$.on(n=>{n.documentId===e&&t(n)}),onStateChange:t=>this.state$.on(n=>{n.documentId===e&&t(n.state)})}}getDocumentState(e){const t=e??this.getActiveDocumentId();return this.state.documents[t]??null}getDocumentStateOrThrow(e){const t=this.getDocumentState(e);if(!t)throw new Error(`Capture state not found for document: ${e??"active"}`);return t}registerMarqueeOnPage(e){if(!this.interactionManagerCapability)return this.logger.warn("CapturePlugin","MissingDependency","Interaction manager plugin not loaded, marquee capture disabled"),()=>{};const t=this.coreState.core.documents[e.documentId];if(!t||!t.document)return this.logger.warn("CapturePlugin","DocumentNotFound","Document not found"),()=>{};const n=t.document.pages[e.pageIndex];if(!n)return this.logger.warn("CapturePlugin","PageNotFound",`Page ${e.pageIndex} not found`),()=>{};const o=function(e){const{pageSize:t,scale:n,minDragPx:o=5,onPreview:i,onCommit:r}=e;let a=null,s=null;return{onPointerDown:(e,t)=>{var n;a=e,s={origin:{x:e.x,y:e.y},size:{width:0,height:0}},null==i||i(s),null==(n=t.setPointerCapture)||n.call(t)},onPointerMove:e=>{if(!a)return;const n=ko(e.x,0,t.width),o=ko(e.y,0,t.height);s={origin:{x:Math.min(a.x,n),y:Math.min(a.y,o)},size:{width:Math.abs(n-a.x),height:Math.abs(o-a.y)}},null==i||i(s)},onPointerUp:(e,t)=>{var l;s&&Math.max(s.size.width,s.size.height)*n>o&&(null==r||r(s)),a=null,s=null,null==i||i(null),null==(l=t.releasePointerCapture)||l.call(t)},onPointerCancel:(e,t)=>{var n;a=null,s=null,null==i||i(null),null==(n=t.releasePointerCapture)||n.call(t)}}}({pageSize:n.size,scale:e.scale,onPreview:e.callback.onPreview,onCommit:t=>{var n,o;this.captureArea(e.pageIndex,t,e.documentId),null==(o=(n=e.callback).onCommit)||o.call(n,t)}});return this.interactionManagerCapability.registerHandlers({documentId:e.documentId,modeId:"marqueeCapture",handlers:o,pageIndex:e.pageIndex})}captureArea(e,t,n){const o=n??this.getActiveDocumentId();this.disableMarqueeCapture(o);this.renderCapability.forDocument(o).renderPageRect({pageIndex:e,rect:t,options:{imageType:this.config.imageType,scaleFactor:this.config.scale,withAnnotations:this.config.withAnnotations||!1}}).wait(n=>{this.captureArea$.emit({documentId:o,pageIndex:e,rect:t,blob:n,imageType:this.config.imageType||"image/png",scale:this.config.scale||1,withAnnotations:this.config.withAnnotations||!1})},Ln)}enableMarqueeCapture(e){var t;const n=e??this.getActiveDocumentId();null==(t=this.interactionManagerCapability)||t.forDocument(n).activate("marqueeCapture")}disableMarqueeCapture(e){var t;const n=e??this.getActiveDocumentId();null==(t=this.interactionManagerCapability)||t.forDocument(n).activateDefaultMode()}toggleMarqueeCapture(e){var t;const n=e??this.getActiveDocumentId(),o=null==(t=this.interactionManagerCapability)?void 0:t.forDocument(n);"marqueeCapture"===(null==o?void 0:o.getActiveMode())?o.activateDefaultMode():null==o||o.activate("marqueeCapture")}isMarqueeCaptureActive(e){var t;const n=e??this.getActiveDocumentId();return"marqueeCapture"===(null==(t=this.interactionManagerCapability)?void 0:t.forDocument(n).getActiveMode())}onStoreUpdated(e,t){for(const n in t.documents){const o=e.documents[n],i=t.documents[n];o&&i&&o.isMarqueeCaptureActive!==i.isMarqueeCaptureActive&&this.state$.emit({documentId:n,state:i})}}async destroy(){this.captureArea$.clear(),this.state$.clear(),super.destroy()}};Nm.id="capture";let Lm=Nm;const Om={manifest:Dm,create:(e,t)=>new Lm(Pm,e,t),reducer:(e=_m,t)=>{switch(t.type){case Rm:{const{documentId:n,state:o}=t.payload;return{...e,documents:{...e.documents,[n]:o},activeDocumentId:e.activeDocumentId??n}}case zm:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i,activeDocumentId:e.activeDocumentId===n?null:e.activeDocumentId}}case"CAPTURE/SET_ACTIVE_DOCUMENT":return{...e,activeDocumentId:t.payload};case Tm:{const{documentId:n,isActive:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,isMarqueeCaptureActive:o}}}:e}default:return e}},initialState:_m},$m=()=>Oo(Lm.id),jm=({documentId:e,pageIndex:t,scale:n,className:o,stroke:i="rgba(33,150,243,0.8)",fill:r="rgba(33,150,243,0.15)"})=>{const{provides:a}=$m(),s=jo(e),[l,c]=Se(null),d=Re(()=>void 0!==n?n:(null==s?void 0:s.scale)??1,[n,null==s?void 0:s.scale]);return Me(()=>{if(a)return a.registerMarqueeOnPage({documentId:e,pageIndex:t,scale:d,callback:{onPreview:c}})},[a,e,t,d]),l?He("div",{style:{position:"absolute",pointerEvents:"none",left:l.origin.x*d,top:l.origin.y*d,width:l.size.width*d,height:l.size.height*d,border:`1px solid ${i}`,background:r,boxSizing:"border-box"},className:o}):null},Fm="history",Um={id:Fm,name:"History Plugin",version:"1.0.0",provides:["history"],requires:[],optional:[],defaultConfig:{}},Hm="HISTORY/INIT_STATE",Wm="HISTORY/CLEANUP_STATE",Bm="HISTORY/SET_DOCUMENT_STATE",qm=class extends bo{constructor(e,t){super(e,t),this.documentHistories=new Map,this.historyChange$=Po()}async initialize(e){this.logger.info("HistoryPlugin","Initialize","History plugin initialized")}onDocumentLoadingStarted(e){this.dispatch((e=>({type:Hm,payload:{documentId:e}}))(e)),this.documentHistories.set(e,{topicHistories:new Map,globalTimeline:[],globalIndex:-1}),this.logger.debug("HistoryPlugin","DocumentOpened",`Initialized history state for document: ${e}`)}onDocumentClosed(e){this.dispatch((e=>({type:Wm,payload:{documentId:e}}))(e)),this.documentHistories.delete(e),this.logger.debug("HistoryPlugin","DocumentClosed",`Cleaned up history state for document: ${e}`)}getDocumentHistoryData(e){const t=e??this.getActiveDocumentId(),n=this.documentHistories.get(t);if(!n)throw new Error(`History data not found for document: ${t}`);return n}getDocumentHistoryState(e){const t=this.documentHistories.get(e);if(!t)throw new Error(`History data not found for document: ${e}`);const n={};return Array.from(t.topicHistories.entries()).forEach(([e,t])=>{n[e]={canUndo:t.currentIndex>-1,canRedo:t.currentIndex-1,canRedo:t.globalIndex({type:Bm,payload:{documentId:e,state:t}}))(e,n)),this.historyChange$.emit({documentId:e,topic:t,state:n})}register(e,t,n){const o=this.getDocumentHistoryData(n);o.topicHistories.has(t)||o.topicHistories.set(t,{commands:[],currentIndex:-1});const i=o.topicHistories.get(t);i.commands.splice(i.currentIndex+1),i.commands.push(e),i.currentIndex++;const r={command:e,topic:t};o.globalTimeline.splice(o.globalIndex+1),o.globalTimeline.push(r),o.globalIndex++,e.execute(),this.emitHistoryChange(n,t)}undo(e,t){const n=this.getDocumentHistoryData(t);let o;if(e){const t=n.topicHistories.get(e);t&&t.currentIndex>-1&&(t.commands[t.currentIndex].undo(),t.currentIndex--,o=e)}else if(n.globalIndex>-1){const e=n.globalTimeline[n.globalIndex];e.command.undo(),n.topicHistories.get(e.topic).currentIndex--,n.globalIndex--,o=e.topic}o&&this.emitHistoryChange(t,o)}redo(e,t){const n=this.getDocumentHistoryData(t);let o;if(e){const t=n.topicHistories.get(e);t&&t.currentIndex-1}return n.globalIndex>-1}canRedo(e,t){const n=this.getDocumentHistoryData(t);if(e){const t=n.topicHistories.get(e);return!!t&&t.currentIndexe(t.metadata),a=t?[t]:Array.from(o.topicHistories.keys());for(const e of a){const t=o.topicHistories.get(e);if(!t)continue;const n=[];let a=0;for(let e=0;e0&&(this.emitHistoryChange(n,t),this.logger.debug("HistoryPlugin","PurgeByMetadata",`Purged ${i} history entries for document: ${n}${t?`, topic: ${t}`:""}`)),i}createHistoryScope(e){return{register:(t,n)=>this.register(t,n,e),undo:t=>this.undo(t,e),redo:t=>this.redo(t,e),canUndo:t=>this.canUndo(t,e),canRedo:t=>this.canRedo(t,e),getHistoryState:()=>this.getDocumentHistoryState(e),onHistoryChange:t=>this.historyChange$.on(n=>{n.documentId===e&&t(n.topic)}),purgeByMetadata:(t,n)=>this.purgeByMetadata(t,n,e)}}buildCapability(){return{register:(e,t)=>{const n=this.getActiveDocumentId();this.register(e,t,n)},undo:e=>{const t=this.getActiveDocumentId();this.undo(e,t)},redo:e=>{const t=this.getActiveDocumentId();this.redo(e,t)},canUndo:e=>{const t=this.getActiveDocumentId();return this.canUndo(e,t)},canRedo:e=>{const t=this.getActiveDocumentId();return this.canRedo(e,t)},getHistoryState:()=>{const e=this.getActiveDocumentId();return this.getDocumentHistoryState(e)},forDocument:e=>this.createHistoryScope(e),onHistoryChange:this.historyChange$.on,purgeByMetadata:(e,t)=>{const n=this.getActiveDocumentId();return this.purgeByMetadata(e,t,n)}}}async destroy(){this.historyChange$.clear(),this.documentHistories.clear(),super.destroy()}};qm.id="history";let Gm=qm;const Vm={global:{canUndo:!1,canRedo:!1},topics:{}},Km={documents:{},activeDocumentId:null},Zm={manifest:Um,create:e=>new Gm(Fm,e),reducer:(e=Km,t)=>{switch(t.type){case Hm:{const{documentId:n}=t.payload;return{...e,documents:{...e.documents,[n]:{...Vm}}}}case Wm:{const{documentId:n}=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i,activeDocumentId:e.activeDocumentId===n?null:e.activeDocumentId}}case Bm:{const{documentId:n,state:o}=t.payload;return e.documents[n]?{...e,documents:{...e.documents,[n]:o}}:e}case"HISTORY/SET_ACTIVE_DOCUMENT":return{...e,activeDocumentId:t.payload};default:return e}},initialState:Km};var Ym=(e=>(e.Redact="redact",e.MarqueeRedact="marqueeRedact",e.RedactSelection="redactSelection",e))(Ym||{});const Xm="REDACTION/INIT_STATE",Qm="REDACTION/CLEANUP_STATE",Jm="START_REDACTION",eg="END_REDACTION",tg="ADD_PENDING",ng="REMOVE_PENDING",og="UPDATE_PENDING",ig="CLEAR_PENDING",rg="SELECT_PENDING",ag="DESELECT_PENDING";const sg=(e,t)=>({type:tg,payload:{documentId:e,items:t}}),lg=(e,t,n)=>({type:ng,payload:{documentId:e,page:t,id:n}}),cg=e=>({type:ig,payload:e}),dg=(e,t,n,o)=>({type:og,payload:{documentId:e,page:t,id:n,patch:o}}),ug=(e,t,n)=>({type:rg,payload:{documentId:e,page:t,id:n}}),hg=e=>({type:ag,payload:e}),mg=e=>Object.values(e).reduce((e,t)=>e+t.length,0),gg={isRedacting:!1,activeType:null,pending:{},pendingCount:0,selected:null},pg={documents:{},activeDocumentId:null},fg={id:"redact",name:"Redact",matchScore:e=>e.type===Ot.REDACT?10:0,interaction:{mode:Ym.Redact,exclusive:!1,cursor:"crosshair",textSelection:!0,isDraggable:e=>{var t;return e.type!==Ot.REDACT||!(null==(t=e.segmentRects)?void 0:t.length)},isResizable:e=>{var t;return e.type!==Ot.REDACT||!(null==(t=e.segmentRects)?void 0:t.length)},isRotatable:!1,lockAspectRatio:!1,isGroupDraggable:!1,isGroupResizable:!1,isGroupRotatable:!1},defaults:{type:Ot.REDACT,color:"#000000",overlayColor:"#FFFFFF",strokeColor:"#E44234",opacity:1},behavior:{useAppearanceStream:!1}},vg=[fg],yg=class extends bo{constructor(e,t,n){var o,i,r,a;if(super(e,t),this.redactionSelection$=new Map,this.redactionMarquee$=new Map,this.pending$=Do(),this.selected$=Do(),this.state$=Do(),this.events$=Do(),this.documentUnsubscribers=new Map,this.config=n,this.selectionCapability=null==(o=this.registry.getPlugin("selection"))?void 0:o.provides(),this.interactionManagerCapability=null==(i=this.registry.getPlugin("interaction-manager"))?void 0:i.provides(),this.annotationCapability=null==(r=this.registry.getPlugin("annotation"))?void 0:r.provides(),this.historyCapability=null==(a=this.registry.getPlugin("history"))?void 0:a.provides(),this.config.useAnnotationMode?this.annotationCapability?this.useAnnotationMode=!0:(this.logger.warn("RedactionPlugin","ConfigError","useAnnotationMode is enabled but annotation plugin is not available. Falling back to legacy mode."),this.useAnnotationMode=!1):this.useAnnotationMode=!1,this.useAnnotationMode)for(const e of vg)this.annotationCapability.addTool(e);this.setupRedactionModes(),!this.useAnnotationMode&&this.annotationCapability&&this.logger.info("RedactionPlugin","LegacyMode","Using legacy redaction mode. Set useAnnotationMode: true in config to use annotation-based redactions."),this.setupModeChangeListener()}setupRedactionModes(){this.interactionManagerCapability&&(this.interactionManagerCapability.registerMode({id:Ym.Redact,scope:"page",exclusive:!1,cursor:"crosshair"}),this.interactionManagerCapability.registerMode({id:Ym.MarqueeRedact,scope:"page",exclusive:!1,cursor:"crosshair"}),this.interactionManagerCapability.registerMode({id:Ym.RedactSelection,scope:"page",exclusive:!1}))}setupModeChangeListener(){var e;null==(e=this.interactionManagerCapability)||e.onModeChange(e=>{const t=e.documentId;if(e.activeMode===Ym.Redact||e.activeMode===Ym.MarqueeRedact||e.activeMode===Ym.RedactSelection)this.dispatch(((e,t)=>({type:Jm,payload:{documentId:e,mode:t}}))(t,e.activeMode));else{const e=this.getDocumentState(t);(null==e?void 0:e.isRedacting)&&this.dispatch((e=>({type:eg,payload:e}))(t))}})}onDocumentLoadingStarted(e){this.dispatch(function(e,t){return{type:Xm,payload:{documentId:e,state:t}}}(e,{...gg})),this.redactionSelection$.set(e,Do()),this.redactionMarquee$.set(e,Do());const t=[];if(this.selectionCapability){const n=this.selectionCapability.forDocument(e),o=n.onSelectionChange(()=>{const t=this.getDocumentState(e);if(!(null==t?void 0:t.isRedacting))return;const o=n.getFormattedSelection(),i=this.redactionSelection$.get(e);null==i||i.emit(o)}),i=n.onEndSelection(()=>{const t=this.getDocumentState(e);if(!(null==t?void 0:t.isRedacting))return;if(!this.checkPermission(e,Qt.ModifyContents))return;const o=n.getFormattedSelection();if(!o.length)return;const i=n.getSelectedText(),r=this.redactionSelection$.get(e);null==r||r.emit([]),n.clear(),i.wait(t=>{const n=t.join(" ");this.createRedactionsFromSelection(e,o,n)},()=>{this.createRedactionsFromSelection(e,o)})}),r=n.onMarqueeChange(t=>{var n;const o=this.getDocumentState(e);(null==o?void 0:o.isRedacting)&&(null==(n=this.redactionMarquee$.get(e))||n.emit({pageIndex:t.pageIndex,rect:t.rect,modeId:t.modeId}))}),a=n.onMarqueeEnd(t=>{const n=this.getDocumentState(e);if((null==n?void 0:n.isRedacting)&&this.checkPermission(e,Qt.ModifyContents))if(this.useAnnotationMode)this.createRedactAnnotationFromArea(e,t.pageIndex,t.rect);else{const n=this.config.drawBlackBoxes?"#000000":"transparent",o={id:_n(),kind:"area",page:t.pageIndex,rect:t.rect,source:"legacy",markColor:"#FF0000",redactionColor:n};this.dispatch(sg(e,[o])),this.selectPending(t.pageIndex,o.id,e)}}),s=n.onEmptySpaceClick(()=>{this.deselectPending(e)});t.push(o,i,r,a,s)}if(this.useAnnotationMode&&this.annotationCapability){const n=this.annotationCapability.forDocument(e),o=n.onAnnotationEvent(t=>{var n;if("loaded"===t.type)return void this.syncFromAnnotationLoad(e);if((null==(n=t.annotation)?void 0:n.type)!==Ot.REDACT)return;const o=t.annotation;"create"===t.type?(this.syncFromAnnotationCreate(e,o),this.events$.emit({type:"add",documentId:e,items:[this.annotationToRedactionItem(o)]})):"update"===t.type?(this.logger.debug("RedactionPlugin","AnnotationUpdated",{documentId:e,redactAnno:o,patch:t.patch}),this.syncFromAnnotationUpdate(e,o,t.patch)):"delete"===t.type&&(this.syncFromAnnotationDelete(e,o),this.events$.emit({type:"remove",documentId:e,page:o.pageIndex,id:o.id}))}),i=n.onStateChange(()=>{this.syncSelectionFromAnnotation(e)});t.push(o,i)}this.documentUnsubscribers.set(e,t),this.logger.debug("RedactionPlugin","DocumentOpened",`Initialized redaction state for document: ${e}`)}onDocumentLoaded(e){var t,n,o;null==(t=this.selectionCapability)||t.enableForMode(Ym.Redact,{enableSelection:!0,showSelectionRects:!1,enableMarquee:!0,showMarqueeRects:!1},e),null==(n=this.selectionCapability)||n.enableForMode(Ym.MarqueeRedact,{enableSelection:!1,enableMarquee:!0,showMarqueeRects:!1},e),null==(o=this.selectionCapability)||o.enableForMode(Ym.RedactSelection,{enableSelection:!0,showSelectionRects:!1},e)}onDocumentClosed(e){this.dispatch(function(e){return{type:Qm,payload:e}}(e));const t=this.redactionSelection$.get(e);null==t||t.clear(),this.redactionSelection$.delete(e);const n=this.redactionMarquee$.get(e);null==n||n.clear(),this.redactionMarquee$.delete(e);const o=this.documentUnsubscribers.get(e);o&&(o.forEach(e=>e()),this.documentUnsubscribers.delete(e)),this.logger.debug("RedactionPlugin","DocumentClosed",`Cleaned up redaction state for document: ${e}`)}async initialize(e){this.logger.info("RedactionPlugin","Initialize","Redaction plugin initialized")}buildCapability(){return{queueCurrentSelectionAsPending:()=>this.queueCurrentSelectionAsPending(),enableRedact:()=>this.enableRedact(),toggleRedact:()=>this.toggleRedact(),isRedactActive:()=>this.isRedactActive(),endRedact:()=>this.endRedact(),enableMarqueeRedact:()=>this.enableMarqueeRedact(),toggleMarqueeRedact:()=>this.toggleMarqueeRedact(),isMarqueeRedactActive:()=>this.isMarqueeRedactActive(),enableRedactSelection:()=>this.enableRedactSelection(),toggleRedactSelection:()=>this.toggleRedactSelection(),isRedactSelectionActive:()=>this.isRedactSelectionActive(),addPending:e=>this.addPendingItems(e),removePending:(e,t)=>this.removePendingItem(e,t),clearPending:()=>this.clearPendingItems(),commitAllPending:()=>this.commitAllPending(),commitPending:(e,t)=>this.commitPendingOne(e,t),selectPending:(e,t)=>this.selectPending(e,t),getSelectedPending:()=>this.getSelectedPending(),deselectPending:()=>this.deselectPending(),getState:()=>this.getDocumentStateOrThrow(),forDocument:e=>this.createRedactionScope(e),onPendingChange:this.pending$.on,onSelectedChange:this.selected$.on,onRedactionEvent:this.events$.on,onStateChange:this.state$.on}}createRedactionScope(e){return{queueCurrentSelectionAsPending:()=>this.queueCurrentSelectionAsPending(e),enableRedact:()=>this.enableRedact(e),toggleRedact:()=>this.toggleRedact(e),isRedactActive:()=>this.isRedactActive(e),endRedact:()=>this.endRedact(e),enableMarqueeRedact:()=>this.enableMarqueeRedact(e),toggleMarqueeRedact:()=>this.toggleMarqueeRedact(e),isMarqueeRedactActive:()=>this.isMarqueeRedactActive(e),enableRedactSelection:()=>this.enableRedactSelection(e),toggleRedactSelection:()=>this.toggleRedactSelection(e),isRedactSelectionActive:()=>this.isRedactSelectionActive(e),addPending:t=>this.addPendingItems(t,e),removePending:(t,n)=>this.removePendingItem(t,n,e),clearPending:()=>this.clearPendingItems(e),commitAllPending:()=>this.commitAllPending(e),commitPending:(t,n)=>this.commitPendingOne(t,n,e),selectPending:(t,n)=>this.selectPending(t,n,e),getSelectedPending:()=>this.getSelectedPending(e),deselectPending:()=>this.deselectPending(e),getState:()=>this.getDocumentStateOrThrow(e),onPendingChange:t=>this.pending$.on(n=>{n.documentId===e&&t(n.pending)}),onSelectedChange:t=>this.selected$.on(n=>{n.documentId===e&&t(n.selected)}),onRedactionEvent:t=>this.events$.on(n=>{n.documentId===e&&t(n)}),onStateChange:t=>this.state$.on(n=>{n.documentId===e&&t(n.state)})}}getPendingFromAnnotations(e){if(!this.annotationCapability)return{};try{const t=this.annotationCapability.forDocument(e).getState(),n={};for(const e of Object.values(t.byUid))if(e.object.type===Ot.REDACT){const t=this.annotationToRedactionItem(e.object),o=e.object.pageIndex;(n[o]??(n[o]=[])).push(t)}return n}catch{return{}}}getDocumentState(e){const t=e??this.getActiveDocumentId();return this.state.documents[t]??null}getDocumentStateOrThrow(e){const t=this.getDocumentState(e);if(!t)throw new Error(`Redaction state not found for document: ${e??"active"}`);return t}syncFromAnnotationCreate(e,t){const n=this.annotationToRedactionItem(t);this.dispatch(sg(e,[n]))}syncFromAnnotationUpdate(e,t,n){if(!("rect"in n||"segmentRects"in n||"strokeColor"in n||"color"in n))return;const o={};n.rect&&(o.rect=n.rect),n.segmentRects&&(o.rects=n.segmentRects),n.strokeColor&&(o.markColor=n.strokeColor),n.color&&(o.redactionColor=n.color),this.logger.debug("RedactionPlugin","AnnotationUpdated",{documentId:e,annotation:t,patch:o}),this.dispatch(dg(e,t.pageIndex,t.id,o))}syncFromAnnotationDelete(e,t){this.dispatch(lg(e,t.pageIndex,t.id))}syncFromAnnotationLoad(e){const t=this.getPendingFromAnnotations(e);this.dispatch(cg(e));for(const[,n]of Object.entries(t))n.length>0&&this.dispatch(sg(e,n))}syncSelectionFromAnnotation(e){var t;const n=null==(t=this.annotationCapability)?void 0:t.forDocument(e).getState();if(!n)return;const o=n.selectedUids.map(e=>n.byUid[e]).find(e=>(null==e?void 0:e.object.type)===Ot.REDACT);if(o){const t=o.object;this.dispatch(ug(e,t.pageIndex,t.id))}else{const t=this.getDocumentState(e);(null==t?void 0:t.selected)&&this.dispatch(hg(e))}}addPendingItems(e,t){const n=t??this.getActiveDocumentId();if(this.checkPermission(n,Qt.ModifyContents)){if(this.useAnnotationMode){const t=this.annotationCapability.forDocument(n);for(const n of e){const e=this.redactionItemToAnnotation(n);t.createAnnotation(n.page,e)}if(e.length>0){const n=e[e.length-1];t.selectAnnotation(n.page,n.id)}}else this.dispatch(sg(n,e));this.events$.emit({type:"add",documentId:n,items:e})}else this.logger.debug("RedactionPlugin","AddPendingItems",`Cannot add redactions: document ${n} lacks ModifyContents permission`)}removePendingItem(e,t,n){var o;const i=n??this.getActiveDocumentId();this.useAnnotationMode?null==(o=this.annotationCapability)||o.forDocument(i).deleteAnnotation(e,t):this.dispatch(lg(i,e,t)),this.events$.emit({type:"remove",documentId:i,page:e,id:t})}clearPendingItems(e){var t;const n=e??this.getActiveDocumentId();if(this.useAnnotationMode){const e=this.getPendingFromAnnotations(n),o=null==(t=this.annotationCapability)?void 0:t.forDocument(n);for(const[t,n]of Object.entries(e)){const e=Number(t);for(const t of n)null==o||o.deleteAnnotation(e,t.id)}}else this.dispatch(cg(n));this.events$.emit({type:"clear",documentId:n})}selectPending(e,t,n){var o,i,r;const a=n??this.getActiveDocumentId();this.useAnnotationMode?null==(o=this.annotationCapability)||o.forDocument(a).selectAnnotation(e,t):(this.dispatch(ug(a,e,t)),null==(i=this.interactionManagerCapability)||i.claimPageActivity(a,"redaction-selection",e)),null==(r=this.selectionCapability)||r.forDocument(a).clear()}getSelectedPending(e){var t;const n=e??this.getActiveDocumentId();return(null==(t=this.getDocumentState(n))?void 0:t.selected)??null}deselectPending(e){var t,n;const o=e??this.getActiveDocumentId();this.useAnnotationMode?null==(t=this.annotationCapability)||t.forDocument(o).deselectAnnotation():(this.dispatch(hg(o)),null==(n=this.interactionManagerCapability)||n.releasePageActivity(o,"redaction-selection"))}enableRedactSelection(e){var t;const n=e??this.getActiveDocumentId();this.checkPermission(n,Qt.ModifyContents)?null==(t=this.interactionManagerCapability)||t.forDocument(n).activate(Ym.RedactSelection):this.logger.debug("RedactionPlugin","EnableRedactSelection",`Cannot enable redact selection: document ${n} lacks ModifyContents permission`)}toggleRedactSelection(e){var t;const n=e??this.getActiveDocumentId(),o=null==(t=this.interactionManagerCapability)?void 0:t.forDocument(n);if((null==o?void 0:o.getActiveMode())===Ym.RedactSelection)null==o||o.activateDefaultMode();else{if(!this.checkPermission(n,Qt.ModifyContents))return;null==o||o.activate(Ym.RedactSelection)}}isRedactSelectionActive(e){var t;const n=e??this.getActiveDocumentId(),o=null==(t=this.interactionManagerCapability)?void 0:t.forDocument(n).getActiveMode();return o===Ym.Redact||o===Ym.RedactSelection}enableMarqueeRedact(e){var t;const n=e??this.getActiveDocumentId();this.checkPermission(n,Qt.ModifyContents)?null==(t=this.interactionManagerCapability)||t.forDocument(n).activate(Ym.MarqueeRedact):this.logger.debug("RedactionPlugin","EnableMarqueeRedact",`Cannot enable marquee redact: document ${n} lacks ModifyContents permission`)}toggleMarqueeRedact(e){var t;const n=e??this.getActiveDocumentId(),o=null==(t=this.interactionManagerCapability)?void 0:t.forDocument(n);if((null==o?void 0:o.getActiveMode())===Ym.MarqueeRedact)null==o||o.activateDefaultMode();else{if(!this.checkPermission(n,Qt.ModifyContents))return;null==o||o.activate(Ym.MarqueeRedact)}}isMarqueeRedactActive(e){var t;const n=e??this.getActiveDocumentId(),o=null==(t=this.interactionManagerCapability)?void 0:t.forDocument(n).getActiveMode();return o===Ym.Redact||o===Ym.MarqueeRedact}enableRedact(e){var t;const n=e??this.getActiveDocumentId();this.checkPermission(n,Qt.ModifyContents)?null==(t=this.interactionManagerCapability)||t.forDocument(n).activate(Ym.Redact):this.logger.debug("RedactionPlugin","EnableRedact",`Cannot enable redact mode: document ${n} lacks ModifyContents permission`)}toggleRedact(e){var t;const n=e??this.getActiveDocumentId(),o=null==(t=this.interactionManagerCapability)?void 0:t.forDocument(n);if((null==o?void 0:o.getActiveMode())===Ym.Redact)null==o||o.activateDefaultMode();else{if(!this.checkPermission(n,Qt.ModifyContents))return;null==o||o.activate(Ym.Redact)}}isRedactActive(e){var t;const n=e??this.getActiveDocumentId();return(null==(t=this.interactionManagerCapability)?void 0:t.forDocument(n).getActiveMode())===Ym.Redact}endRedact(e){var t;const n=e??this.getActiveDocumentId();null==(t=this.interactionManagerCapability)||t.forDocument(n).activateDefaultMode()}onRedactionSelectionChange(e,t){const n=this.redactionSelection$.get(e);return(null==n?void 0:n.on(t))??(()=>{})}onRedactionMarqueeChange(e,t){const n=this.redactionMarquee$.get(e);return(null==n?void 0:n.on(t))??(()=>{})}getPreviewStrokeColor(){if(this.useAnnotationMode&&this.annotationCapability){const e=this.annotationCapability.getTool("redact");return(null==e?void 0:e.defaults.strokeColor)??"#FF0000"}return"#FF0000"}queueCurrentSelectionAsPending(e){const t=e??this.getActiveDocumentId();if(!this.selectionCapability)return nn.reject({code:tn.NotFound,message:"[RedactionPlugin] selection plugin required"});const n=this.coreState.core.documents[t];if(!(null==n?void 0:n.document))return nn.reject({code:tn.NotFound,message:"Document not found"});const o=this.selectionCapability.forDocument(t),i=o.getFormattedSelection();if(!i.length)return nn.resolve(!0);const r=o.getSelectedText(),a=this.redactionSelection$.get(t);null==a||a.emit([]),o.clear(),this.useAnnotationMode||this.enableRedactSelection(t);const s=new Ct;return r.wait(e=>{const n=e.join(" ");this.createRedactionsFromSelection(t,i,n),s.resolve(!0)},()=>{this.createRedactionsFromSelection(t,i),s.resolve(!0)}),s}commitPendingOne(e,t,n){const o=n??this.getActiveDocumentId();if(!this.checkPermission(o,Qt.ModifyContents))return this.logger.debug("RedactionPlugin","CommitPendingOne",`Cannot commit redaction: document ${o} lacks ModifyContents permission`),nn.reject({code:tn.Security,message:"Document lacks ModifyContents permission"});const i=this.coreState.core.documents[o];if(!(null==i?void 0:i.document))return nn.reject({code:tn.NotFound,message:"Document not found"});const r=i.document.pages[e];if(!r)return nn.reject({code:tn.NotFound,message:"Page not found"});if(this.useAnnotationMode)return this.logger.debug("RedactionPlugin","CommitPendingOne",`Applying redaction in annotation mode: page ${e}, id ${t}`),this.applyRedactionAnnotationMode(o,i.document,r,t);const a=this.getDocumentState(o);if(!a)return nn.reject({code:tn.NotFound,message:"Document state not found"});const s=(a.pending[e]??[]).find(e=>e.id===t);return s?this.commitPendingOneLegacy(o,i.document,r,e,s):(this.logger.debug("RedactionPlugin","CommitPendingOne",`No pending item found for page ${e}, id ${t}`),nn.resolve(!0))}commitPendingOneLegacy(e,t,n,o,i){const r="text"===i.kind?i.rects:[i.rect],a=new Ct;return this.engine.redactTextInRects(t,n,r,{drawBlackBoxes:this.config.drawBlackBoxes}).wait(()=>{this.dispatch(lg(e,o,i.id)),this.dispatchCoreAction(ro(e,[o])),this.events$.emit({type:"commit",documentId:e,success:!0}),a.resolve(!0)},t=>{this.events$.emit({type:"commit",documentId:e,success:!1,error:t.reason}),a.reject({code:tn.Unknown,message:"Failed to commit redactions"})}),a}applyRedactionAnnotationMode(e,t,n,o){var i;const r=new Ct,a=null==(i=this.annotationCapability)?void 0:i.forDocument(e).getAnnotationById(o);return this.logger.debug("RedactionPlugin","ApplyRedactionAnnotationMode",`Looking for annotation ${o}, found: ${!!a}, type: ${null==a?void 0:a.object.type}`),a&&a.object.type===Ot.REDACT?(this.logger.debug("RedactionPlugin","ApplyRedactionAnnotationMode",`Calling engine.applyRedaction for annotation ${o} on page ${n.index}`),this.engine.applyRedaction(t,n,a.object).wait(()=>{var t,i;this.logger.debug("RedactionPlugin","ApplyRedactionAnnotationMode",`Successfully applied redaction ${o} on page ${n.index}`),null==(t=this.annotationCapability)||t.forDocument(e).purgeAnnotation(n.index,o),this.dispatch(lg(e,n.index,o)),null==(i=this.historyCapability)||i.forDocument(e).purgeByMetadata(e=>{var t;return(null==(t=null==e?void 0:e.annotationIds)?void 0:t.includes(o))??!1},"annotations"),this.dispatchCoreAction(ro(e,[n.index])),this.events$.emit({type:"commit",documentId:e,success:!0}),r.resolve(!0)},t=>{var n;this.logger.error("RedactionPlugin","ApplyRedactionAnnotationMode",`Failed to apply redaction ${o}: ${(null==(n=t.reason)?void 0:n.message)??"Unknown error"}`),this.events$.emit({type:"commit",documentId:e,success:!1,error:t.reason}),r.reject({code:tn.Unknown,message:"Failed to apply redaction"})}),r):(this.logger.warn("RedactionPlugin","ApplyRedactionAnnotationMode",`Redaction annotation not found or wrong type: ${o}`),nn.reject({code:tn.NotFound,message:"Redaction annotation not found"}))}commitAllPending(e){const t=e??this.getActiveDocumentId();if(!this.checkPermission(t,Qt.ModifyContents))return this.logger.debug("RedactionPlugin","CommitAllPending",`Cannot commit redactions: document ${t} lacks ModifyContents permission`),nn.reject({code:tn.Security,message:"Document lacks ModifyContents permission"});const n=this.coreState.core.documents[t];if(!(null==n?void 0:n.document))return nn.reject({code:tn.NotFound,message:"Document not found"});const o=this.getDocumentState(t);return o?this.useAnnotationMode?this.applyAllRedactionsAnnotationMode(t,n.document):this.commitAllPendingLegacy(t,n.document,o):nn.reject({code:tn.NotFound,message:"Document state not found"})}commitAllPendingLegacy(e,t,n){const o=new Map;for(const[e,t]of Object.entries(n.pending)){const n=Number(e),i=o.get(n)??[];for(const e of t)"text"===e.kind?i.push(...e.rects):i.push(e.rect);o.set(n,i)}const i=Array.from(o.entries()).filter(([e,t])=>t.length>0).map(([e])=>e),r=[];for(const[e,n]of o){const o=t.pages[e];o&&(n.length&&r.push(this.engine.redactTextInRects(t,o,n,{drawBlackBoxes:this.config.drawBlackBoxes})))}const a=new Ct;return Ct.all(r).wait(()=>{this.dispatch(cg(e)),this.dispatchCoreAction(ro(e,i)),this.events$.emit({type:"commit",documentId:e,success:!0}),a.resolve(!0)},t=>{this.events$.emit({type:"commit",documentId:e,success:!1,error:t.reason}),a.reject({code:tn.Unknown,message:"Failed to commit redactions"})}),a}applyAllRedactionsAnnotationMode(e,t){const n=this.annotationCapability.forDocument(e).getState(),o=new Map;for(const e of Object.values(n.byUid))if(e.object.type===Ot.REDACT){const t=o.get(e.object.pageIndex)??[];t.push(e.object.id),o.set(e.object.pageIndex,t)}const i=Array.from(o.keys());if(0===i.length)return nn.resolve(!0);const r=[];for(const e of i){const n=t.pages[e];n&&r.push(this.engine.applyAllRedactions(t,n))}const a=new Ct;return Ct.all(r).wait(()=>{var t,n;const r=null==(t=this.annotationCapability)?void 0:t.forDocument(e),s=[];for(const[t,n]of o)for(const o of n)null==r||r.purgeAnnotation(t,o),this.dispatch(lg(e,t,o)),s.push(o);s.length>0&&(null==(n=this.historyCapability)||n.forDocument(e).purgeByMetadata(e=>{var t;return(null==(t=null==e?void 0:e.annotationIds)?void 0:t.some(e=>s.includes(e)))??!1},"annotations")),this.dispatchCoreAction(ro(e,i)),this.events$.emit({type:"commit",documentId:e,success:!0}),a.resolve(!0)},t=>{this.events$.emit({type:"commit",documentId:e,success:!1,error:t.reason}),a.reject({code:tn.Unknown,message:"Failed to apply redactions"})}),a}createRedactAnnotationsFromSelection(e,t,n){if(!this.annotationCapability)return[];const o=this.annotationCapability.forDocument(e),i=this.annotationCapability.getTool("redact"),r=null==i?void 0:i.defaults,a=[];for(const e of t){const i=_n();a.push(i);const s={...r,id:i,type:Ot.REDACT,pageIndex:e.pageIndex,rect:e.rect,segmentRects:e.segmentRects,...n?{custom:{text:n}}:{},created:new Date};o.createAnnotation(e.pageIndex,s),e===t[t.length-1]&&o.selectAnnotation(e.pageIndex,i)}if(n)for(let o=0;o({id:_n(),kind:"text",page:e.pageIndex,rect:e.rect,rects:e.segmentRects,source:"legacy",markColor:"#FF0000",redactionColor:o,text:n}));this.dispatch(sg(e,i)),i.length&&this.selectPending(i[i.length-1].page,i[i.length-1].id,e)}createRedactionsFromSelection(e,t,n){this.useAnnotationMode?this.createRedactAnnotationsFromSelection(e,t,n):this.createLegacyRedactionsFromSelection(e,t,n)}createRedactAnnotationFromArea(e,t,n){if(!this.annotationCapability)return;const o=this.annotationCapability.forDocument(e),i=this.annotationCapability.getTool("redact"),r=null==i?void 0:i.defaults,a=_n(),s={...r,id:a,type:Ot.REDACT,pageIndex:t,rect:n,segmentRects:[],created:new Date};o.createAnnotation(t,s),o.selectAnnotation(t,a)}redactionItemToAnnotation(e){var t;const n=null==(t=this.annotationCapability)?void 0:t.getTool("redact");return{...(null==n?void 0:n.defaults)??{},id:e.id,type:Ot.REDACT,pageIndex:e.page,rect:e.rect,segmentRects:"text"===e.kind?e.rects:[],created:new Date}}annotationToRedactionItem(e){var t;const n=e.strokeColor??"#FF0000",o=e.color??"transparent";return e.segmentRects&&e.segmentRects.length>0?{id:e.id,kind:"text",page:e.pageIndex,rect:e.rect,rects:e.segmentRects,source:"annotation",markColor:n,redactionColor:o,...(null==(t=e.custom)?void 0:t.text)?{text:e.custom.text}:{}}:{id:e.id,kind:"area",page:e.pageIndex,rect:e.rect,source:"annotation",markColor:n,redactionColor:o}}emitPendingChange(e){const t=this.getDocumentState(e);t&&this.pending$.emit({documentId:e,pending:t.pending})}emitSelectedChange(e){const t=this.getDocumentState(e);t&&this.selected$.emit({documentId:e,selected:t.selected})}emitStateChange(e){const t=this.getDocumentState(e);t&&this.state$.emit({documentId:e,state:t})}onStoreUpdated(e,t){for(const e in t.documents){t.documents[e]&&(this.emitPendingChange(e),this.emitSelectedChange(e),this.emitStateChange(e))}}async destroy(){this.pending$.clear(),this.selected$.clear(),this.state$.clear(),this.events$.clear(),this.redactionSelection$.forEach(e=>e.clear()),this.redactionSelection$.clear(),this.redactionMarquee$.forEach(e=>e.clear()),this.redactionMarquee$.clear(),this.documentUnsubscribers.forEach(e=>{e.forEach(e=>e())}),this.documentUnsubscribers.clear(),await super.destroy()}};yg.id="redaction";let bg=yg;const wg="redaction",xg={manifest:{id:wg,name:"Redaction Plugin",version:"1.0.0",provides:["redaction"],requires:[],optional:["interaction-manager","selection","annotation"],defaultConfig:{drawBlackBoxes:!0}},create:(e,t)=>new bg(wg,e,t),reducer:(e=pg,t)=>{switch(t.type){case Xm:{const{documentId:n,state:o}=t.payload;return{...e,documents:{...e.documents,[n]:o},activeDocumentId:e.activeDocumentId??n}}case Qm:{const n=t.payload,{[n]:o,...i}=e.documents;return{...e,documents:i,activeDocumentId:e.activeDocumentId===n?null:e.activeDocumentId}}case"REDACTION/SET_ACTIVE_DOCUMENT":return{...e,activeDocumentId:t.payload};case tg:{const{documentId:n,items:o}=t.payload,i=e.documents[n];if(!i)return e;const r={...i.pending};for(const e of o){const t=r[e.page]??[];t.some(t=>t.id===e.id)||(r[e.page]=t.concat(e))}return{...e,documents:{...e.documents,[n]:{...i,pending:r,pendingCount:mg(r)}}}}case ng:{const{documentId:n,page:o,id:i}=t.payload,r=e.documents[n];if(!r)return e;const a=(r.pending[o]??[]).filter(e=>e.id!==i),s={...r.pending,[o]:a},l=r.selected&&!(r.selected.page===o&&r.selected.id===i);return{...e,documents:{...e.documents,[n]:{...r,pending:s,pendingCount:mg(s),selected:l?r.selected:null}}}}case og:{const{documentId:n,page:o,id:i,patch:r}=t.payload,a=e.documents[n];if(!a)return e;const s=(a.pending[o]??[]).map(e=>e.id===i?{...e,...r}:e);return{...e,documents:{...e.documents,[n]:{...a,pending:{...a.pending,[o]:s}}}}}case ig:{const n=t.payload,o=e.documents[n];return o?{...e,documents:{...e.documents,[n]:{...o,pending:{},pendingCount:0,selected:null}}}:e}case rg:{const{documentId:n,page:o,id:i}=t.payload,r=e.documents[n];return r?{...e,documents:{...e.documents,[n]:{...r,selected:{page:o,id:i}}}}:e}case ag:{const n=t.payload,o=e.documents[n];return o?{...e,documents:{...e.documents,[n]:{...o,selected:null}}}:e}case Jm:{const{documentId:n,mode:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,isRedacting:!0,activeType:o}}}:e}case eg:{const n=t.payload,o=e.documents[n];return o?{...e,documents:{...e.documents,[n]:{...o,isRedacting:!1,activeType:null}}}:e}case"SET_ACTIVE_TYPE":{const{documentId:n,mode:o}=t.payload,i=e.documents[n];return i?{...e,documents:{...e.documents,[n]:{...i,activeType:o}}}:e}default:return e}},initialState:pg};function Cg({annotation:e,isSelected:t,scale:n,onClick:o,style:i}){const[r,a]=Se(!1),{object:s}=e,l=s.segmentRects??[],c=s.rect,d=s.strokeColor??"#FF0000",u=s.color??"#000000",h=s.opacity??1,m=s.fontColor??s.overlayColor??"#FFFFFF",g=s.overlayText,p=s.overlayTextRepeat??!1,f=s.fontSize??12,v=s.fontFamily??Pt.Helvetica,y=s.textAlign??Dt.Center,b=()=>{if(!g)return null;if(!p)return g;return Array(10).fill(g).join(" ")};return He("div",{onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{position:"absolute",inset:0},children:l.map((e,t)=>He("div",{onPointerDown:o,style:{position:"absolute",left:(c?e.origin.x-c.origin.x:e.origin.x)*n,top:(c?e.origin.y-c.origin.y:e.origin.y)*n,width:e.size.width*n,height:e.size.height*n,background:r?u:"transparent",border:r?"none":`2px solid ${d}`,opacity:r?h:1,boxSizing:"border-box",pointerEvents:"auto",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:y===Dt.Left?"flex-start":y===Dt.Right?"flex-end":"center",overflow:"hidden",...i},children:r&&g&&He("span",{style:{color:m,fontSize:Math.min(f*n,e.size.height*n*.8),...In(v),textAlign:hn(y),whiteSpace:p?"normal":"nowrap",overflow:"hidden",textOverflow:"ellipsis",lineHeight:1},children:b()})},t))})}function kg({annotation:e,isSelected:t,scale:n,onClick:o,style:i}){const[r,a]=Se(!1),{object:s}=e,l=s.strokeColor??"#FF0000",c=s.color??"#000000",d=s.opacity??1,u=s.fontColor??s.overlayColor??"#FFFFFF",h=s.overlayText,m=s.overlayTextRepeat??!1,g=s.fontSize??12,p=s.fontFamily??Pt.Helvetica,f=s.textAlign??Dt.Center;return He("div",{onPointerDown:t?void 0:o,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{position:"absolute",inset:0,background:r?c:"transparent",border:r?"none":`2px solid ${l}`,opacity:r?d:1,boxSizing:"border-box",pointerEvents:"auto",cursor:t?"move":"pointer",display:"flex",alignItems:"center",justifyContent:f===Dt.Left?"flex-start":f===Dt.Right?"flex-end":"center",overflow:"hidden",...i},children:r&&h&&He("span",{style:{color:u,fontSize:g*n,...In(p),textAlign:hn(f),whiteSpace:m?"normal":"nowrap",overflow:"hidden",textOverflow:"ellipsis",padding:"4px"},children:(()=>{if(!h)return null;if(!m)return h;return Array(10).fill(h).join(" ")})()})})}const Ig=[Ph({id:"redactHighlight",matches:e=>{var t;return e.type===Ot.REDACT&&"segmentRects"in e&&((null==(t=e.segmentRects)?void 0:t.length)??0)>0},render:({annotation:e,isSelected:t,scale:n,pageIndex:o,onClick:i})=>He(Cg,{annotation:e,isSelected:t,scale:n,pageIndex:o,onClick:i}),interactionDefaults:{isDraggable:!1,isResizable:!1,isRotatable:!1},useAppearanceStream:!1}),Ph({id:"redactArea",matches:e=>{var t;return!(e.type!==Ot.REDACT||"segmentRects"in e&&(null==(t=e.segmentRects)?void 0:t.length))},render:({annotation:e,isSelected:t,scale:n,pageIndex:o,onClick:i})=>He(kg,{annotation:e,isSelected:t,scale:n,pageIndex:o,onClick:i}),interactionDefaults:{isDraggable:!1,isResizable:!1,isRotatable:!1},useAppearanceStream:!1})];const Sg=()=>Lo(bg.id),Ag=()=>Oo(bg.id),Mg=({documentId:e,pageIndex:t,scale:n,className:o,stroke:i,fill:r="transparent"})=>{const{plugin:a}=Sg(),s=jo(e),[l,c]=Se(null),d=n??(null==s?void 0:s.scale)??1,u=i??(null==a?void 0:a.getPreviewStrokeColor())??"red";return Me(()=>{if(a&&e)return a.onRedactionMarqueeChange(e,e=>{c(e.pageIndex===t?e.rect:null)})},[a,e,t]),l?He("div",{style:{position:"absolute",pointerEvents:"none",left:l.origin.x*d,top:l.origin.y*d,width:l.size.width*d,height:l.size.height*d,border:`1px solid ${u}`,background:r,boxSizing:"border-box"},className:o}):null};function Pg({color:e="#FFFF00",opacity:t=1,border:n="1px solid red",rects:o,rect:i,scale:r,onClick:a,style:s,...l}){return He(H,{children:o.map((o,c)=>He("div",{onPointerDown:a,style:{position:"absolute",border:n,left:(i?o.origin.x-i.origin.x:o.origin.x)*r,top:(i?o.origin.y-i.origin.y:o.origin.y)*r,width:o.size.width*r,height:o.size.height*r,background:e,opacity:t,pointerEvents:a?"auto":"none",cursor:a?"pointer":"default",zIndex:a?1:void 0,...s},...l},c))})}function Dg({documentId:e,pageIndex:t,scale:n}){const{plugin:o}=Sg(),[i,r]=Se([]),[a,s]=Se(null),l=(null==o?void 0:o.getPreviewStrokeColor())??"red";return Me(()=>{if(o)return o.onRedactionSelectionChange(e,e=>{const n=e.find(e=>e.pageIndex===t);r((null==n?void 0:n.segmentRects)??[]),s((null==n?void 0:n.rect)??null)})},[o,e,t]),a?He("div",{style:{mixBlendMode:"normal",pointerEvents:"none",position:"absolute",inset:0},children:He(Pg,{color:"transparent",opacity:1,rects:i,scale:n,border:`1px solid ${l}`})}):null}function Rg({documentId:e,pageIndex:t,scale:n,bboxStroke:o="rgba(0,0,0,0.8)",rotation:i=We.Degree0,selectionMenu:r}){const{provides:a}=Ag(),[s,l]=Se([]),[c,d]=Se(null);Me(()=>{if(!a)return;const n=a.forDocument(e),o=n.getState();l((o.pending[t]??[]).filter(e=>"legacy"===e.source)),d(o.selected&&o.selected.page===t?o.selected.id:null);const i=n.onPendingChange(e=>{l((e[t]??[]).filter(e=>"legacy"===e.source))}),r=n.onSelectedChange(e=>{d(e&&e.page===t?e.id:null)});return()=>{null==i||i(),null==r||r()}},[a,e,t]);const u=ze((n,o)=>{n.stopPropagation(),a&&a.forDocument(e).selectPending(t,o)},[a,e,t]);return s.length?He("div",{style:{position:"absolute",inset:0,pointerEvents:"none"},children:s.map(e=>{if("area"===e.kind){const a=e.rect;return He(H,{children:[He("div",{style:{position:"absolute",left:a.origin.x*n,top:a.origin.y*n,width:a.size.width*n,height:a.size.height*n,background:"transparent",outline:c===e.id?`1px solid ${o}`:"none",outlineOffset:"2px",border:`1px solid ${e.markColor}`,pointerEvents:"auto",cursor:"pointer"},onPointerDown:t=>u(t,e.id)}),r&&He(zl,{rect:{origin:{x:a.origin.x*n,y:a.origin.y*n},size:{width:a.size.width*n,height:a.size.height*n}},rotation:i,children:n=>r({...n,context:{type:"redaction",item:e,pageIndex:t},selected:c===e.id,placement:{suggestTop:!1}})})]},e.id)}const a=e.rect;return He(H,{children:[He("div",{style:{position:"absolute",left:a.origin.x*n,top:a.origin.y*n,width:a.size.width*n,height:a.size.height*n,background:"transparent",outline:c===e.id?`1px solid ${o}`:"none",outlineOffset:"2px",pointerEvents:"auto",cursor:c===e.id?"pointer":"default"},children:He(Pg,{rect:a,rects:e.rects,color:"transparent",border:`1px solid ${e.markColor}`,scale:n,onClick:t=>u(t,e.id)})}),r&&He(zl,{rect:{origin:{x:a.origin.x*n,y:a.origin.y*n},size:{width:a.size.width*n,height:a.size.height*n}},rotation:i,children:n=>r({...n,context:{type:"redaction",item:e,pageIndex:t},selected:c===e.id,placement:{suggestTop:!1}})})]},e.id)})}):null}const zg=({documentId:e,pageIndex:t,scale:n,rotation:o,selectionMenu:i})=>{var r,a;const s=jo(e),l=null==(a=null==(r=null==s?void 0:s.document)?void 0:r.pages)?void 0:a[t],c=Re(()=>void 0!==n?n:(null==s?void 0:s.scale)??1,[n,null==s?void 0:s.scale]);return He(H,{children:[He(Rg,{documentId:e,pageIndex:t,scale:c,rotation:Re(()=>{if(void 0!==o)return o;return(((null==l?void 0:l.rotation)??0)+((null==s?void 0:s.rotation)??0))%4},[o,null==l?void 0:l.rotation,null==s?void 0:s.rotation]),selectionMenu:i}),He(Mg,{documentId:e,pageIndex:t,scale:c}),He(Dg,{documentId:e,pageIndex:t,scale:c})]})},Tg=To(xg).addUtility(function(){return function(e){const t=Te(yh),n=De(e);Me(()=>{if(t)return t(n.current)},[t])}(Ig),null}).build(),Eg=class extends bo{constructor(e,t){super(e,t)}async initialize(e){}buildCapability(){return{getAttachments:()=>this.getAttachments(),downloadAttachment:e=>this.downloadAttachment(e),forDocument:e=>this.createAttachmentScope(e)}}createAttachmentScope(e){return{getAttachments:()=>this.getAttachments(e),downloadAttachment:t=>this.downloadAttachment(t,e)}}downloadAttachment(e,t){const n=t??this.getActiveDocumentId(),o=this.coreState.core.documents[n];return(null==o?void 0:o.document)?this.engine.readAttachmentContent(o.document,e):nn.reject({code:tn.NotFound,message:`Document ${n} not found`})}getAttachments(e){const t=e??this.getActiveDocumentId(),n=this.coreState.core.documents[t];return(null==n?void 0:n.document)?this.engine.getAttachments(n.document):nn.reject({code:tn.NotFound,message:`Document ${t} not found`})}};Eg.id="attachment";let _g=Eg;const Ng="attachment",Lg={manifest:{id:Ng,name:"Attachment Plugin",version:"1.0.0",provides:["attachment"],requires:[],optional:[],defaultConfig:{}},create:e=>new _g(Ng,e),reducer:()=>{},initialState:{}},Og=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),$g="-",jg=[],Fg=e=>{const t=Wg(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:o}=e;return{getClassGroupId:e=>{if(e.startsWith("[")&&e.endsWith("]"))return Hg(e);const n=e.split($g),o=""===n[0]&&n.length>1?1:0;return Ug(n,o,t)},getConflictingClassGroupIds:(e,t)=>{if(t){const t=o[e],i=n[e];return t?i?((e,t)=>{const n=new Array(e.length+t.length);for(let t=0;t{if(0===e.length-t)return n.classGroupId;const o=e[t],i=n.nextPart.get(o);if(i){const n=Ug(e,t+1,i);if(n)return n}const r=n.validators;if(null===r)return;const a=0===t?e.join($g):e.slice(t).join($g),s=r.length;for(let e=0;e-1===e.slice(1,-1).indexOf(":")?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),o=t.slice(0,n);return o?"arbitrary.."+o:void 0})(),Wg=e=>{const{theme:t,classGroups:n}=e;return Bg(n,t)},Bg=(e,t)=>{const n=Og();for(const o in e){const i=e[o];qg(i,n,o,t)}return n},qg=(e,t,n,o)=>{const i=e.length;for(let r=0;r{"string"!=typeof e?"function"!=typeof e?Zg(e,t,n,o):Kg(e,t,n,o):Vg(e,t,n)},Vg=(e,t,n)=>{(""===e?t:Yg(t,e)).classGroupId=n},Kg=(e,t,n,o)=>{Xg(e)?qg(e(o),t,n,o):(null===t.validators&&(t.validators=[]),t.validators.push(((e,t)=>({classGroupId:e,validator:t}))(n,e)))},Zg=(e,t,n,o)=>{const i=Object.entries(e),r=i.length;for(let e=0;e{let n=e;const o=t.split($g),i=o.length;for(let e=0;e"isThemeGetter"in e&&!0===e.isThemeGetter,Qg=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),o=Object.create(null);const i=(i,r)=>{n[i]=r,t++,t>e&&(t=0,o=n,n=Object.create(null))};return{get(e){let t=n[e];return void 0!==t?t:void 0!==(t=o[e])?(i(e,t),t):void 0},set(e,t){e in n?n[e]=t:i(e,t)}}},Jg=[],ep=(e,t,n,o,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:o,isExternal:i}),tp=e=>{const{prefix:t,experimentalParseClassName:n}=e;let o=e=>{const t=[];let n,o=0,i=0,r=0;const a=e.length;for(let s=0;sr?n-r:void 0)};if(t){const e=t+":",n=o;o=t=>t.startsWith(e)?n(t.slice(e.length)):ep(Jg,!1,t,void 0,!0)}if(n){const e=o;o=t=>n({className:t,parseClassName:e})}return o},np=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((e,n)=>{t.set(e,1e6+n)}),e=>{const n=[];let o=[];for(let i=0;i0&&(o.sort(),n.push(...o),o=[]),n.push(r)):o.push(r)}return o.length>0&&(o.sort(),n.push(...o)),n}},op=/\s+/,ip=e=>{if("string"==typeof e)return e;let t,n="";for(let o=0;o{let n,o,i,r;const a=e=>{const t=o(e);if(t)return t;const r=((e,t)=>{const{parseClassName:n,getClassGroupId:o,getConflictingClassGroupIds:i,sortModifiers:r}=t,a=[],s=e.trim().split(op);let l="";for(let e=s.length-1;e>=0;e-=1){const t=s[e],{isExternal:c,modifiers:d,hasImportantModifier:u,baseClassName:h,maybePostfixModifierPosition:m}=n(t);if(c){l=t+(l.length>0?" "+l:l);continue}let g=!!m,p=o(g?h.substring(0,m):h);if(!p){if(!g){l=t+(l.length>0?" "+l:l);continue}if(p=o(h),!p){l=t+(l.length>0?" "+l:l);continue}g=!1}const f=0===d.length?"":1===d.length?d[0]:r(d).join(":"),v=u?f+"!":f,y=v+p;if(a.indexOf(y)>-1)continue;a.push(y);const b=i(p,g);for(let e=0;e0?" "+l:l)}return l})(e,n);return i(e,r),r};return r=s=>{const l=t.reduce((e,t)=>t(e),e());return n=(e=>({cache:Qg(e.cacheSize),parseClassName:tp(e),sortModifiers:np(e),...Fg(e)}))(l),o=n.cache.get,i=n.cache.set,r=a,a(s)},(...e)=>r(((...e)=>{let t,n,o=0,i="";for(;o{const t=t=>t[e]||ap;return t.isThemeGetter=!0,t},lp=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,cp=/^\((?:(\w[\w-]*):)?(.+)\)$/i,dp=/^\d+\/\d+$/,up=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,hp=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,mp=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,gp=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,pp=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,fp=e=>dp.test(e),vp=e=>!!e&&!Number.isNaN(Number(e)),yp=e=>!!e&&Number.isInteger(Number(e)),bp=e=>e.endsWith("%")&&vp(e.slice(0,-1)),wp=e=>up.test(e),xp=()=>!0,Cp=e=>hp.test(e)&&!mp.test(e),kp=()=>!1,Ip=e=>gp.test(e),Sp=e=>pp.test(e),Ap=e=>!Pp(e)&&!_p(e),Mp=e=>Up(e,qp,kp),Pp=e=>lp.test(e),Dp=e=>Up(e,Gp,Cp),Rp=e=>Up(e,Vp,vp),zp=e=>Up(e,Wp,kp),Tp=e=>Up(e,Bp,Sp),Ep=e=>Up(e,Zp,Ip),_p=e=>cp.test(e),Np=e=>Hp(e,Gp),Lp=e=>Hp(e,Kp),Op=e=>Hp(e,Wp),$p=e=>Hp(e,qp),jp=e=>Hp(e,Bp),Fp=e=>Hp(e,Zp,!0),Up=(e,t,n)=>{const o=lp.exec(e);return!!o&&(o[1]?t(o[1]):n(o[2]))},Hp=(e,t,n=!1)=>{const o=cp.exec(e);return!!o&&(o[1]?t(o[1]):n)},Wp=e=>"position"===e||"percentage"===e,Bp=e=>"image"===e||"url"===e,qp=e=>"length"===e||"size"===e||"bg-size"===e,Gp=e=>"length"===e,Vp=e=>"number"===e,Kp=e=>"family-name"===e,Zp=e=>"shadow"===e,Yp=rp(()=>{const e=sp("color"),t=sp("font"),n=sp("text"),o=sp("font-weight"),i=sp("tracking"),r=sp("leading"),a=sp("breakpoint"),s=sp("container"),l=sp("spacing"),c=sp("radius"),d=sp("shadow"),u=sp("inset-shadow"),h=sp("text-shadow"),m=sp("drop-shadow"),g=sp("blur"),p=sp("perspective"),f=sp("aspect"),v=sp("ease"),y=sp("animate"),b=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom",_p,Pp],w=()=>[_p,Pp,l],x=()=>[fp,"full","auto",...w()],C=()=>[yp,"none","subgrid",_p,Pp],k=()=>["auto",{span:["full",yp,_p,Pp]},yp,_p,Pp],I=()=>[yp,"auto",_p,Pp],S=()=>["auto","min","max","fr",_p,Pp],A=()=>["auto",...w()],M=()=>[fp,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...w()],P=()=>[e,_p,Pp],D=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom",Op,zp,{position:[_p,Pp]}],R=()=>["auto","cover","contain",$p,Mp,{size:[_p,Pp]}],z=()=>[bp,Np,Dp],T=()=>["","none","full",c,_p,Pp],E=()=>["",vp,Np,Dp],_=()=>[vp,bp,Op,zp],N=()=>["","none",g,_p,Pp],L=()=>["none",vp,_p,Pp],O=()=>["none",vp,_p,Pp],$=()=>[vp,_p,Pp],j=()=>[fp,"full",...w()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[wp],breakpoint:[wp],color:[xp],container:[wp],"drop-shadow":[wp],ease:["in","out","in-out"],font:[Ap],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[wp],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[wp],shadow:[wp],spacing:["px",vp],text:[wp],"text-shadow":[wp],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",fp,Pp,_p,f]}],container:["container"],columns:[{columns:[vp,Pp,_p,s]}],"break-after":[{"break-after":["auto","avoid","all","avoid-page","page","left","right","column"]}],"break-before":[{"break-before":["auto","avoid","all","avoid-page","page","left","right","column"]}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:b()}],overflow:[{overflow:["auto","hidden","clip","visible","scroll"]}],"overflow-x":[{"overflow-x":["auto","hidden","clip","visible","scroll"]}],"overflow-y":[{"overflow-y":["auto","hidden","clip","visible","scroll"]}],overscroll:[{overscroll:["auto","contain","none"]}],"overscroll-x":[{"overscroll-x":["auto","contain","none"]}],"overscroll-y":[{"overscroll-y":["auto","contain","none"]}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:x()}],"inset-x":[{"inset-x":x()}],"inset-y":[{"inset-y":x()}],start:[{start:x()}],end:[{end:x()}],top:[{top:x()}],right:[{right:x()}],bottom:[{bottom:x()}],left:[{left:x()}],visibility:["visible","invisible","collapse"],z:[{z:[yp,"auto",_p,Pp]}],basis:[{basis:[fp,"full","auto",s,...w()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[vp,fp,"auto","initial","none",Pp]}],grow:[{grow:["",vp,_p,Pp]}],shrink:[{shrink:["",vp,_p,Pp]}],order:[{order:[yp,"first","last","none",_p,Pp]}],"grid-cols":[{"grid-cols":C()}],"col-start-end":[{col:k()}],"col-start":[{"col-start":I()}],"col-end":[{"col-end":I()}],"grid-rows":[{"grid-rows":C()}],"row-start-end":[{row:k()}],"row-start":[{"row-start":I()}],"row-end":[{"row-end":I()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":S()}],"auto-rows":[{"auto-rows":S()}],gap:[{gap:w()}],"gap-x":[{"gap-x":w()}],"gap-y":[{"gap-y":w()}],"justify-content":[{justify:["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe","normal"]}],"justify-items":[{"justify-items":["start","end","center","stretch","center-safe","end-safe","normal"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch","center-safe","end-safe"]}],"align-content":[{content:["normal","start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"]}],"align-items":[{items:["start","end","center","stretch","center-safe","end-safe",{baseline:["","last"]}]}],"align-self":[{self:["auto","start","end","center","stretch","center-safe","end-safe",{baseline:["","last"]}]}],"place-content":[{"place-content":["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"]}],"place-items":[{"place-items":["start","end","center","stretch","center-safe","end-safe","baseline"]}],"place-self":[{"place-self":["auto","start","end","center","stretch","center-safe","end-safe"]}],p:[{p:w()}],px:[{px:w()}],py:[{py:w()}],ps:[{ps:w()}],pe:[{pe:w()}],pt:[{pt:w()}],pr:[{pr:w()}],pb:[{pb:w()}],pl:[{pl:w()}],m:[{m:A()}],mx:[{mx:A()}],my:[{my:A()}],ms:[{ms:A()}],me:[{me:A()}],mt:[{mt:A()}],mr:[{mr:A()}],mb:[{mb:A()}],ml:[{ml:A()}],"space-x":[{"space-x":w()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":w()}],"space-y-reverse":["space-y-reverse"],size:[{size:M()}],w:[{w:[s,"screen",...M()]}],"min-w":[{"min-w":[s,"screen","none",...M()]}],"max-w":[{"max-w":[s,"screen","none","prose",{screen:[a]},...M()]}],h:[{h:["screen","lh",...M()]}],"min-h":[{"min-h":["screen","lh","none",...M()]}],"max-h":[{"max-h":["screen","lh",...M()]}],"font-size":[{text:["base",n,Np,Dp]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[o,_p,Rp]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",bp,Pp]}],"font-family":[{font:[Lp,Pp,t]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[i,_p,Pp]}],"line-clamp":[{"line-clamp":[vp,"none",_p,Rp]}],leading:[{leading:[r,...w()]}],"list-image":[{"list-image":["none",_p,Pp]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",_p,Pp]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:P()}],"text-color":[{text:P()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:["solid","dashed","dotted","double","wavy"]}],"text-decoration-thickness":[{decoration:[vp,"from-font","auto",_p,Dp]}],"text-decoration-color":[{decoration:P()}],"underline-offset":[{"underline-offset":[vp,"auto",_p,Pp]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:w()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",_p,Pp]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",_p,Pp]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:D()}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","space","round"]}]}],"bg-size":[{bg:R()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},yp,_p,Pp],radial:["",_p,Pp],conic:[yp,_p,Pp]},jp,Tp]}],"bg-color":[{bg:P()}],"gradient-from-pos":[{from:z()}],"gradient-via-pos":[{via:z()}],"gradient-to-pos":[{to:z()}],"gradient-from":[{from:P()}],"gradient-via":[{via:P()}],"gradient-to":[{to:P()}],rounded:[{rounded:T()}],"rounded-s":[{"rounded-s":T()}],"rounded-e":[{"rounded-e":T()}],"rounded-t":[{"rounded-t":T()}],"rounded-r":[{"rounded-r":T()}],"rounded-b":[{"rounded-b":T()}],"rounded-l":[{"rounded-l":T()}],"rounded-ss":[{"rounded-ss":T()}],"rounded-se":[{"rounded-se":T()}],"rounded-ee":[{"rounded-ee":T()}],"rounded-es":[{"rounded-es":T()}],"rounded-tl":[{"rounded-tl":T()}],"rounded-tr":[{"rounded-tr":T()}],"rounded-br":[{"rounded-br":T()}],"rounded-bl":[{"rounded-bl":T()}],"border-w":[{border:E()}],"border-w-x":[{"border-x":E()}],"border-w-y":[{"border-y":E()}],"border-w-s":[{"border-s":E()}],"border-w-e":[{"border-e":E()}],"border-w-t":[{"border-t":E()}],"border-w-r":[{"border-r":E()}],"border-w-b":[{"border-b":E()}],"border-w-l":[{"border-l":E()}],"divide-x":[{"divide-x":E()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":E()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:["solid","dashed","dotted","double","hidden","none"]}],"divide-style":[{divide:["solid","dashed","dotted","double","hidden","none"]}],"border-color":[{border:P()}],"border-color-x":[{"border-x":P()}],"border-color-y":[{"border-y":P()}],"border-color-s":[{"border-s":P()}],"border-color-e":[{"border-e":P()}],"border-color-t":[{"border-t":P()}],"border-color-r":[{"border-r":P()}],"border-color-b":[{"border-b":P()}],"border-color-l":[{"border-l":P()}],"divide-color":[{divide:P()}],"outline-style":[{outline:["solid","dashed","dotted","double","none","hidden"]}],"outline-offset":[{"outline-offset":[vp,_p,Pp]}],"outline-w":[{outline:["",vp,Np,Dp]}],"outline-color":[{outline:P()}],shadow:[{shadow:["","none",d,Fp,Ep]}],"shadow-color":[{shadow:P()}],"inset-shadow":[{"inset-shadow":["none",u,Fp,Ep]}],"inset-shadow-color":[{"inset-shadow":P()}],"ring-w":[{ring:E()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:P()}],"ring-offset-w":[{"ring-offset":[vp,Dp]}],"ring-offset-color":[{"ring-offset":P()}],"inset-ring-w":[{"inset-ring":E()}],"inset-ring-color":[{"inset-ring":P()}],"text-shadow":[{"text-shadow":["none",h,Fp,Ep]}],"text-shadow-color":[{"text-shadow":P()}],opacity:[{opacity:[vp,_p,Pp]}],"mix-blend":[{"mix-blend":["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"]}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[vp]}],"mask-image-linear-from-pos":[{"mask-linear-from":_()}],"mask-image-linear-to-pos":[{"mask-linear-to":_()}],"mask-image-linear-from-color":[{"mask-linear-from":P()}],"mask-image-linear-to-color":[{"mask-linear-to":P()}],"mask-image-t-from-pos":[{"mask-t-from":_()}],"mask-image-t-to-pos":[{"mask-t-to":_()}],"mask-image-t-from-color":[{"mask-t-from":P()}],"mask-image-t-to-color":[{"mask-t-to":P()}],"mask-image-r-from-pos":[{"mask-r-from":_()}],"mask-image-r-to-pos":[{"mask-r-to":_()}],"mask-image-r-from-color":[{"mask-r-from":P()}],"mask-image-r-to-color":[{"mask-r-to":P()}],"mask-image-b-from-pos":[{"mask-b-from":_()}],"mask-image-b-to-pos":[{"mask-b-to":_()}],"mask-image-b-from-color":[{"mask-b-from":P()}],"mask-image-b-to-color":[{"mask-b-to":P()}],"mask-image-l-from-pos":[{"mask-l-from":_()}],"mask-image-l-to-pos":[{"mask-l-to":_()}],"mask-image-l-from-color":[{"mask-l-from":P()}],"mask-image-l-to-color":[{"mask-l-to":P()}],"mask-image-x-from-pos":[{"mask-x-from":_()}],"mask-image-x-to-pos":[{"mask-x-to":_()}],"mask-image-x-from-color":[{"mask-x-from":P()}],"mask-image-x-to-color":[{"mask-x-to":P()}],"mask-image-y-from-pos":[{"mask-y-from":_()}],"mask-image-y-to-pos":[{"mask-y-to":_()}],"mask-image-y-from-color":[{"mask-y-from":P()}],"mask-image-y-to-color":[{"mask-y-to":P()}],"mask-image-radial":[{"mask-radial":[_p,Pp]}],"mask-image-radial-from-pos":[{"mask-radial-from":_()}],"mask-image-radial-to-pos":[{"mask-radial-to":_()}],"mask-image-radial-from-color":[{"mask-radial-from":P()}],"mask-image-radial-to-color":[{"mask-radial-to":P()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"]}],"mask-image-conic-pos":[{"mask-conic":[vp]}],"mask-image-conic-from-pos":[{"mask-conic-from":_()}],"mask-image-conic-to-pos":[{"mask-conic-to":_()}],"mask-image-conic-from-color":[{"mask-conic-from":P()}],"mask-image-conic-to-color":[{"mask-conic-to":P()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:D()}],"mask-repeat":[{mask:["no-repeat",{repeat:["","x","y","space","round"]}]}],"mask-size":[{mask:R()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",_p,Pp]}],filter:[{filter:["","none",_p,Pp]}],blur:[{blur:N()}],brightness:[{brightness:[vp,_p,Pp]}],contrast:[{contrast:[vp,_p,Pp]}],"drop-shadow":[{"drop-shadow":["","none",m,Fp,Ep]}],"drop-shadow-color":[{"drop-shadow":P()}],grayscale:[{grayscale:["",vp,_p,Pp]}],"hue-rotate":[{"hue-rotate":[vp,_p,Pp]}],invert:[{invert:["",vp,_p,Pp]}],saturate:[{saturate:[vp,_p,Pp]}],sepia:[{sepia:["",vp,_p,Pp]}],"backdrop-filter":[{"backdrop-filter":["","none",_p,Pp]}],"backdrop-blur":[{"backdrop-blur":N()}],"backdrop-brightness":[{"backdrop-brightness":[vp,_p,Pp]}],"backdrop-contrast":[{"backdrop-contrast":[vp,_p,Pp]}],"backdrop-grayscale":[{"backdrop-grayscale":["",vp,_p,Pp]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[vp,_p,Pp]}],"backdrop-invert":[{"backdrop-invert":["",vp,_p,Pp]}],"backdrop-opacity":[{"backdrop-opacity":[vp,_p,Pp]}],"backdrop-saturate":[{"backdrop-saturate":[vp,_p,Pp]}],"backdrop-sepia":[{"backdrop-sepia":["",vp,_p,Pp]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":w()}],"border-spacing-x":[{"border-spacing-x":w()}],"border-spacing-y":[{"border-spacing-y":w()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",_p,Pp]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[vp,"initial",_p,Pp]}],ease:[{ease:["linear","initial",v,_p,Pp]}],delay:[{delay:[vp,_p,Pp]}],animate:[{animate:["none",y,_p,Pp]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[p,_p,Pp]}],"perspective-origin":[{"perspective-origin":b()}],rotate:[{rotate:L()}],"rotate-x":[{"rotate-x":L()}],"rotate-y":[{"rotate-y":L()}],"rotate-z":[{"rotate-z":L()}],scale:[{scale:O()}],"scale-x":[{"scale-x":O()}],"scale-y":[{"scale-y":O()}],"scale-z":[{"scale-z":O()}],"scale-3d":["scale-3d"],skew:[{skew:$()}],"skew-x":[{"skew-x":$()}],"skew-y":[{"skew-y":$()}],transform:[{transform:[_p,Pp,"","none","gpu","cpu"]}],"transform-origin":[{origin:b()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:j()}],"translate-x":[{"translate-x":j()}],"translate-y":[{"translate-y":j()}],"translate-z":[{"translate-z":j()}],"translate-none":["translate-none"],accent:[{accent:P()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:P()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",_p,Pp]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":w()}],"scroll-mx":[{"scroll-mx":w()}],"scroll-my":[{"scroll-my":w()}],"scroll-ms":[{"scroll-ms":w()}],"scroll-me":[{"scroll-me":w()}],"scroll-mt":[{"scroll-mt":w()}],"scroll-mr":[{"scroll-mr":w()}],"scroll-mb":[{"scroll-mb":w()}],"scroll-ml":[{"scroll-ml":w()}],"scroll-p":[{"scroll-p":w()}],"scroll-px":[{"scroll-px":w()}],"scroll-py":[{"scroll-py":w()}],"scroll-ps":[{"scroll-ps":w()}],"scroll-pe":[{"scroll-pe":w()}],"scroll-pt":[{"scroll-pt":w()}],"scroll-pr":[{"scroll-pr":w()}],"scroll-pb":[{"scroll-pb":w()}],"scroll-pl":[{"scroll-pl":w()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",_p,Pp]}],fill:[{fill:["none",...P()]}],"stroke-w":[{stroke:[vp,Np,Dp,Rp]}],stroke:[{stroke:["none",...P()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}});var Xp=["children","onClick","active","disabled","className","anchorRef"];function Qp(e){var t=e.children,n=e.onClick,o=e.active,i=void 0!==o&&o,r=e.disabled,a=void 0!==r&&r,s=e.className,l=void 0===s?"":s,c=e.anchorRef,d=m(e,Xp);return F("button",h({type:"button",ref:c,onClick:n,disabled:a,className:Yp("flex h-[32px] w-auto min-w-[32px] items-center justify-center rounded-md p-[5px] transition-colors hover:bg-interactive-hover hover:ring hover:ring-accent cursor-pointer rounded-none px-2 py-1 text-sm hover:bg-transparent border-b-2 hover:border-b-fg-muted hover:ring-transparent",i?"border-b-accent text-accent hover:border-b-accent":"border-b-transparent",a?"cursor-not-allowed opacity-50":"",l)},d),t)}var Jp=function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M9 6l6 6l-6 6"}))},ef=function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M15 6l-6 6l6 6"}))},tf=function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M6 9l6 6l6 -6"}))},nf=function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M10 10m-7 0a7 7 0 1 0 14 0a7 7 0 1 0 -14 0"}),F("path",{d:"M21 21l-6 -6"}))},of=function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M18 6l-12 12"}),F("path",{d:"M6 6l12 12"}))},rf=function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r,s=e.secondaryColor,l=void 0===s?"currentColor":s;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M7 4h10"}),F("path",{d:"M12 4v8"}),F("defs",null,F("clipPath",{id:"stripeClip"},F("rect",{x:"2",y:"12",width:"20",height:"10",rx:"2"}))),F("rect",{x:"2",y:"12",width:"20",height:"10",rx:"2",fill:"none",stroke:a}),F("g",{"clip-path":"url(#stripeClip)",stroke:l},F("path",{d:"M-7 24l12 -12"}),F("path",{d:"M-3 24l12 -12"}),F("path",{d:"M1 24l12 -12"}),F("path",{d:"M5 24l12 -12"}),F("path",{d:"M9 24l12 -12"}),F("path",{d:"M13 24l12 -12"}),F("path",{d:"M17 24l12 -12"}),F("path",{d:"M21 24l12 -12"}),F("path",{d:"M25 24l12 -12"})))},af=function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r,s=e.secondaryColor,l=void 0===s?"currentColor":s;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:a,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M6 20h-1a2 2 0 0 1 -2 -2v-1"}),F("path",{d:"M3 13v-3"}),F("path",{d:"M3 6v-1a2 2 0 0 1 2 -2h1"}),F("path",{d:"M10 3h3"}),F("path",{d:"M17 3h1a2 2 0 0 1 2 2v1"}),F("defs",null,F("clipPath",{id:"redactClip"},F("rect",{x:"10",y:"10",width:"12",height:"12",rx:"2"}))),F("rect",{x:"10",y:"10",width:"12",height:"12",rx:"2",fill:"none"}),F("g",{"clip-path":"url(#redactClip)",stroke:l},F("path",{d:"M-2 24l14 -14"}),F("path",{d:"M2 24l14 -14"}),F("path",{d:"M6 24l14 -14"}),F("path",{d:"M10 24l15 -15"}),F("path",{d:"M14 24l15 -15"}),F("path",{d:"M18 24l15 -15"})))};var sf={download:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2 -2v-2"}),F("path",{d:"M7 11l5 5l5 -5"}),F("path",{d:"M12 4l0 12"}))},menu:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 8l16 0"}),F("path",{d:"M4 16l16 0"}))},fullscreen:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 8v-2a2 2 0 0 1 2 -2h2"}),F("path",{d:"M4 16v2a2 2 0 0 0 2 2h2"}),F("path",{d:"M16 4h2a2 2 0 0 1 2 2v2"}),F("path",{d:"M16 20h2a2 2 0 0 0 2 -2v-2"}))},fullscreenExit:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 8v-2c0 -.551 .223 -1.05 .584 -1.412"}),F("path",{d:"M4 16v2a2 2 0 0 0 2 2h2"}),F("path",{d:"M16 4h2a2 2 0 0 1 2 2v2"}),F("path",{d:"M16 20h2c.545 0 1.04 -.218 1.4 -.572"}),F("path",{d:"M3 3l18 18"}))},save:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M6 4h10l4 4v10a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2"}),F("path",{d:"M12 14m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),F("path",{d:"M14 4l0 4l-6 0l0 -4"}))},print:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M17 17h2a2 2 0 0 0 2 -2v-4a2 2 0 0 0 -2 -2h-14a2 2 0 0 0 -2 2v4a2 2 0 0 0 2 2h2"}),F("path",{d:"M17 9v-4a2 2 0 0 0 -2 -2h-6a2 2 0 0 0 -2 2v4"}),F("path",{d:"M7 13m0 2a2 2 0 0 1 2 -2h6a2 2 0 0 1 2 2v4a2 2 0 0 1 -2 2h-6a2 2 0 0 1 -2 -2z"}))},settings:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M10.325 4.317c.426 -1.756 2.924 -1.756 3.35 0a1.724 1.724 0 0 0 2.573 1.066c1.543 -.94 3.31 .826 2.37 2.37a1.724 1.724 0 0 0 1.065 2.572c1.756 .426 1.756 2.924 0 3.35a1.724 1.724 0 0 0 -1.066 2.573c.94 1.543 -.826 3.31 -2.37 2.37a1.724 1.724 0 0 0 -2.572 1.065c-.426 1.756 -2.924 1.756 -3.35 0a1.724 1.724 0 0 0 -2.573 -1.066c-1.543 .94 -3.31 -.826 -2.37 -2.37a1.724 1.724 0 0 0 -1.065 -2.572c-1.756 -.426 -1.756 -2.924 0 -3.35a1.724 1.724 0 0 0 1.066 -2.573c-.94 -1.543 .826 -3.31 2.37 -2.37c1 .608 2.296 .07 2.572 -1.065z"}),F("path",{d:"M9 12a3 3 0 1 0 6 0a3 3 0 0 0 -6 0"}))},viewSettings:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M12 14m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),F("path",{d:"M12 10.5v1.5"}),F("path",{d:"M12 16v1.5"}),F("path",{d:"M15.031 12.25l-1.299 .75"}),F("path",{d:"M10.268 15l-1.3 .75"}),F("path",{d:"M15 15.803l-1.285 -.773"}),F("path",{d:"M10.285 12.97l-1.285 -.773"}),F("path",{d:"M14 3v4a1 1 0 0 0 1 1h4"}),F("path",{d:"M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z"}))},rotateClockwise:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4.05 11a8 8 0 1 1 .5 4m-.5 5v-5h5"}))},rotateCounterClockwise:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M19.95 11a8 8 0 1 0 -.5 4m.5 5v-5h-5"}))},singlePage:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M5 3m0 1a1 1 0 0 1 1 -1h12a1 1 0 0 1 1 1v16a1 1 0 0 1 -1 1h-12a1 1 0 0 1 -1 -1z"}))},doublePage:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M3 3m0 1a1 1 0 0 1 1 -1h16a1 1 0 0 1 1 1v16a1 1 0 0 1 -1 1h-16a1 1 0 0 1 -1 -1zm9 -1v18"}))},zoomIn:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0"}),F("path",{d:"M9 12h6"}),F("path",{d:"M12 9v6"}))},zoomOut:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"}),F("path",{d:"M9 12l6 0"}))},fitToWidth:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 12v-6a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v6"}),F("path",{d:"M10 18h-7"}),F("path",{d:"M21 18h-7"}),F("path",{d:"M6 15l-3 3l3 3"}),F("path",{d:"M18 15l3 3l-3 3"}))},fitToPage:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M12 20h-6a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2h6"}),F("path",{d:"M18 14v7"}),F("path",{d:"M18 3v7"}),F("path",{d:"M15 18l3 3l3 -3"}),F("path",{d:"M15 6l3 -3l3 3"}))},chevronRight:Jp,chevronLeft:ef,chevronDown:tf,search:nf,comment:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M12 11v.01"}),F("path",{d:"M8 11v.01"}),F("path",{d:"M16 11v.01"}),F("path",{d:"M18 4a3 3 0 0 1 3 3v8a3 3 0 0 1 -3 3h-5l-5 3v-3h-2a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3z"}))},sidebar:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 18v-12a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z"}),F("path",{d:"M10 18v-12a2 2 0 0 1 2 -2h6a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-6a2 2 0 0 1 -2 -2z"}))},dots:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M5 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"}),F("path",{d:"M12 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"}),F("path",{d:"M19 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"}))},vertical:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M8 7l4 -4l4 4"}),F("path",{d:"M8 17l4 4l4 -4"}),F("path",{d:"M12 3l0 18"}))},horizontal:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M7 8l-4 4l4 4"}),F("path",{d:"M17 8l4 4l-4 4"}),F("path",{d:"M3 12l18 0"}))},book:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M3 19a9 9 0 0 1 9 0a9 9 0 0 1 9 0"}),F("path",{d:"M3 6a9 9 0 0 1 9 0a9 9 0 0 1 9 0"}),F("path",{d:"M3 6l0 13"}),F("path",{d:"M12 6l0 13"}),F("path",{d:"M21 6l0 13"}))},book2:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M19 4v16h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2h12z"}),F("path",{d:"M19 16h-12a2 2 0 0 0 -2 2"}),F("path",{d:"M9 8h6"}))},squares:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M8 10a2 2 0 0 1 2 -2h9a2 2 0 0 1 2 2v9a2 2 0 0 1 -2 2h-9a2 2 0 0 1 -2 -2z"}),F("path",{d:"M16 8v-3a2 2 0 0 0 -2 -2h-9a2 2 0 0 0 -2 2v9a2 2 0 0 0 2 2h3"}))},listTree:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M9 6h11"}),F("path",{d:"M12 12h8"}),F("path",{d:"M15 18h5"}),F("path",{d:"M5 6v.01"}),F("path",{d:"M8 12v.01"}),F("path",{d:"M11 18v.01"}))},paperclip:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M15 7l-6.5 6.5a1.5 1.5 0 0 0 3 3l6.5 -6.5a3 3 0 0 0 -6 -6l-6.5 6.5a4.5 4.5 0 0 0 9 9l6.5 -6.5"}))},copy:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M7 7m0 2.667a2.667 2.667 0 0 1 2.667 -2.667h8.666a2.667 2.667 0 0 1 2.667 2.667v8.666a2.667 2.667 0 0 1 -2.667 2.667h-8.666a2.667 2.667 0 0 1 -2.667 -2.667z"}),F("path",{d:"M4.012 16.737a2.005 2.005 0 0 1 -1.012 -1.737v-10c0 -1.1 .9 -2 2 -2h10c.75 0 1.158 .385 1.5 1"}))},underline:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none","stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 20h16",stroke:a}),F("path",{d:"M8 16v-8a4 4 0 1 1 8 0v8",stroke:"currentColor"}),F("path",{d:"M8 10h8",stroke:"currentColor"}))},squiggly:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none","stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M8 16v-8a4 4 0 1 1 8 0v8",stroke:"currentColor"}),F("path",{d:"M8 10h8",stroke:"currentColor"}),F("path",{d:"M4 20c1.5 -1.5 3.5 -1.5 5 0s3.5 1.5 5 0 3.5 -1.5 5 0",stroke:a}))},strikethrough:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none","stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M8 16v-8a4 4 0 1 1 8 0v8",stroke:"currentColor"}),F("path",{d:"M4 10h16",stroke:a}))},highlight:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none","stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("rect",{x:"2",y:"6",width:"20",height:"16",rx:"2",fill:a,stroke:"none"}),F("path",{d:"M8 16v-8a4 4 0 1 1 8 0v8",stroke:"currentColor"}),F("path",{d:"M8 10h8",stroke:"currentColor"}))},palette:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M12 21a9 9 0 0 1 0 -18c4.97 0 9 3.582 9 8c0 1.06 -.474 2.078 -1.318 2.828c-.844 .75 -1.989 1.172 -3.182 1.172h-2.5a2 2 0 0 0 -1 3.75a1.3 1.3 0 0 1 -1 2.25"}),F("path",{d:"M8.5 10.5m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"}),F("path",{d:"M12.5 7.5m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"}),F("path",{d:"M16.5 10.5m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"}))},x:of,fileImport:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M14 3v4a1 1 0 0 0 1 1h4"}),F("path",{d:"M5 13v-8a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2h-5.5m-9.5 -2h7m-3 -3l3 3l-3 3"}))},hand:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M8 13v-7.5a1.5 1.5 0 0 1 3 0v6.5"}),F("path",{d:"M11 5.5v-2a1.5 1.5 0 1 1 3 0v8.5"}),F("path",{d:"M14 5.5a1.5 1.5 0 0 1 3 0v6.5"}),F("path",{d:"M17 7.5a1.5 1.5 0 0 1 3 0v8.5a6 6 0 0 1 -6 6h-2h.208a6 6 0 0 1 -5.012 -2.7a69.74 69.74 0 0 1 -.196 -.3c-.312 -.479 -1.407 -2.388 -3.286 -5.728a1.5 1.5 0 0 1 .536 -2.022a1.867 1.867 0 0 1 2.28 .28l1.47 1.47"}))},zoomInArea:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M15 13v4"}),F("path",{d:"M13 15h4"}),F("path",{d:"M15 15m-5 0a5 5 0 1 0 10 0a5 5 0 1 0 -10 0"}),F("path",{d:"M22 22l-3 -3"}),F("path",{d:"M6 18h-1a2 2 0 0 1 -2 -2v-1"}),F("path",{d:"M3 11v-1"}),F("path",{d:"M3 6v-1a2 2 0 0 1 2 -2h1"}),F("path",{d:"M10 3h1"}),F("path",{d:"M15 3h1a2 2 0 0 1 2 2v1"}))},screenshot:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M7 19a2 2 0 0 1 -2 -2"}),F("path",{d:"M5 13v-2"}),F("path",{d:"M5 7a2 2 0 0 1 2 -2"}),F("path",{d:"M11 5h2"}),F("path",{d:"M17 5a2 2 0 0 1 2 2"}),F("path",{d:"M19 11v2"}),F("path",{d:"M19 17v4"}),F("path",{d:"M21 19h-4"}),F("path",{d:"M13 19h-2"}))},arrowBackUp:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M9 14l-4 -4l4 -4"}),F("path",{d:"M5 10h11a4 4 0 1 1 0 8h-1"}))},arrowForwardUp:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M15 14l4 -4l-4 -4"}),F("path",{d:"M19 10h-11a4 4 0 1 0 0 8h1"}))},trash:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 7l16 0"}),F("path",{d:"M10 11l0 6"}),F("path",{d:"M14 11l0 6"}),F("path",{d:"M5 7l1 12a2 2 0 0 0 2 2h8a2 2 0 0 0 2 -2l1 -12"}),F("path",{d:"M9 7v-3a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v3"}))},deviceFloppy:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M6 4h10l4 4v10a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2"}),F("path",{d:"M12 14m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),F("path",{d:"M14 4l0 4l-6 0l0 -4"}))},pencilMarker:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none","stroke-linejoin":"round","stroke-linecap":"round","stroke-width":i,class:e.className,role:"img","aria-label":e.title},F("path",{d:"m9.109 16.275 8.856-8.097c.812-.743.87-2.014.127-2.826s-2.014-.869-2.826-.127L6.41 13.322l-.127 2.826zM13.79 6.575l2.7 2.952",stroke:"currentColor"}),F("path",{stroke:a,d:"M19.375 20.125c.569.063-4.05-.562-6.412-.437s-4.759 1.229-6.857 1.625c-1.764.687-3.404-.938-1.981-2.5"}))},circle:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r,s=e.secondaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:void 0===s?"none":s,stroke:a,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"}))},square:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r,s=e.secondaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:void 0===s?"none":s,stroke:a,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M3 3m0 2a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2z"}))},line:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2.2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M20 4l-16 16"}))},lineArrow:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2.2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M20 4l-16 16"}),F("path",{d:"M16 3h5v5"}))},polygon:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r,s=e.secondaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:void 0===s?"none":s,stroke:a,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M13.163 2.168l8.021 5.828c.694 .504 .984 1.397 .719 2.212l-3.064 9.43a1.978 1.978 0 0 1 -1.881 1.367h-9.916a1.978 1.978 0 0 1 -1.881 -1.367l-3.064 -9.43a1.978 1.978 0 0 1 .719 -2.212l8.021 -5.828a1.978 1.978 0 0 1 2.326 0z"}))},zigzag:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{d:"M12 2.4L21.36 11.76L2.64 12.24L12 21.6"}))},text:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M6.5 15.5m-3.5 0a3.5 3.5 0 1 0 7 0a3.5 3.5 0 1 0 -7 0"}),F("path",{d:"M14 19v-10.5a3.5 3.5 0 0 1 7 0v10.5"}),F("path",{d:"M14 13h7"}),F("path",{d:"M10 12v7"}))},italic:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M11 5l6 0"}),F("path",{d:"M7 19l6 0"}),F("path",{d:"M14 5l-4 14"}))},bold:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M7 5h6a3.5 3.5 0 0 1 0 7h-6z"}),F("path",{d:"M13 12h1a3.5 3.5 0 0 1 0 7h-7v-7"}))},alignLeft:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 6l16 0"}),F("path",{d:"M4 12l10 0"}),F("path",{d:"M4 18l14 0"}))},alignCenter:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 6l16 0"}),F("path",{d:"M8 12l8 0"}),F("path",{d:"M6 18l12 0"}))},alignRight:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 6l16 0"}),F("path",{d:"M10 12l10 0"}),F("path",{d:"M6 18l14 0"}))},alignTop:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M3 19v-14a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2z"}),F("path",{d:"M11 13h2"}),F("path",{d:"M9 10h6"}),F("path",{d:"M10 7h4"}))},alignMiddle:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M3 19v-14a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2z"}),F("path",{d:"M11 15h2"}),F("path",{d:"M9 12h6"}),F("path",{d:"M10 9h4"}))},alignBottom:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M3 19v-14a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2z"}),F("path",{d:"M11 17h2"}),F("path",{d:"M9 14h6"}),F("path",{d:"M10 11h4"}))},photo:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M15 8h.01"}),F("path",{d:"M3 6a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v12a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3v-12z"}),F("path",{d:"M3 16l5 -5c.928 -.893 2.072 -.893 3 0l5 5"}),F("path",{d:"M14 14l1 -1c.928 -.893 2.072 -.893 3 0l3 3"}))},pointer:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M7.904 17.563a1.2 1.2 0 0 0 2.228 .308l2.09 -3.093l4.907 4.907a1.067 1.067 0 0 0 1.509 0l1.047 -1.047a1.067 1.067 0 0 0 0 -1.509l-4.907 -4.907l3.113 -2.09a1.2 1.2 0 0 0 -.309 -2.228l-13.582 -3.904l3.904 13.563z"}))},redact:rf,redactArea:af,redactCombined:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r,s=e.secondaryColor,l=void 0===s?"currentColor":s;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:a,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M6 20h-1a2 2 0 0 1 -2 -2v-1"}),F("path",{d:"M3 13v-3"}),F("path",{d:"M20 13v-3"}),F("path",{d:"M3 6v-1a2 2 0 0 1 2 -2h1"}),F("path",{d:"M10 3h3"}),F("path",{d:"M17 3h1a2 2 0 0 1 2 2v1"}),F("path",{d:"M8 8h8"}),F("path",{d:"M12 8v7"}),F("defs",null,F("clipPath",{id:"redactCombinedClip"},F("rect",{x:"10",y:"18",width:"13",height:"6",rx:"2"}))),F("rect",{x:"10",y:"17",width:"13",height:"6",rx:"2",fill:"none"}),F("g",{"clip-path":"url(#redactCombinedClip)",stroke:l},F("path",{d:"M6 19l12 -12"}),F("path",{d:"M6 23l12 -12"}),F("path",{d:"M10 23l12 -12"}),F("path",{d:"M14 27l12 -12"}),F("path",{d:"M14 23l12 -12"})))},check:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M5 12l5 5l10 -10"}))},file:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r,s=e.className,l=e.title;return F("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:a,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:s,"aria-hidden":!l,role:l?"img":"presentation"},l&&F("title",null,l),F("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),F("polyline",{points:"14 2 14 8 20 8"}))},plus:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor,a=void 0===r?"currentColor":r,s=e.className,l=e.title;return F("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:a,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:s,"aria-hidden":!l,role:l?"img":"presentation"},l&&F("title",null,l),F("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),F("line",{x1:"5",y1:"12",x2:"19",y2:"12"}))},lock:function(e){var t=e.size,n=void 0===t?24:t,o=e.className;return F("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:void 0===o?"":o,style:e.style},F("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),F("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}))},unlock:function(e){var t=e.size,n=void 0===t?24:t,o=e.className;return F("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:void 0===o?"":o,style:e.style},F("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),F("path",{d:"M7 11V7a5 5 0 0 1 9.9-1"}))},alertTriangle:function(e){var t=e.size,n=void 0===t?24:t,o=e.className;return F("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:void 0===o?"":o,style:e.style},F("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),F("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),F("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"}))},eye:function(e){var t=e.size,n=void 0===t?24:t,o=e.className;return F("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:void 0===o?"":o,style:e.style},F("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),F("circle",{cx:"12",cy:"12",r:"3"}))},"eye-off":function(e){var t=e.size,n=void 0===t?24:t,o=e.className;return F("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:void 0===o?"":o,style:e.style},F("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"}),F("line",{x1:"1",y1:"1",x2:"23",y2:"23"}))},info:function(e){var t=e.size,n=void 0===t?24:t,o=e.className;return F("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:void 0===o?"":o,style:e.style},F("circle",{cx:"12",cy:"12",r:"10"}),F("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),F("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"}))},link:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M9 15l6 -6"}),F("path",{d:"M11 6l.463 -.536a5 5 0 0 1 7.071 7.072l-.534 .464"}),F("path",{d:"M13 18l-.397 .534a5.068 5.068 0 0 1 -7.127 0a4.972 4.972 0 0 1 0 -7.071l.524 -.463"}))},linkOff:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M9 15l3 -3m2 -2l1 -1"}),F("path",{d:"M11 6l.463 -.536a5 5 0 0 1 7.072 7.071l-.534 .464"}),F("path",{d:"M13 18l-.397 .534a5.068 5.068 0 0 1 -7.127 0a4.972 4.972 0 0 1 0 -7.071l.524 -.463"}),F("path",{d:"M3 3l18 18"}))},externalLink:function(e){return F("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e.className},F("path",{d:"M12 6h-6a2 2 0 0 0 -2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-6"}),F("path",{d:"M11 13l9 -9"}),F("path",{d:"M15 4h5v5"}))},marqueeSelect:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M17 20h6"}),F("path",{d:"M20 17v6"}),F("path",{d:"M4 13v-2"}),F("path",{d:"M4 6v-1a1 1 0 0 1 1 -1h1"}),F("path",{d:"M6 20h-1a1 1 0 0 1 -1 -1v-1"}),F("path",{d:"M11 4h2"}),F("path",{d:"M11 20h2"}),F("path",{d:"M18 4h1a1 1 0 0 1 1 1v1"}),F("path",{d:"M20 11v2"}))},group:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M3 5a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),F("path",{d:"M17 5a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),F("path",{d:"M3 19a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),F("path",{d:"M17 19a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),F("path",{d:"M5 7v10"}),F("path",{d:"M19 7v10"}),F("path",{d:"M7 5h10"}),F("path",{d:"M7 19h10"}),F("path",{d:"M8 8H12.8V11.2H16V16H11.2V12.8H8V8Z"}))},ungroup:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("rect",{x:"4",y:"4",width:"7",height:"7",rx:"1"}),F("rect",{x:"13",y:"13",width:"7",height:"7",rx:"1"}))},redactionSidebar:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 6a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z"}),F("path",{d:"M15 4v16"}),F("path",{d:"M7 8h5"}),F("path",{d:"M7 11h5"}),F("path",{d:"M7 14h4"}))},freeText:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M4 7v-2h12v2"}),F("path",{d:"M10 5v14"}),F("path",{d:"M12 19h-4"}),F("path",{d:"M15 13v-1h6v1"}),F("path",{d:"M18 12v7"}),F("path",{d:"M17 19h2"}))},insertText:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M3 7v-2h12v2"}),F("path",{d:"M9 5v14"}),F("path",{d:"M7 19h4"}),F("path",{d:"M18 15l2 2h-5"}),F("path",{d:"M18 19l2 -2"}))},replaceText:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M3 7v-2h12v2"}),F("path",{d:"M9 5v14"}),F("path",{d:"M7 19h4"}),F("g",{transform:"translate(-1, -3) rotate(180 19 18)"},F("path",{d:"M20 14l2 2h-3"}),F("path",{d:"M20 18l2 -2"}),F("path",{d:"M19 16a3 3 0 1 0 2 5.236"})))},message:function(e){var t=e.size,n=void 0===t?24:t,o=e.strokeWidth,i=void 0===o?2:o,r=e.primaryColor;return F("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:void 0===r?"currentColor":r,"stroke-width":i,"stroke-linecap":"round","stroke-linejoin":"round",class:e.className,role:"img","aria-label":e.title},F("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),F("path",{d:"M8 9h8",stroke:"currentColor"}),F("path",{d:"M8 13h6",stroke:"currentColor"}),F("path",{d:"M18 4a3 3 0 0 1 3 3v8a3 3 0 0 1 -3 3h-5l-5 3v-3h-2a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3h12"}))}},lf=new Map,cf=/^[MmZzLlHhVvCcSsQqTtAa0-9\s,.\-eE]+$/;function df(e){return cf.test(e.trim())}function uf(e,t){for(var n=function(e){var t,n;return"path"in e?{viewBox:e.viewBox||"0 0 24 24",paths:[{d:e.path,stroke:null!==(t=e.stroke)&&void 0!==t?t:"primary",fill:null!==(n=e.fill)&&void 0!==n?n:"none",strokeWidth:e.strokeWidth}],strokeLinecap:e.strokeLinecap||"round",strokeLinejoin:e.strokeLinejoin||"round",strokeWidth:e.strokeWidth}:{viewBox:e.viewBox||"0 0 24 24",paths:e.paths,strokeLinecap:e.strokeLinecap||"round",strokeLinejoin:e.strokeLinejoin||"round",strokeWidth:e.strokeWidth}}(t),o=0;o({x:e,y:e}),Cf={left:"right",right:"left",bottom:"top",top:"bottom"},kf={start:"end",end:"start"};function If(e,t,n){return yf(e,vf(t,n))}function Sf(e,t){return"function"==typeof e?e(t):e}function Af(e){return e.split("-")[0]}function Mf(e){return e.split("-")[1]}function Pf(e){return"x"===e?"y":"x"}function Df(e){return"y"===e?"height":"width"}const Rf=new Set(["top","bottom"]);function zf(e){return Rf.has(Af(e))?"y":"x"}function Tf(e){return Pf(zf(e))}function Ef(e){return e.replace(/start|end/g,e=>kf[e])}const _f=["left","right"],Nf=["right","left"],Lf=["top","bottom"],Of=["bottom","top"];function $f(e,t,n,o){const i=Mf(e);let r=function(e,t,n){switch(e){case"top":case"bottom":return n?t?Nf:_f:t?_f:Nf;case"left":case"right":return t?Lf:Of;default:return[]}}(Af(e),"start"===n,o);return i&&(r=r.map(e=>e+"-"+i),t&&(r=r.concat(r.map(Ef)))),r}function jf(e){return e.replace(/left|right|bottom|top/g,e=>Cf[e])}function Ff(e){return"number"!=typeof e?function(e){return{top:0,right:0,bottom:0,left:0,...e}}(e):{top:e,right:e,bottom:e,left:e}}function Uf(e){const{x:t,y:n,width:o,height:i}=e;return{width:o,height:i,top:n,left:t,right:t+o,bottom:n+i,x:t,y:n}}function Hf(e,t,n){let{reference:o,floating:i}=e;const r=zf(t),a=Tf(t),s=Df(a),l=Af(t),c="y"===r,d=o.x+o.width/2-i.width/2,u=o.y+o.height/2-i.height/2,h=o[s]/2-i[s]/2;let m;switch(l){case"top":m={x:d,y:o.y-i.height};break;case"bottom":m={x:d,y:o.y+o.height};break;case"right":m={x:o.x+o.width,y:u};break;case"left":m={x:o.x-i.width,y:u};break;default:m={x:o.x,y:o.y}}switch(Mf(t)){case"start":m[a]-=h*(n&&c?-1:1);break;case"end":m[a]+=h*(n&&c?-1:1)}return m}async function Wf(e,t){var n;void 0===t&&(t={});const{x:o,y:i,platform:r,rects:a,elements:s,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:u="floating",altBoundary:h=!1,padding:m=0}=Sf(t,e),g=Ff(m),p=s[h?"floating"===u?"reference":"floating":u],f=Uf(await r.getClippingRect({element:null==(n=await(null==r.isElement?void 0:r.isElement(p)))||n?p:p.contextElement||await(null==r.getDocumentElement?void 0:r.getDocumentElement(s.floating)),boundary:c,rootBoundary:d,strategy:l})),v="floating"===u?{x:o,y:i,width:a.floating.width,height:a.floating.height}:a.reference,y=await(null==r.getOffsetParent?void 0:r.getOffsetParent(s.floating)),b=await(null==r.isElement?void 0:r.isElement(y))&&await(null==r.getScale?void 0:r.getScale(y))||{x:1,y:1},w=Uf(r.convertOffsetParentRelativeRectToViewportRelativeRect?await r.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:v,offsetParent:y,strategy:l}):v);return{top:(f.top-w.top+g.top)/b.y,bottom:(w.bottom-f.bottom+g.bottom)/b.y,left:(f.left-w.left+g.left)/b.x,right:(w.right-f.right+g.right)/b.x}}const Bf=new Set(["left","top"]);function qf(){return"undefined"!=typeof window}function Gf(e){return Zf(e)?(e.nodeName||"").toLowerCase():"#document"}function Vf(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Kf(e){var t;return null==(t=(Zf(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function Zf(e){return!!qf()&&(e instanceof Node||e instanceof Vf(e).Node)}function Yf(e){return!!qf()&&(e instanceof Element||e instanceof Vf(e).Element)}function Xf(e){return!!qf()&&(e instanceof HTMLElement||e instanceof Vf(e).HTMLElement)}function Qf(e){return!(!qf()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Vf(e).ShadowRoot)}const Jf=new Set(["inline","contents"]);function ev(e){const{overflow:t,overflowX:n,overflowY:o,display:i}=hv(e);return/auto|scroll|overlay|hidden|clip/.test(t+o+n)&&!Jf.has(i)}const tv=new Set(["table","td","th"]);function nv(e){return tv.has(Gf(e))}const ov=[":popover-open",":modal"];function iv(e){return ov.some(t=>{try{return e.matches(t)}catch(e){return!1}})}const rv=["transform","translate","scale","rotate","perspective"],av=["transform","translate","scale","rotate","perspective","filter"],sv=["paint","layout","strict","content"];function lv(e){const t=cv(),n=Yf(e)?hv(e):e;return rv.some(e=>!!n[e]&&"none"!==n[e])||!!n.containerType&&"normal"!==n.containerType||!t&&!!n.backdropFilter&&"none"!==n.backdropFilter||!t&&!!n.filter&&"none"!==n.filter||av.some(e=>(n.willChange||"").includes(e))||sv.some(e=>(n.contain||"").includes(e))}function cv(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("-webkit-backdrop-filter","none")}const dv=new Set(["html","body","#document"]);function uv(e){return dv.has(Gf(e))}function hv(e){return Vf(e).getComputedStyle(e)}function mv(e){return Yf(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function gv(e){if("html"===Gf(e))return e;const t=e.assignedSlot||e.parentNode||Qf(e)&&e.host||Kf(e);return Qf(t)?t.host:t}function pv(e){const t=gv(e);return uv(t)?e.ownerDocument?e.ownerDocument.body:e.body:Xf(t)&&ev(t)?t:pv(t)}function fv(e,t,n){var o;void 0===t&&(t=[]),void 0===n&&(n=!0);const i=pv(e),r=i===(null==(o=e.ownerDocument)?void 0:o.body),a=Vf(i);if(r){const e=vv(a);return t.concat(a,a.visualViewport||[],ev(i)?i:[],e&&n?fv(e):[])}return t.concat(i,fv(i,[],n))}function vv(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function yv(e){const t=hv(e);let n=parseFloat(t.width)||0,o=parseFloat(t.height)||0;const i=Xf(e),r=i?e.offsetWidth:n,a=i?e.offsetHeight:o,s=bf(n)!==r||bf(o)!==a;return s&&(n=r,o=a),{width:n,height:o,$:s}}function bv(e){return Yf(e)?e:e.contextElement}function wv(e){const t=bv(e);if(!Xf(t))return xf(1);const n=t.getBoundingClientRect(),{width:o,height:i,$:r}=yv(t);let a=(r?bf(n.width):n.width)/o,s=(r?bf(n.height):n.height)/i;return a&&Number.isFinite(a)||(a=1),s&&Number.isFinite(s)||(s=1),{x:a,y:s}}const xv=xf(0);function Cv(e){const t=Vf(e);return cv()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:xv}function kv(e,t,n,o){void 0===t&&(t=!1),void 0===n&&(n=!1);const i=e.getBoundingClientRect(),r=bv(e);let a=xf(1);t&&(o?Yf(o)&&(a=wv(o)):a=wv(e));const s=function(e,t,n){return void 0===t&&(t=!1),!(!n||t&&n!==Vf(e))&&t}(r,n,o)?Cv(r):xf(0);let l=(i.left+s.x)/a.x,c=(i.top+s.y)/a.y,d=i.width/a.x,u=i.height/a.y;if(r){const e=Vf(r),t=o&&Yf(o)?Vf(o):o;let n=e,i=vv(n);for(;i&&o&&t!==n;){const e=wv(i),t=i.getBoundingClientRect(),o=hv(i),r=t.left+(i.clientLeft+parseFloat(o.paddingLeft))*e.x,a=t.top+(i.clientTop+parseFloat(o.paddingTop))*e.y;l*=e.x,c*=e.y,d*=e.x,u*=e.y,l+=r,c+=a,n=Vf(i),i=vv(n)}}return Uf({width:d,height:u,x:l,y:c})}function Iv(e,t){const n=mv(e).scrollLeft;return t?t.left+n:kv(Kf(e)).left+n}function Sv(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-Iv(e,n),y:n.top+t.scrollTop}}const Av=new Set(["absolute","fixed"]);function Mv(e,t,n){let o;if("viewport"===t)o=function(e,t){const n=Vf(e),o=Kf(e),i=n.visualViewport;let r=o.clientWidth,a=o.clientHeight,s=0,l=0;if(i){r=i.width,a=i.height;const e=cv();(!e||e&&"fixed"===t)&&(s=i.offsetLeft,l=i.offsetTop)}const c=Iv(o);if(c<=0){const e=o.ownerDocument,t=e.body,n=getComputedStyle(t),i="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,a=Math.abs(o.clientWidth-t.clientWidth-i);a<=25&&(r-=a)}else c<=25&&(r+=c);return{width:r,height:a,x:s,y:l}}(e,n);else if("document"===t)o=function(e){const t=Kf(e),n=mv(e),o=e.ownerDocument.body,i=yf(t.scrollWidth,t.clientWidth,o.scrollWidth,o.clientWidth),r=yf(t.scrollHeight,t.clientHeight,o.scrollHeight,o.clientHeight);let a=-n.scrollLeft+Iv(e);const s=-n.scrollTop;return"rtl"===hv(o).direction&&(a+=yf(t.clientWidth,o.clientWidth)-i),{width:i,height:r,x:a,y:s}}(Kf(e));else if(Yf(t))o=function(e,t){const n=kv(e,!0,"fixed"===t),o=n.top+e.clientTop,i=n.left+e.clientLeft,r=Xf(e)?wv(e):xf(1);return{width:e.clientWidth*r.x,height:e.clientHeight*r.y,x:i*r.x,y:o*r.y}}(t,n);else{const n=Cv(e);o={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return Uf(o)}function Pv(e,t){const n=gv(e);return!(n===t||!Yf(n)||uv(n))&&("fixed"===hv(n).position||Pv(n,t))}function Dv(e,t,n){const o=Xf(t),i=Kf(t),r="fixed"===n,a=kv(e,!0,r,t);let s={scrollLeft:0,scrollTop:0};const l=xf(0);function c(){l.x=Iv(i)}if(o||!o&&!r)if(("body"!==Gf(t)||ev(i))&&(s=mv(t)),o){const e=kv(t,!0,r,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}else i&&c();r&&!o&&i&&c();const d=!i||o||r?xf(0):Sv(i,s);return{x:a.left+s.scrollLeft-l.x-d.x,y:a.top+s.scrollTop-l.y-d.y,width:a.width,height:a.height}}function Rv(e){return"static"===hv(e).position}function zv(e,t){if(!Xf(e)||"fixed"===hv(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Kf(e)===n&&(n=n.ownerDocument.body),n}function Tv(e,t){const n=Vf(e);if(iv(e))return n;if(!Xf(e)){let t=gv(e);for(;t&&!uv(t);){if(Yf(t)&&!Rv(t))return t;t=gv(t)}return n}let o=zv(e,t);for(;o&&nv(o)&&Rv(o);)o=zv(o,t);return o&&uv(o)&&Rv(o)&&!lv(o)?n:o||function(e){let t=gv(e);for(;Xf(t)&&!uv(t);){if(lv(t))return t;if(iv(t))return null;t=gv(t)}return null}(e)||n}const Ev={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:n,offsetParent:o,strategy:i}=e;const r="fixed"===i,a=Kf(o),s=!!t&&iv(t.floating);if(o===a||s&&r)return n;let l={scrollLeft:0,scrollTop:0},c=xf(1);const d=xf(0),u=Xf(o);if((u||!u&&!r)&&(("body"!==Gf(o)||ev(a))&&(l=mv(o)),Xf(o))){const e=kv(o);c=wv(o),d.x=e.x+o.clientLeft,d.y=e.y+o.clientTop}const h=!a||u||r?xf(0):Sv(a,l);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+d.x+h.x,y:n.y*c.y-l.scrollTop*c.y+d.y+h.y}},getDocumentElement:Kf,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:o,strategy:i}=e;const r=[..."clippingAncestors"===n?iv(t)?[]:function(e,t){const n=t.get(e);if(n)return n;let o=fv(e,[],!1).filter(e=>Yf(e)&&"body"!==Gf(e)),i=null;const r="fixed"===hv(e).position;let a=r?gv(e):e;for(;Yf(a)&&!uv(a);){const t=hv(a),n=lv(a);n||"fixed"!==t.position||(i=null),(r?!n&&!i:!n&&"static"===t.position&&i&&Av.has(i.position)||ev(a)&&!n&&Pv(e,a))?o=o.filter(e=>e!==a):i=t,a=gv(a)}return t.set(e,o),o}(t,this._c):[].concat(n),o],a=r[0],s=r.reduce((e,n)=>{const o=Mv(t,n,i);return e.top=yf(o.top,e.top),e.right=vf(o.right,e.right),e.bottom=vf(o.bottom,e.bottom),e.left=yf(o.left,e.left),e},Mv(t,a,i));return{width:s.right-s.left,height:s.bottom-s.top,x:s.left,y:s.top}},getOffsetParent:Tv,getElementRects:async function(e){const t=this.getOffsetParent||Tv,n=this.getDimensions,o=await n(e.floating);return{reference:Dv(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:o.width,height:o.height}}},getClientRects:function(e){return Array.from(e.getClientRects())},getDimensions:function(e){const{width:t,height:n}=yv(e);return{width:t,height:n}},getScale:wv,isElement:Yf,isRTL:function(e){return"rtl"===hv(e).direction}};function _v(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Nv(e,t,n,o){void 0===o&&(o={});const{ancestorScroll:i=!0,ancestorResize:r=!0,elementResize:a="function"==typeof ResizeObserver,layoutShift:s="function"==typeof IntersectionObserver,animationFrame:l=!1}=o,c=bv(e),d=i||r?[...c?fv(c):[],...fv(t)]:[];d.forEach(e=>{i&&e.addEventListener("scroll",n,{passive:!0}),r&&e.addEventListener("resize",n)});const u=c&&s?function(e,t){let n,o=null;const i=Kf(e);function r(){var e;clearTimeout(n),null==(e=o)||e.disconnect(),o=null}return function a(s,l){void 0===s&&(s=!1),void 0===l&&(l=1),r();const c=e.getBoundingClientRect(),{left:d,top:u,width:h,height:m}=c;if(s||t(),!h||!m)return;const g={rootMargin:-wf(u)+"px "+-wf(i.clientWidth-(d+h))+"px "+-wf(i.clientHeight-(u+m))+"px "+-wf(d)+"px",threshold:yf(0,vf(1,l))||1};let p=!0;function f(t){const o=t[0].intersectionRatio;if(o!==l){if(!p)return a();o?a(!1,o):n=setTimeout(()=>{a(!1,1e-7)},1e3)}1!==o||_v(c,e.getBoundingClientRect())||a(),p=!1}try{o=new IntersectionObserver(f,{...g,root:i.ownerDocument})}catch(e){o=new IntersectionObserver(f,g)}o.observe(e)}(!0),r}(c,n):null;let h,m=-1,g=null;a&&(g=new ResizeObserver(e=>{let[o]=e;o&&o.target===c&&g&&(g.unobserve(t),cancelAnimationFrame(m),m=requestAnimationFrame(()=>{var e;null==(e=g)||e.observe(t)})),n()}),c&&!l&&g.observe(c),g.observe(t));let p=l?kv(e):null;return l&&function t(){const o=kv(e);p&&!_v(p,o)&&n();p=o,h=requestAnimationFrame(t)}(),n(),()=>{var e;d.forEach(e=>{i&&e.removeEventListener("scroll",n),r&&e.removeEventListener("resize",n)}),null==u||u(),null==(e=g)||e.disconnect(),g=null,l&&cancelAnimationFrame(h)}}const Lv=function(e){return void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var n,o;const{x:i,y:r,placement:a,middlewareData:s}=t,l=await async function(e,t){const{placement:n,platform:o,elements:i}=e,r=await(null==o.isRTL?void 0:o.isRTL(i.floating)),a=Af(n),s=Mf(n),l="y"===zf(n),c=Bf.has(a)?-1:1,d=r&&l?-1:1,u=Sf(t,e);let{mainAxis:h,crossAxis:m,alignmentAxis:g}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return s&&"number"==typeof g&&(m="end"===s?-1*g:g),l?{x:m*d,y:h*c}:{x:h*c,y:m*d}}(t,e);return a===(null==(n=s.offset)?void 0:n.placement)&&null!=(o=s.arrow)&&o.alignmentOffset?{}:{x:i+l.x,y:r+l.y,data:{...l,placement:a}}}}},Ov=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:o,placement:i,platform:r}=t,{mainAxis:a=!0,crossAxis:s=!1,limiter:l={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...c}=Sf(e,t),d={x:n,y:o},u=await r.detectOverflow(t,c),h=zf(Af(i)),m=Pf(h);let g=d[m],p=d[h];if(a){const e="y"===m?"bottom":"right";g=If(g+u["y"===m?"top":"left"],g,g-u[e])}if(s){const e="y"===h?"bottom":"right";p=If(p+u["y"===h?"top":"left"],p,p-u[e])}const f=l.fn({...t,[m]:g,[h]:p});return{...f,data:{x:f.x-n,y:f.y-o,enabled:{[m]:a,[h]:s}}}}}},$v=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,o;const{placement:i,middlewareData:r,rects:a,initialPlacement:s,platform:l,elements:c}=t,{mainAxis:d=!0,crossAxis:u=!0,fallbackPlacements:h,fallbackStrategy:m="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:p=!0,...f}=Sf(e,t);if(null!=(n=r.arrow)&&n.alignmentOffset)return{};const v=Af(i),y=zf(s),b=Af(s)===s,w=await(null==l.isRTL?void 0:l.isRTL(c.floating)),x=h||(b||!p?[jf(s)]:function(e){const t=jf(e);return[Ef(e),t,Ef(t)]}(s)),C="none"!==g;!h&&C&&x.push(...$f(s,p,g,w));const k=[s,...x],I=await l.detectOverflow(t,f),S=[];let A=(null==(o=r.flip)?void 0:o.overflows)||[];if(d&&S.push(I[v]),u){const e=function(e,t,n){void 0===n&&(n=!1);const o=Mf(e),i=Tf(e),r=Df(i);let a="x"===i?o===(n?"end":"start")?"right":"left":"start"===o?"bottom":"top";return t.reference[r]>t.floating[r]&&(a=jf(a)),[a,jf(a)]}(i,a,w);S.push(I[e[0]],I[e[1]])}if(A=[...A,{placement:i,overflows:S}],!S.every(e=>e<=0)){var M,P;const e=((null==(M=r.flip)?void 0:M.index)||0)+1,t=k[e];if(t){if(!("alignment"===u&&y!==zf(t))||A.every(e=>zf(e.placement)!==y||e.overflows[0]>0))return{data:{index:e,overflows:A},reset:{placement:t}}}let n=null==(P=A.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:P.placement;if(!n)switch(m){case"bestFit":{var D;const e=null==(D=A.filter(e=>{if(C){const t=zf(e.placement);return t===y||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:D[0];e&&(n=e);break}case"initialPlacement":n=s}if(i!==n)return{reset:{placement:n}}}return{}}}},jv=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:o,placement:i,rects:r,platform:a,elements:s,middlewareData:l}=t,{element:c,padding:d=0}=Sf(e,t)||{};if(null==c)return{};const u=Ff(d),h={x:n,y:o},m=Tf(i),g=Df(m),p=await a.getDimensions(c),f="y"===m,v=f?"top":"left",y=f?"bottom":"right",b=f?"clientHeight":"clientWidth",w=r.reference[g]+r.reference[m]-h[m]-r.floating[g],x=h[m]-r.reference[m],C=await(null==a.getOffsetParent?void 0:a.getOffsetParent(c));let k=C?C[b]:0;k&&await(null==a.isElement?void 0:a.isElement(C))||(k=s.floating[b]||r.floating[g]);const I=w/2-x/2,S=k/2-p[g]/2-1,A=vf(u[v],S),M=vf(u[y],S),P=A,D=k-p[g]-M,R=k/2-p[g]/2+I,z=If(P,R,D),T=!l.arrow&&null!=Mf(i)&&R!==z&&r.reference[g]/2-(R{const o=new Map,i={platform:Ev,...n},r={...i.platform,_c:o};return(async(e,t,n)=>{const{placement:o="bottom",strategy:i="absolute",middleware:r=[],platform:a}=n,s=r.filter(Boolean),l=await(null==a.isRTL?void 0:a.isRTL(t));let c=await a.getElementRects({reference:e,floating:t,strategy:i}),{x:d,y:u}=Hf(c,o,l),h=o,m={},g=0;for(let n=0;n=75?"full":o<=25?"closed":"half",C.current={y:e,height:o,time:Date.now(),state:t},k.current={y:e,time:Date.now()},f(0),t!==c&&d(t),m(!0)}},[s,c]),A=ze(function(e){if(h){var t=s.clientHeight,n=(C.current.y-e)/t*100,o=Math.max(0,Math.min(100,C.current.height+n));k.current={y:e,time:Date.now()};var i=I(C.current.state);f(o-i)}},[h,s]),M=ze(function(){if(h){if(Math.abs(C.current.y-k.current.y)<5)return m(!1),void f(0);var e=I(C.current.state)+p,t=Date.now()-k.current.time,n=k.current.y-C.current.y,o=function(e,t){return Math.abs(t)>.5?t>0?e>50?"half":"closed":e<50?"half":"full":e>=75?"full":e<=25?"closed":"half"}(e,t>0?n/t:0);"closed"===o?(d("closed"),m(!1),f(0),i()):(m(!1),f(0),d(o))}},[h,p,i]),P=ze(function(e){S(e.touches[0].clientY)},[S]),D=ze(function(e){h&&(e.cancelable&&e.preventDefault(),A(e.touches[0].clientY))},[h,A]),R=ze(function(){M()},[M]),z=ze(function(e){e.preventDefault(),S(e.clientY)},[S]);if(Me(function(){if(h){var e=function(e){A(e.clientY)},t=function(){M()};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",t),function(){document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",t)}}},[h,A,M]),!b)return null;var T=I(h?C.current.state:c),E=h?Math.max(0,Math.min(100,T+p)):T,_=.3*Math.min(E/50,1);return F(H,null,F("div",{className:"bg-bg-overlay absolute inset-0 z-40 transition-opacity duration-300 ".concat(0===E?"pointer-events-none":""),style:{opacity:_},onClick:i}),F("div",{ref:x,className:"bg-bg-surface absolute inset-x-0 bottom-0 z-50 flex flex-col rounded-t-2xl shadow-2xl ".concat(h?"":"transition-[height] duration-300 ease-out"),style:{height:"".concat(E,"%")},"data-sidebar-id":t.id},F("div",{className:"flex flex-shrink-0 cursor-grab touch-none items-center justify-center py-3 active:cursor-grabbing",onTouchStart:P,onTouchMove:D,onTouchEnd:R,onMouseDown:z},F("div",{className:"bg-border-default h-1.5 w-12 rounded-full"})),F("div",{className:"min-h-0 flex-1 overflow-hidden"},"tabs"===a.type&&F(ny,{content:a,documentId:n,renderCustomComponent:r}),"component"===a.type&&F(H,null,r(a.componentId,n,{})))))}function ny(e){var t,n=e.content,o=e.documentId,i=e.renderCustomComponent,r=v(Se((null===(t=n.tabs[0])||void 0===t?void 0:t.id)||""),2),a=r[0],s=r[1];return F("div",{className:"flex h-full flex-1 flex-col"},F("div",{role:"tablist",className:"bg-bg-surface mx-4 my-4 flex flex-shrink-0 overflow-hidden"},n.tabs.map(function(e,t,n){var o=a===e.id,i=0===t,r=t===n.length-1;return F("button",{key:e.id,role:"tab","aria-selected":o,tabIndex:o?0:-1,onClick:function(){return s(e.id)},className:"relative flex h-7 flex-1 cursor-pointer items-center justify-center border outline-none transition-colors ".concat(i?"rounded-l-md":""," ").concat(r?"rounded-r-md":""," ").concat(r?"":"border-r-0"," ").concat(o?"border-accent bg-accent text-fg-on-accent":"border-border-default text-fg-secondary hover:bg-interactive-hover")},e.icon&&F(gf,{icon:e.icon,className:"h-5 w-5"}))})),F("div",{className:"min-h-0 flex-1 overflow-auto"},n.tabs.filter(function(e){return e.id===a}).map(function(e){return F(H,{key:e.id},i(e.componentId,o,{}))})))}function oy(e){var t=e.schema,n=e.documentId,o=e.anchorEl,i=e.onClose,r=ta().getContainer,a=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:768,n=v(Se(function(){var n=e();return!!n&&n.clientWidth{const{provides:e}=Qr();return(null==e?void 0:e.getSchema())??null})(),c=v(Se([{menuId:t.id,schema:t,title:void 0}]),2),d=c[0],u=c[1];Me(function(){u([{menuId:t.id,schema:t,title:void 0}])},[t]);var h=d[d.length-1],m=ze(function(e,t){if(l){var n=l.menus[e];n?u(function(o){return[].concat(y(o),[{menuId:e,schema:n,title:t}])}):console.warn("Submenu schema not found: ".concat(e))}},[l]),g=ze(function(){d.length>1&&u(function(e){return e.slice(0,-1)})},[d.length]);return h?a&&s?Pu(F(iy,{currentMenu:h,menuStack:d,documentId:n,onClose:i,onNavigateBack:g,onNavigateToSubmenu:m,container:s}),s):F(ry,{currentMenu:h,documentId:n,anchorEl:o,onClose:i,onNavigateToSubmenu:m}):null}function iy(e){var t=e.currentMenu,n=e.menuStack,o=e.documentId,i=e.onClose,r=e.onNavigateBack,a=e.onNavigateToSubmenu,s=e.container,l=v(Se(!1),2),c=l[0],d=l[1],u=v(Se(!1),2),m=u[0],g=u[1],p=v(Se(0),2),f=p[0],y=p[1],b=De(null),w=De(null),x=De({isDragging:!1,startY:0,currentY:0,startTime:0,sheetHeight:0});Me(function(){d(!0),requestAnimationFrame(function(){requestAnimationFrame(function(){g(!0)})})},[]);var C=v(Se(null),2),k=C[0],I=C[1];Me(function(){if(w.current){var e=(n.length>1?60:0)+w.current.scrollHeight+24,t=.8*s.clientHeight;I(Math.min(e,t))}},[t,n.length,s]);var S=ze(function(){g(!1),setTimeout(function(){d(!1),i()},300)},[i]),A=ze(function(e){b.current&&(x.current={isDragging:!0,startY:e,currentY:e,startTime:Date.now(),sheetHeight:b.current.offsetHeight})},[]),M=ze(function(e){if(x.current.isDragging){var t=e-x.current.startY,n=Math.max(0,t);x.current.currentY=e,y(n)}},[]),P=ze(function(){if(x.current.isDragging){var e=x.current,t=e.startY,n=e.currentY,o=e.startTime,i=e.sheetHeight,r=Math.abs(t-n);if(x.current.isDragging=!1,r<5)y(0);else{var a=n-t,s=a/i*100,l=Date.now()-o;s>30||(l>0?a/l:0)>.5?S():y(0)}}},[S]),D=ze(function(e){A(e.touches[0].clientY)},[A]),R=ze(function(e){x.current.isDragging&&e.cancelable&&e.preventDefault(),M(e.touches[0].clientY)},[M]),z=ze(function(){P()},[P]),T=ze(function(e){e.preventDefault(),A(e.clientY)},[A]);if(Me(function(){if(x.current.isDragging){var e=function(e){return M(e.clientY)},t=function(){return P()};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",t),function(){document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",t)}}},[M,P]),Me(function(){var e=function(e){"Escape"===e.key&&S()};return document.addEventListener("keydown",e),function(){return document.removeEventListener("keydown",e)}},[S]),!c)return null;var E=m?f:k||400;return F(H,null,F("div",{className:"bg-bg-overlay absolute inset-0 z-40 transition-opacity duration-300 ".concat(m?"opacity-100":"opacity-0"),onClick:S}),F("div",h({ref:b,className:"bg-bg-surface absolute inset-x-0 bottom-0 z-50 flex flex-col rounded-t-2xl shadow-2xl ".concat(x.current.isDragging?"":"transition-transform duration-300 ease-out"),style:{maxHeight:"80%",transform:"translateY(".concat(E,"px)")}},Hr(t.schema)),F("div",{className:"flex flex-shrink-0 cursor-grab touch-none items-center justify-center py-3 active:cursor-grabbing",onTouchStart:D,onTouchMove:R,onTouchEnd:z,onMouseDown:T},F("div",{className:"bg-border-default h-1.5 w-12 rounded-full"})),n.length>1&&F("div",{className:"border-border-subtle flex items-center gap-3 border-b px-4 pb-3"},F("button",{onClick:r,className:"hover:bg-interactive-hover rounded-full p-1"},F(ef,{className:"h-5 w-5"})),F("h3",{className:"text-fg-primary font-semibold"},t.title||"Menu")),F("div",{ref:w,className:"flex-1 overflow-y-auto py-2"},t.schema.items.map(function(e){return F(ay,{key:e.id,item:e,documentId:o,onClose:S,isMobile:!0,onNavigateToSubmenu:a})}))))}function ry(e){var t=e.currentMenu,n=e.documentId,o=e.anchorEl,i=e.onClose,r=e.onNavigateToSubmenu,a=De(null),s=v(Se(null),2),l=s[0],c=s[1];Me(function(){if(o){var e=function(){var e,t=o.getBoundingClientRect(),n=(null===(e=a.current)||void 0===e?void 0:e.offsetWidth)||200,i=t.bottom+4,r=t.left;r+n>window.innerWidth&&(r=window.innerWidth-n-8),r<8&&(r=8),c({top:i,left:r})};return e(),window.addEventListener("scroll",e),window.addEventListener("resize",e),function(){window.removeEventListener("scroll",e),window.removeEventListener("resize",e)}}},[o]),Me(function(){var e=function(e){if(a.current){var t=e.composedPath(),n=t.includes(a.current),r=o&&t.includes(o);n||r||i()}},t=setTimeout(function(){document.addEventListener("mousedown",e)},0);return function(){clearTimeout(t),document.removeEventListener("mousedown",e)}},[i,o]),Me(function(){var e=function(e){"Escape"===e.key&&i()};return document.addEventListener("keydown",e),function(){return document.removeEventListener("keydown",e)}},[i]);var d=l?{position:"fixed",top:"".concat(l.top,"px"),left:"".concat(l.left,"px"),zIndex:1e3}:{display:"none"};return F("div",h(h({ref:a},Hr(t.schema)),{},{className:"border-border-default bg-bg-elevated min-w-[200px] rounded-lg border py-2 shadow-lg",style:d}),t.schema.items.map(function(e){return F(ay,{key:e.id,item:e,documentId:n,onClose:i,isMobile:!1,onNavigateToSubmenu:r})}))}function ay(e){var t=e.item,n=e.documentId,o=e.onClose,i=e.isMobile,r=e.onNavigateToSubmenu;switch(t.type){case"command":return F(sy,{item:t,documentId:n,onClose:o,isMobile:i});case"submenu":return F(ly,{item:t,documentId:n,isMobile:i,onNavigateToSubmenu:r});case"divider":return F("div",h({},Hr(t)),F("hr",{className:"border-border-subtle my-2"}));case"section":return F(cy,{item:t,documentId:n,onClose:o,isMobile:i,onNavigateToSubmenu:r});default:return null}}function sy(e){var t,n,o=e.item,i=e.documentId,r=e.onClose,a=e.isMobile,s=Ra(o.commandId,i);if(!s||!s.visible)return null;var l,c,d=function(){s.disabled||(s.execute(),r())};return a?F("button",h(h({},Hr(o)),{},{onClick:d,disabled:s.disabled,className:"active:bg-interactive-active flex w-full items-center gap-3 px-4 py-3 text-left text-base transition-colors ".concat(s.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"," ").concat(s.active?"bg-interactive-selected text-accent":"text-fg-secondary"),role:"menuitem"}),s.icon&&F(gf,{icon:s.icon,className:"h-5 w-5",primaryColor:null===(l=s.iconProps)||void 0===l?void 0:l.primaryColor,secondaryColor:null===(c=s.iconProps)||void 0===c?void 0:c.secondaryColor}),F("span",{className:"flex-1"},s.label)):F("button",h(h({},Hr(o)),{},{onClick:d,disabled:s.disabled,className:"flex w-full items-center justify-between gap-2 px-4 py-1 text-left ".concat(s.disabled?"pointer-events-none cursor-not-allowed opacity-50":"cursor-pointer"," ").concat(s.active&&!s.disabled?"bg-accent text-fg-on-accent":"text-fg-muted hover:bg-accent hover:text-fg-on-accent"),role:"menuitem"}),F("div",{className:"flex items-center gap-2"},F("div",{className:"flex h-6 w-6 items-center justify-center"},s.icon&&F(gf,{icon:s.icon,className:"h-6 w-6",primaryColor:null===(t=s.iconProps)||void 0===t?void 0:t.primaryColor,secondaryColor:null===(n=s.iconProps)||void 0===n?void 0:n.secondaryColor})),F("span",{className:"text-sm"},s.label)))}function ly(e){var t=e.item,n=e.documentId,o=e.isMobile,i=e.onNavigateToSubmenu,r=Ha(n).translate,a=t.labelKey?r(t.labelKey):t.label||"",s=function(){return i(t.menuId,a)};return o?F("button",h(h({},Hr(t)),{},{onClick:s,className:"text-fg-secondary active:bg-interactive-active flex w-full cursor-pointer items-center gap-3 px-4 py-3 text-left text-base transition-colors",role:"menuitem"}),F("span",{className:"flex-1"},a),F(Jp,{className:"h-4 w-4"})):F("button",h(h({},Hr(t)),{},{onClick:s,className:"text-fg-muted hover:bg-accent hover:text-fg-on-accent flex w-full cursor-pointer items-center justify-between gap-2 px-4 py-1 text-left",role:"menuitem"}),F("span",{className:"text-sm"},a),F(Jp,{className:"h-6 w-6"}))}function cy(e){var t=e.item,n=e.documentId,o=e.onClose,i=e.isMobile,r=e.onNavigateToSubmenu,a=Ha(n).translate,s=t.labelKey?a(t.labelKey):t.label||"";return F("div",h({},Hr(t)),F("div",{className:"text-fg-secondary px-4 py-3 text-xs font-medium uppercase"},s),t.items.map(function(e){return F(ay,{key:e.id,item:e,documentId:n,onClose:o,isMobile:i,onNavigateToSubmenu:r})}))}function dy(e){var t=e.schema,n=e.documentId,o=e.isOpen,i=e.onClose,r=e.onExited,a=e.modalProps,s=t.content,l=la().renderCustomComponent;return"component"!==s.type?(console.warn("SchemaModal only supports component content type, got: ".concat(s.type)),null):F(H,null,l(s.componentId,n,h({isOpen:o,onClose:i,onExited:r},a)))}function uy(e){var t=e.documentId;e.onClose;var n=Ri(t),o=n.state,i=n.provides;return F("div",{className:"flex h-full flex-1 flex-col"},F("div",{className:"flex-1 overflow-hidden"},F(Cc,{documentId:t,style:{width:"100%",height:"100%"}},function(e){return F("div",{key:e.pageIndex,style:{position:"absolute",width:"100%",height:e.wrapperHeight,top:e.top,display:"flex",flexDirection:"column",alignItems:"center",cursor:"pointer"},onClick:function(){var t;null==i||null===(t=i.scrollToPage)||void 0===t||t.call(i,{pageNumber:e.pageIndex+1})}},F("div",{style:{width:e.width,height:e.height,border:"2px solid ".concat(o.currentPage===e.pageIndex+1?"var(--ep-accent-primary)":"var(--ep-border-default)"),borderRadius:"4px",overflow:"hidden",boxShadow:o.currentPage===e.pageIndex+1?"0 0 0 2px var(--ep-interactive-focus-ring)":"none"}},F(kc,{documentId:t,meta:e,style:{width:"100%",height:"100%"}})),F("div",{style:{height:e.labelHeight,display:"flex",alignItems:"center",justifyContent:"center",marginTop:"4px"}},F("span",{className:"text-fg-secondary text-xs"},e.pageIndex+1)))})))}function hy(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:300,n=v(Se(e),2),o=n[0],i=n[1];return Me(function(){var n=window.setTimeout(function(){return i(e)},t);return function(){return clearTimeout(n)}},[e,t]),o}var my=function(e){var t=e.label,n=e.checked,o=e.onChange;return F("label",{className:"text-fg-secondary inline-flex cursor-pointer select-none items-center gap-2 text-xs font-medium"},F("input",{type:"checkbox",checked:n,onChange:function(e){return o(e.target.checked)},className:"border-border-default bg-bg-input checked:border-accent checked:bg-accent peer h-4 w-4 shrink-0 appearance-none rounded-[3px] border transition-all"}),F("svg",{viewBox:"0 0 24 24",className:"/* fine-tune centering */ text-fg-on-accent pointer-events-none absolute h-3.5 w-3.5 translate-x-[1px] translate-y-[1px] opacity-0 peer-checked:opacity-100",fill:"none",stroke:"currentColor",strokeWidth:3,strokeLinecap:"round",strokeLinejoin:"round"},F("polyline",{points:"20 6 9 17 4 12"})),t)},gy=function(e){var t=e.hit,n=e.onClick,o=e.active,i=De(null);return Me(function(){o&&i.current&&i.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[o]),F("button",{ref:i,onClick:n,className:"w-full rounded border p-2 text-left text-sm transition-colors ".concat(o?"border-accent bg-accent-light text-fg-primary":"border-border-subtle bg-bg-surface text-fg-secondary hover:bg-interactive-hover")},F("span",null,t.context.truncatedLeft&&"… ",t.context.before,F("span",{className:"text-accent font-bold"},t.context.match),t.context.after,t.context.truncatedRight&&" …"))};function py(e){var t=e.documentId;e.onClose;var n=(e=>{const{provides:t}=Hs(),[n,o]=Se(Ns),i=Re(()=>null==t?void 0:t.forDocument(e),[t,e]);return Me(()=>{if(i)return o(i.getState()),i.onStateChange(e=>o(e));o(Ns)},[i]),{state:n,provides:i??null}})(t),o=n.state,i=n.provides,r=Di().provides,a=Ha(t).translate,s=De(null),l=v(Se(""),2),c=l[0],d=l[1];Me(function(){},[]),Me(function(){o.query&&!c&&d(o.query)},[o.query]),Me(function(){void 0!==o.activeResultIndex&&o.activeResultIndex>=0&&m(o.activeResultIndex)},[o.activeResultIndex]);var u=hy(c,300);Me(function(){u!==o.query&&(null==i||i.searchAllPages(u))},[u,i,o.query]);var h=function(e,t){t?null==i||i.setFlags([].concat(y(o.flags),[e])):null==i||i.setFlags(o.flags.filter(function(t){return t!==e}))},m=function(e){var n,i=o.results[e];if(i){var a=i.rects.reduce(function(e,t){return{x:Math.min(e.x,t.origin.x),y:Math.min(e.y,t.origin.y)}},{x:1/0,y:1/0});null==r||null===(n=r.forDocument(t))||void 0===n||n.scrollToPage({pageNumber:i.pageIndex+1,pageCoordinates:a,alignX:50,alignY:25})}},g=function(e){var t={};return e.forEach(function(e,n){t[e.pageIndex]||(t[e.pageIndex]=[]),t[e.pageIndex].push({hit:e,index:n})}),t}(o.results);return F("div",{className:"bg-bg-surface flex h-full flex-col"},F("div",{className:"p-4"},F("div",{className:"relative"},F("div",{className:"pointer-events-none absolute inset-y-0 left-0 flex items-center pl-2"},F(nf,{className:"text-fg-muted h-4 w-4"})),F("input",{ref:s,type:"text",placeholder:a("search.placeholder"),value:c,onInput:function(e){var t=e.target;d(t.value)},className:"border-border-default bg-bg-input focus:border-accent focus:ring-accent w-full rounded-md border py-1 pl-8 pr-9 text-base focus:outline-none focus:ring-1"}),c&&F("div",{className:"absolute inset-y-0 right-0 flex cursor-pointer items-center pr-3",onClick:function(){d(""),s.current&&s.current.focus()}},F(of,{className:"text-fg-muted hover:text-fg-secondary h-4 w-4"}))),F("div",{className:"mt-3 flex flex-col gap-2"},F(my,{label:a("search.caseSensitive"),checked:o.flags.includes(Xt.MatchCase),onChange:function(e){return h(Xt.MatchCase,e)}}),F(my,{label:a("search.wholeWord"),checked:o.flags.includes(Xt.MatchWholeWord),onChange:function(e){return h(Xt.MatchWholeWord,e)}})),F("hr",{className:"border-border-subtle mb-2 mt-5"}),o.active&&F("div",{className:"flex h-[32px] flex-row items-center justify-between"},F("div",{className:"text-fg-muted text-xs"},a("search.resultsFound",{params:{count:o.total}})),o.total>1&&F("div",{className:"flex flex-row"},F(ff,{onClick:function(){null==i||i.previousResult()}},F(ef,{className:"h-4 w-4"})),F(ff,{onClick:function(){null==i||i.nextResult()}},F(Jp,{className:"h-4 w-4"}))))),F("div",{className:"flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-4"},Object.entries(g).map(function(e){var t=v(e,2),n=t[0],r=t[1];return F("div",{key:n,className:"mt-2 first:mt-0"},F("div",{className:"bg-bg-surface/80 text-fg-muted py-2 text-xs backdrop-blur"},a("search.page",{params:{page:Number(n)+1}})),F("div",{className:"flex flex-col gap-2"},r.map(function(e){var t=e.hit,n=e.index;return F(gy,{key:n,hit:t,active:n===o.activeResultIndex,onClick:function(){null==i||i.goToResult(n)}})})))}),F("div",null)))}function fy(e){var t=e.documentId,n=Oo(pm.id).provides,o=Di().provides,i=Ha(t).translate,r=jo(t),a=v(Se([]),2),s=a[0],l=a[1],c=v(Se(new Set),2),d=c[0],u=c[1],h=v(Se(!0),2),m=h[0],g=h[1];Me(function(){if(n&&null!=r&&r.document){g(!0);var e=n.getBookmarks();return e.wait(function(e){var t=e.bookmarks;l(t);var n=t.map(function(e,t){return"bookmark-".concat(t)});u(new Set(n)),g(!1)},function(){g(!1)}),function(){e.abort({code:tn.Cancelled,message:"Bookmark task cancelled"})}}},[n,null==r?void 0:r.document]);var p=function(e,t){var n,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,a="bookmark-".concat(t),s=e.children&&e.children.length>0,l=d.has(a);return F("div",{key:a,className:"select-none"},F("div",{className:"hover:bg-interactive-hover flex cursor-pointer items-center gap-1 px-2 py-1",style:{paddingLeft:"".concat(16*i+8,"px")},onClick:function(){return function(e){if(o&&e.target){var t;if("action"===e.target.type){var n=e.target.action;if(n.type===Et.Goto||n.type===Et.RemoteGoto)t=n.destination;else if(n.type===Et.URI)return void window.open(n.uri,"_blank")}else"destination"===e.target.type&&(t=e.target.destination);if(t)if(t.zoom.mode===At.XYZ){var i,a=null==r||null===(i=r.document)||void 0===i?void 0:i.pages.find(function(e){return e.index===t.pageIndex});if(!a)return;o.scrollToPage({pageNumber:t.pageIndex+1,pageCoordinates:t.zoom.params?{x:t.zoom.params.x,y:a.size.height-t.zoom.params.y}:void 0,behavior:"smooth"})}else o.scrollToPage({pageNumber:t.pageIndex+1,behavior:"smooth"})}}(e)}},s&&F("button",{onClick:function(e){e.stopPropagation(),function(e){u(function(t){var n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}(a)},className:"flex h-4 w-4 items-center justify-center"},F(l?tf:Jp,{className:"h-3 w-3"})),!s&&F("div",{className:"w-4"}),F("span",{className:"text-fg-secondary text-sm"},e.title)),s&&l&&F("div",null,null===(n=e.children)||void 0===n?void 0:n.map(function(e,t){return p(e,t,i+1)})))};return null==r||!r.document||m?F("div",{className:"text-fg-secondary flex h-full flex-col gap-3 p-4 text-sm"},F("div",{className:"text-fg-primary font-medium"},i("outline.title")),F("p",null,i("outline.loading"))):0===s.length?F("div",{className:"flex h-full items-center justify-center p-6"},F("div",{className:"text-fg-muted text-center"},F("div",{className:"text-sm"},i("outline.noOutline")),F("div",{className:"mt-1 text-xs"},i("outline.noBookmarks")))):F("div",{className:"bg-bg-surface flex h-full flex-col"},F("div",{className:"flex-1 overflow-y-auto"},F("div",{className:"outline-tree"},s.map(function(e,t){return p(e,t)}))))}function vy(e){var t=e.size,n=void 0===t?"md":t,o=e.text,i=e.className,r={sm:"w-6 h-6",md:"w-10 h-10",lg:"w-16 h-16"};return F("div",{className:"flex flex-col items-center justify-center gap-3 ".concat(void 0===i?"":i)},F("div",{className:"relative"},F("div",{className:"".concat(r[n]," border-border-default animate-spin rounded-full border-4")}),F("div",{className:"".concat(r[n]," border-r-accent border-t-accent absolute left-0 top-0 animate-spin rounded-full border-4 border-transparent")})),o&&F("p",{className:"".concat({sm:"text-sm",md:"text-base",lg:"text-lg"}[n]," text-fg-secondary animate-pulse font-medium")},o))}function yy(e){var t=e.size,n=void 0===t?"md":t,o=e.className,i=void 0===o?"":o;return F("div",{className:"".concat({sm:"w-4 h-4 border-2",md:"w-6 h-6 border-2",lg:"w-8 h-8 border-3"}[n]," border-border-default border-t-accent animate-spin rounded-full ").concat(i)})}var by,wy=function(e){var t=e.documentId,n=ch().provides,o=v(Se({show:!1,mode:null,isAnimating:!1}),2),i=o[0],r=o[1],a=Ha(t).translate;Me(function(){if(n)return n.onModeChange(function(e){var t=e.activeMode;if("marqueeZoom"===t||"marqueeCapture"===t){r({show:!0,mode:t,isAnimating:!0});var n=setTimeout(function(){r(function(e){return h(h({},e),{},{show:!1})})},3e3);return function(){return clearTimeout(n)}}r({show:!1,mode:null,isAnimating:!1})})},[n]);if(!i.show&&!i.isAnimating)return null;var s="marqueeZoom"===i.mode?a("zoom.dragTip"):a("capture.dragTip"),l="marqueeZoom"===i.mode?"rgba(33,150,243,0.8)":"rgba(76,175,80,0.8)";return F("div",{className:"hint-overlay ".concat(i.show?"hint-show":"hint-hide"),onAnimationEnd:function(){i.show||r(function(e){return h(h({},e),{},{isAnimating:!1,mode:null})})},style:{position:"absolute",top:0,left:0,right:0,bottom:0,pointerEvents:"none",zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"20px"}},F("div",{className:"hint-text",style:{background:"rgba(0, 0, 0, 0.8)",color:"white",padding:"12px 20px",borderRadius:"8px",fontSize:"14px",fontWeight:"500",textAlign:"center",maxWidth:"250px"}},s),F("div",{className:"drag-demo",style:{position:"relative",width:"150px",height:"100px"}},F("div",{style:{position:"absolute",top:"20px",left:"20px",width:"110px",height:"60px",border:"2px dashed ".concat(l),borderRadius:"4px",opacity:.6}}),F("div",{className:"animated-rect",style:{position:"absolute",top:"20px",left:"20px",border:"2px solid ".concat(l),backgroundColor:"".concat(l.replace("0.8","0.15")),borderRadius:"4px"}}),F("div",{className:"cursor-demo",style:{position:"absolute",width:"20px",height:"20px"}},F("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg"},F("path",{d:"M3.5 2.5L16.5 10L10 11.5L7.5 16.5L3.5 2.5Z",fill:"rgba(0,0,0,0.3)",transform:"translate(1,1)"}),F("path",{d:"M3 2L16 10L10 11.5L7.5 16L3 2Z",fill:"white",stroke:"black",strokeWidth:"1"}),F("path",{d:"M4 3.5L13.5 9.5L9.5 10.5L7.5 14L4 3.5Z",fill:"rgba(255,255,255,0.8)"})))),F("style",{jsx:!0},"\n .hint-overlay {\n animation-duration: 0.3s;\n animation-fill-mode: both;\n }\n\n .hint-show {\n animation-name: hintFadeIn;\n }\n\n .hint-hide {\n animation-name: hintFadeOut;\n }\n\n @keyframes hintFadeIn {\n from {\n opacity: 0;\n transform: translateY(10px);\n }\n to {\n opacity: 1;\n transform: translateY(0);\n }\n }\n\n @keyframes hintFadeOut {\n from {\n opacity: 1;\n transform: translateY(0);\n }\n to {\n opacity: 0;\n transform: translateY(-10px);\n }\n }\n\n .animated-rect {\n animation: rectGrow 2s ease-in-out infinite;\n }\n\n @keyframes rectGrow {\n 0% {\n width: 0;\n height: 0;\n }\n 50% {\n width: 110px;\n height: 60px;\n }\n 100% {\n width: 110px;\n height: 60px;\n opacity: 0.7;\n }\n }\n\n .cursor-demo {\n animation: cursorMove 2s ease-in-out infinite;\n }\n\n @keyframes cursorMove {\n 0% {\n top: 20px;\n left: 20px;\n }\n 50% {\n top: 50px;\n left: 80px;\n }\n 100% {\n top: 80px;\n left: 130px;\n }\n }\n\n .hint-text {\n animation: textPulse 0.6s ease-in-out;\n }\n\n @keyframes textPulse {\n 0% {\n transform: scale(0.9);\n }\n 50% {\n transform: scale(1.05);\n }\n 100% {\n transform: scale(1);\n }\n }\n "))},xy=function(e){var t=e.placeholder,n=e.onSubmit,o=e.inputRef,i=e.isFocused,r=v(Se(""),2),a=r[0],s=r[1];return F("form",{className:"border-border-subtle mt-4 flex items-end space-x-2 border-t pt-4",onClick:function(e){return e.stopPropagation()},onSubmit:function(e){null==e||e.preventDefault(),a.trim()&&(n(a),s(""))}},F("input",{ref:o,type:"text",placeholder:t,value:a,onInput:function(e){return s(e.currentTarget.value)},className:"bg-bg-input text-fg-primary placeholder-fg-muted w-full rounded-lg border px-3 py-1 text-base transition-colors focus:border-transparent focus:outline-none focus:ring-2 ".concat(i?"border-accent focus:ring-accent":"border-border-default focus:ring-accent")}),F("button",{type:"submit",disabled:!a.trim(),className:"bg-accent text-fg-on-accent hover:bg-accent-hover disabled:bg-interactive-disabled rounded-lg p-2 transition-colors disabled:cursor-not-allowed"},F("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},F("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 19l9 2-9-18-9 18 9-2zm0 0v-8"}))))},Cy=["bg-red-500","bg-blue-500","bg-green-500","bg-yellow-500","bg-purple-500","bg-pink-500","bg-indigo-500","bg-teal-500"],ky=function(e){if(!e)return Cy[0];var t=e.length>0?e.charCodeAt(0)%Cy.length:0;return Cy[t]},Iy=function(e){var t=e.name,n=e.className,o=void 0===n?"":n;return F("div",{className:"flex h-8 w-8 items-center justify-center rounded-full text-sm font-medium text-white ".concat(ky(t)," ").concat(o)},function(e){return e?e.split(" ").map(function(e){return e[0]}).join("").toUpperCase().slice(0,2):"G"}(t))},Sy=function(e){var t,n,o=e.onEdit,i=e.onDelete,r=e.onClose,a=e.documentId,s=De(null),l=Ha(a).translate;Me(function(){var e=function(e){t.current&&!t.current.contains(e.target)&&n()};return document.addEventListener("click",e),function(){document.removeEventListener("click",e)}},[t=s,n=r]);return F("div",{ref:s,className:"bg-bg-elevated ring-border-default absolute right-0 top-6 z-10 w-32 rounded-md shadow-lg ring-1"},F("div",{className:"py-1"},F("button",{onClick:function(e){e.preventDefault(),e.stopPropagation(),o(),r()},className:"text-fg-secondary hover:bg-interactive-hover block w-full px-4 py-2 text-left text-sm"},l("comments.edit")),F("button",{onClick:function(e){e.preventDefault(),e.stopPropagation(),i(),r()},className:"text-state-error hover:bg-interactive-hover block w-full px-4 py-2 text-left text-sm"},l("comments.delete"))))},Ay=function(e){var t=e.initialText,n=e.onSave,o=e.onCancel,i=e.autoFocus,r=void 0!==i&&i,a=e.documentId,s=v(Se(t),2),l=s[0],c=s[1],d=De(null),u=Ha(a).translate;Me(function(){r&&d.current&&(d.current.focus(),d.current.setSelectionRange(l.length,l.length))},[r,l.length]);return F("div",{className:"flex-1 space-y-2"},F("textarea",{ref:d,value:l,onInput:function(e){return c(e.currentTarget.value)},className:"border-border-default bg-bg-input text-fg-primary focus:border-accent focus:ring-accent w-full rounded-md border px-3 py-2 text-base focus:outline-none focus:ring-1",rows:3}),F("div",{className:"flex flex-wrap gap-2"},F("button",{onClick:function(e){e.stopPropagation(),n(l)},className:"bg-accent text-fg-on-accent hover:bg-accent-hover whitespace-nowrap rounded-md px-3 py-1 text-sm"},u("comments.save")),F("button",{onClick:function(e){e.stopPropagation(),o()},className:"bg-interactive-hover text-fg-secondary hover:bg-border-default whitespace-nowrap rounded-md px-3 py-1 text-sm"},u("comments.cancel"))))},My=function(e){if(!e)return"(no date)";try{return(e instanceof Date?e:new Date(e)).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}catch(t){return"string"==typeof e?e:"(no date)"}},Py=function(e){var t=e.annotation,n=e.onSave,o=e.onDelete,i=e.isReply,r=void 0!==i&&i,a=e.documentId,s=e.isReadOnly,l=void 0!==s&&s,c=v(Se(!1),2),d=c[0],u=c[1],h=v(Se(!1),2),m=h[0],g=h[1],p=t.author||"Guest";return m?F("div",{className:"flex w-full items-start space-x-3",onClick:function(e){return e.stopPropagation()}},r&&F(Iy,{name:p,className:"h-8 w-8"}),F(Ay,{initialText:t.contents||"",onSave:function(e){n(e),g(!1)},onCancel:function(){g(!1)},autoFocus:!0,documentId:a})):F("div",{className:"flex items-start space-x-3"},r&&F(Iy,{name:p,className:"h-8 w-8"}),F("div",{className:"min-w-0 flex-1"},r&&F("div",{className:"flex items-center justify-between"},F("div",{className:"leading-none"},F("h5",{className:"text-fg-primary text-sm font-medium"},p),F("span",{className:"text-fg-muted text-xs"},My(t.modified||t.created))),!l&&F("div",{className:"relative"},F("button",{onClick:function(e){e.stopPropagation(),u(!0)},className:"text-fg-muted hover:bg-interactive-hover rounded-md p-1"},F("svg",{className:"h-4 w-4",fill:"currentColor",viewBox:"0 0 20 20"},F("path",{d:"M6 10a2 2 0 11-4 0 2 2 0 014 0zM12 10a2 2 0 11-4 0 2 2 0 014 0zM16 12a2 2 0 100-4 2 2 0 000 4z"}))),d&&F(Sy,{onEdit:function(){return g(!0)},onDelete:o,onClose:function(){return u(!1)},documentId:a}))),F("p",{className:"text-fg-primary mt-2 text-sm"},t.contents)))},Dy=(s(s(s(s(s(s(s(s(s(s(by={},Ot.TEXT,{label:"Comment",labelKey:"annotation.comment",icon:"message",iconProps:function(e){return{primaryColor:e.strokeColor||e.color||"#6b7280"}}}),Ot.HIGHLIGHT,{label:"Highlight",labelKey:"annotation.highlight",icon:"highlight",iconProps:function(e){return{primaryColor:e.strokeColor||"#ffff00"}}}),Ot.CIRCLE,{label:"Circle",labelKey:"annotation.circle",icon:"circle",iconProps:function(e){return{primaryColor:e.strokeColor||"#000000",secondaryColor:e.color}}}),Ot.SQUARE,{label:"Square",labelKey:"annotation.square",icon:"square",iconProps:function(e){return{primaryColor:e.strokeColor||"#000000",secondaryColor:e.color}}}),Ot.LINE,{label:"Line",labelKey:"annotation.line",icon:"line",iconProps:function(e){return{primaryColor:e.strokeColor||"#000000"}}}),Ot.UNDERLINE,{label:"Underline",labelKey:"annotation.underline",icon:"underline",iconProps:function(e){return{primaryColor:e.strokeColor||"#000000"}}}),Ot.SQUIGGLY,{label:"Squiggly",labelKey:"annotation.squiggly",icon:"squiggly",iconProps:function(e){return{primaryColor:e.strokeColor||"#000000"}}}),Ot.STRIKEOUT,{label:"Strikethrough",labelKey:"annotation.strikeout",icon:"strikethrough",iconProps:function(e){return{primaryColor:e.strokeColor||"#000000"}}}),Ot.INK,{label:"Ink",labelKey:"annotation.ink",icon:"pencilMarker",iconProps:function(e){return{primaryColor:e.strokeColor||"#000000"}}}),Ot.FREETEXT,{label:"Text",labelKey:"annotation.freeText",icon:"freeText",iconProps:function(e){return{primaryColor:e.fontColor||"#000000"}}}),s(s(s(s(s(by,Ot.POLYGON,{label:"Polygon",labelKey:"annotation.polygon",icon:"polygon",iconProps:function(e){return{primaryColor:e.strokeColor||"#000000",secondaryColor:e.color}}}),Ot.POLYLINE,{label:"Polyline",labelKey:"annotation.polyline",icon:"zigzag",iconProps:function(e){return{primaryColor:e.strokeColor||"#000000"}}}),Ot.STAMP,{label:"Stamp",labelKey:"annotation.stamp",icon:"deviceFloppy",iconProps:function(){return{primaryColor:"#dc2626"}}}),Ot.CARET,{label:"Caret",labelKey:"annotation.caret",icon:"insertText",iconProps:function(e){return{primaryColor:e.strokeColor||"#E44234"}}}),Ot.REDACT,{label:"Redact",labelKey:"annotation.redact",icon:"redact",iconProps:function(e){return{primaryColor:e.strokeColor||"#000000",secondaryColor:e.color||"#000000"}}})),Ry=function(e){return nd(e)?Dy[e.object.type]:null},zy=function(e){var t=e.text,n=e.maxWords,o=void 0===n?16:n,i=e.className,r=void 0===i?"":i,a=e.documentId,s=v(Se(!1),2),l=s[0],c=s[1],d=Ha(a).translate,u=t.split(" ");return u.length>o?F("div",{className:r},l?t:u.slice(0,o).join(" ")+"..."," ",F("button",{onClick:function(e){e.stopPropagation(),c(!l)},className:"text-accent hover:text-accent-hover text-sm font-medium focus:outline-none"},d(l?"comments.showLess":"comments.showMore"))):F("div",{className:r},t)},Ty=function(e){var t=e.annotation,n=e.config,o=e.className,i=void 0===o?"":o,r=e.title,a=n.iconProps(t.object);return F("div",{className:"bg-bg-surface-alt flex items-center justify-center rounded-full ".concat(i),title:r},F(gf,h({icon:n.icon},a)))},Ey=function(e){var t,n=e.entry,o=e.isSelected,i=e.onSelect,r=e.onUpdate,a=e.onDelete,s=e.onReply,l=e.documentId,c=e.isReadOnly,d=void 0!==c&&c,u=n.annotation,h=n.replies,m=n.groupMembers,g=v(Se(!1),2),p=g[0],f=g[1],y=v(Se(!1),2),b=y[0],w=y[1],x=v(Se(!1),2),C=x[0],k=x[1],I=Ha(l).translate,S=null!=m&&m.length>0,A=Ry(u),M=!!u.object.contents,P=h.length>0,D=!M&&!P,R=De(null),z=De(!1),T=u.object.author||"Guest";if(Me(function(){var e;o&&!z.current&&(null===(e=R.current)||void 0===e||e.focus({preventScroll:!0}));z.current=o},[o]),!A)return null;return F("div",{onClick:i,className:"bg-bg-surface cursor-pointer rounded-lg border shadow-sm transition-all hover:shadow-md ".concat(o?"border-accent ring-interactive-focus-ring ring-2":"border-border-subtle")},F("div",{className:"p-4"},F("div",{className:"flex items-start space-x-3"},F(Ty,{annotation:u,config:A,title:I(A.labelKey,{fallback:A.label}),className:"h-8 w-8"}),F("div",{className:"min-w-0 flex-1"},F("div",{className:"flex items-center justify-between"},F("div",{className:"leading-none"},F("h4",{className:"text-fg-primary text-sm font-medium"},T),F("span",{className:"text-fg-disabled text-xs"},My(u.object.modified||u.object.created))),!d&&F("div",{className:"relative"},F("button",{onClick:function(e){e.stopPropagation(),f(!0)},className:"text-fg-disabled hover:bg-interactive-hover hover:text-fg-secondary rounded-md p-1"},F("svg",{className:"h-4 w-4",fill:"currentColor",viewBox:"0 0 20 20"},F("path",{d:"M6 10a2 2 0 11-4 0 2 2 0 014 0zM12 10a2 2 0 11-4 0 2 2 0 014 0zM16 12a2 2 0 100-4 2 2 0 000 4z"}))),p&&F(Sy,{onEdit:function(){return w(!0)},onDelete:function(){return a(u)},onClose:function(){return f(!1)},documentId:l}))),(null===(t=u.object.custom)||void 0===t?void 0:t.text)&&F(zy,{text:u.object.custom.text,maxWords:14,className:"text-fg-muted mt-2 text-sm",documentId:l}),b?F("div",{className:"mt-2"},F(Ay,{initialText:u.object.contents||"",onSave:function(e){r(u.object.id,e),w(!1)},onCancel:function(){w(!1)},autoFocus:!0,documentId:l})):M?F("p",{className:"text-fg-primary mt-2 text-sm"},u.object.contents):null)),P&&F("div",{className:"border-border-subtle mt-4 space-y-4 border-t pt-4"},h.map(function(e){return F(Py,{key:e.object.id,annotation:e.object,onSave:function(t){return r(e.object.id,t)},onDelete:function(){return a(e)},isReply:!0,documentId:l,isReadOnly:d})})),S&&F("div",{className:"border-border-subtle mt-4 border-t pt-3"},F("button",{onClick:function(e){e.stopPropagation(),k(function(e){return!e})},className:"text-accent hover:text-accent-hover flex w-full items-center justify-center gap-1 text-sm font-medium"},C?I("comments.closeAllAnnotations",{fallback:"Close All Annotations"}):I("comments.showAllAnnotations",{fallback:"Show All Annotations"}),F("svg",{className:"h-4 w-4 transition-transform ".concat(C?"rotate-180":""),fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2},F("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"}))),C&&F("div",{className:"mt-3 space-y-3"},m.map(function(e){var t,n=Ry(e);if(!n)return null;var o=e.object.author||"Guest";return F("div",{key:e.object.id,className:"flex items-start gap-2"},F(Ty,{annotation:e,config:n,title:I(n.labelKey,{fallback:n.label}),className:"h-6 w-6"}),F("div",{className:"min-w-0 flex-1"},F("div",{className:"leading-none"},F("span",{className:"text-fg-primary text-sm font-medium"},o),F("span",{className:"text-fg-disabled ml-2 text-xs"},My(e.object.modified||e.object.created)," (".concat(I("comments.page",{params:{page:e.object.pageIndex+1}}),")"))),(null===(t=e.object.custom)||void 0===t?void 0:t.text)&&F(zy,{text:e.object.custom.text,maxWords:14,className:"text-fg-muted mt-1 text-sm",documentId:l}),e.object.contents&&F("p",{className:"text-fg-primary mt-1 text-sm"},e.object.contents)))}))),!b&&!d&&F(xy,{inputRef:R,isFocused:o,placeholder:I(D?"comments.addComment":"comments.addReply"),onSubmit:function(e){D?r(u.object.id,e):s(u.object.id,e)}})))},_y=function(e){var t=e.documentId,n=Ha(t).translate;return F("div",{class:"text-fg-muted flex flex-col items-center gap-2 p-4"},F(gf,{icon:"comment",className:"h-18 w-18 text-fg-muted"}),F("div",{className:"text-fg-muted max-w-[150px] text-center text-sm"},n("comments.emptyState")))},Ny=function(e){var t=e.documentId,n=xh().provides,o=Ch(t).state,i=Di().provides,r=Ha(t).translate,s=Bo(t).canModifyAnnotations,l=De({}),c=De(null),d=!s,u=id(o),h=(e=>{const t={};for(const n of Object.values(e.pages))for(const o of n){const n=e.byUid[o];if(n&&td(n)){const e=n.object.inReplyToId;e&&(t[e]||(t[e]=[])).push(n)}}const n={},o=new Set;for(const t of Object.values(e.pages))for(const i of t){const t=e.byUid[i];if(t&&t.object.inReplyToId&&t.object.replyType===Ut.Group&&t.object.type!==Ot.LINK&&nd(t)){const e=t.object.inReplyToId;(n[e]||(n[e]=[])).push(t),o.add(t.object.id)}}const i={};for(const[r,a]of Object.entries(e.pages)){const s=Number(r),l=[];for(const i of a){const r=e.byUid[i];if(!r||!nd(r))continue;if(o.has(r.object.id))continue;const a=n[r.object.id];l.push({page:s,annotation:r,replies:t[r.object.id]??[],...a&&a.length>0?{groupMembers:a}:{}})}l.length>0&&(i[s]=l)}return i})(o),m=new Set(u.map(function(e){var t;return null!==(t=ld(o,e.object.id))&&void 0!==t?t:e.object.id}));Me(function(){var e=m.values().next().value;if(e&&c.current){var t=l.current[e];if(t){var n=c.current,o=n.getBoundingClientRect(),i=t.getBoundingClientRect(),r=i.top-o.top+n.scrollTop-n.clientHeight/2+i.height/2;n.scrollTo({top:r,behavior:"smooth"})}}},[o.selectedUids]);var g=function(e,t){var o=y(e);o&&(null==n||n.updateAnnotation(o.object.pageIndex,e,{contents:t,modified:new Date}))},p=function(e){null==n||n.deleteAnnotation(e.object.pageIndex,e.object.id)},f=function(e,t){var o=y(e);o&&(null==n||n.createAnnotation(o.object.pageIndex,{id:_n(),rect:{origin:{x:o.object.rect.origin.x,y:o.object.rect.origin.y},size:{width:24,height:24}},pageIndex:o.object.pageIndex,created:new Date,modified:new Date,type:Ot.TEXT,contents:t,inReplyToId:o.object.id,flags:["noRotate","noZoom","print"],icon:jt.Comment}))},v=Object.keys(h).map(Number).sort(function(e,t){return e-t}),y=function(e){var t,n=a(v);try{for(n.s();!(t=n.n()).done;){var o,i=t.value,r=a(h[i]);try{for(r.s();!(o=r.n()).done;){var s=o.value;if(s.annotation.object.id===e)return s.annotation;var l=s.replies.find(function(t){return t.object.id===e});if(l)return l}}catch(e){r.e(e)}finally{r.f()}}}catch(e){n.e(e)}finally{n.f()}};return 0===v.length?F(_y,{documentId:t}):F("div",{ref:c,className:"h-full overflow-y-auto"},F("div",{className:"space-y-6 p-3"},v.map(function(e){return F("div",{key:e,className:"space-y-3"},F("div",{className:"bg-bg-surface sticky top-0 z-10 px-1"},F("div",{className:"border-border-subtle border-b py-2"},F("h3",{className:"text-md text-fg-primary font-semibold"},r("comments.page",{params:{page:e+1}})),F("p",{className:"text-fg-muted text-sm"},1===h[e].length?r("comments.commentCount",{params:{count:1}}):r("comments.commentCountPlural",{params:{count:h[e].length}})))),F("div",{className:"space-y-3 px-1"},h[e].map(function(e){return F("div",{key:e.annotation.object.id,ref:function(t){t&&(l.current[e.annotation.object.id]=t)}},F(Ey,{entry:e,isSelected:m.has(e.annotation.object.id),onSelect:function(){return t=e.annotation,null==n||n.selectAnnotation(t.object.pageIndex,t.object.id),void(null==i||i.scrollToPage({pageNumber:t.object.pageIndex+1,pageCoordinates:{x:t.object.rect.origin.x,y:t.object.rect.origin.y},alignX:50,alignY:25,behavior:"smooth"}));var t},onUpdate:g,onDelete:p,onReply:f,documentId:t,isReadOnly:d}))})))})))};function Ly(e){var t=e.documentId,n=(e=>{const{provides:t}=ns(),[n,o]=Se(Xa);return Me(()=>{if(!t)return;const n=t.forDocument(e);return o(n.getState()),n.onStateChange(e=>{o(e)})},[t,e]),{state:n,provides:(null==t?void 0:t.forDocument(e))??null}})(t),o=n.state,i=n.provides,r=v(Se(""),2),a=r[0],s=r[1];if(!i)return null;var l=Math.round(100*o.currentZoomLevel);Me(function(){s(l.toString())},[l]);return F("div",{className:"relative"},F("div",{className:"bg-interactive-hover flex items-center rounded"},F("form",{onSubmit:function(e){e.preventDefault();var t=e.target,n=new FormData(t),o=parseFloat(n.get("zoom")||a);!isNaN(o)&&o>0&&i.requestZoom(o/100)},className:"block"},F("input",{name:"zoom",type:"text",inputMode:"numeric",pattern:"\\d*",className:"h-6 w-8 border-0 bg-transparent p-0 text-right text-sm outline-none focus:outline-none","aria-label":"Set zoom",autoFocus:!1,value:a,onInput:function(e){var t=e.target.value.replace(/[^0-9]/g,"");s(t)},onBlur:function(){(!a||parseFloat(a)<=0)&&s(l.toString())}}),F("span",{className:"text-sm"},"%")),F(Wv,{commandId:"zoom:toggle-menu",documentId:t,itemId:"zoom-menu-button"}),F(Wv,{commandId:"zoom:out",documentId:t}),F(Wv,{commandId:"zoom:in",documentId:t})))}var Oy,$y=function(e){var t=e.documentId,n=Ha(t).translate;return F("div",{class:"text-fg-muted flex flex-col items-center gap-2 p-4"},F(gf,{icon:"palette",className:"h-18 w-18 text-fg-muted"}),F("div",{className:"text-fg-muted max-w-[150px] text-center text-sm"},n("annotation.selectAnnotation")))},jy={color:{key:"color",type:"colorWithTransparent",labelKey:"annotation.fillColor"},strokeColor:{key:"strokeColor",type:"colorWithTransparent",labelKey:"annotation.strokeColor"},opacity:{key:"opacity",type:"opacity",labelKey:"annotation.opacity",min:.1,max:1,step:.05,debounce:!0},strokeWidth:{key:"strokeWidth",type:"slider",labelKey:"annotation.strokeWidth",min:1,max:30,step:1,unit:"px",debounce:!0},strokeStyle:{key:"strokeStyle",type:"strokeStyle",labelKey:"annotation.borderStyle"},lineEndings:{key:"lineEndings",type:"lineEndings",labelKey:"annotation.lineEndings"},fontFamily:{key:"fontFamily",type:"fontFamily",labelKey:"annotation.fontFamily"},fontSize:{key:"fontSize",type:"fontSize",labelKey:"annotation.fontSize"},fontColor:{key:"fontColor",type:"fontColor",labelKey:"annotation.fontColor"},textAlign:{key:"textAlign",type:"textAlign",labelKey:"annotation.textAlign"},verticalAlign:{key:"verticalAlign",type:"verticalAlign",labelKey:"annotation.verticalAlign"},blendMode:{key:"blendMode",type:"blendMode",labelKey:"annotation.blendMode"},rotation:{key:"rotation",type:"rotation",labelKey:"annotation.rotation",debounce:!0,editOnly:!0},overlayText:{key:"overlayText",type:"text",labelKey:"annotation.overlayText",placeholderKey:"annotation.overlayTextPlaceholder"}},Fy=(s(s(s(s(s(s(s(s(s(s(Oy={},Ot.TEXT,["strokeColor","opacity"]),Ot.INK,["strokeColor","opacity","strokeWidth","rotation"]),Ot.CIRCLE,["color","opacity","strokeColor","strokeStyle","strokeWidth","rotation"]),Ot.SQUARE,["color","opacity","strokeColor","strokeStyle","strokeWidth","rotation"]),Ot.POLYGON,["strokeColor","opacity","strokeStyle","strokeWidth","color","rotation"]),Ot.LINE,["strokeColor","opacity","strokeStyle","strokeWidth","lineEndings","color","rotation"]),Ot.POLYLINE,["strokeColor","opacity","strokeStyle","strokeWidth","lineEndings","color","rotation"]),Ot.HIGHLIGHT,["strokeColor","opacity","blendMode"]),Ot.UNDERLINE,["strokeColor","opacity","blendMode"]),Ot.STRIKEOUT,["strokeColor","opacity","blendMode"]),s(s(s(s(s(Oy,Ot.SQUIGGLY,["strokeColor","opacity","blendMode"]),Ot.STAMP,["rotation"]),Ot.FREETEXT,["fontFamily","fontSize","fontColor","textAlign","verticalAlign","opacity","color","rotation"]),Ot.CARET,["strokeColor","opacity"]),Ot.REDACT,["strokeColor","color","opacity"]));var Uy,Hy=["position"],Wy=function(){var e=v(Se(!1),2),t=e[0],n=e[1],o=De(null),i=De(null);return Me(function(){if(t){var e=function(e){o.current&&!o.current.contains(e.target)&&n(!1)};return document.addEventListener("click",e),function(){return document.removeEventListener("click",e)}}},[t]),Me(function(){t&&i.current&&i.current.scrollIntoView({block:"center",inline:"start"})},[t]),{open:t,setOpen:n,rootRef:o,selectedItemRef:i}},By=function(e){var t=e.value,n=e.onChange,o=e.options,i=e.getOptionKey,r=e.renderValue,a=e.renderOption,s=e.triggerClass,l=void 0===s?"px-3 py-2":s,c=Wy(),d=c.open,u=c.setOpen,h=c.rootRef,m=c.selectedItemRef;return F("div",{ref:h,class:"relative inline-block w-full"},F("button",{type:"button",class:"border-border-default bg-bg-input flex w-full items-center justify-between gap-2 rounded border ".concat(l),onClick:function(){return u(function(e){return!e})}},r(t),F("svg",{class:"text-fg-secondary h-4 w-4",viewBox:"0 0 20 20",fill:"currentColor"},F("path",{fillRule:"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 10.94l3.71-3.71a.75.75 0 111.06 1.06l-4.24 4.24a.75.75 0 01-1.06 0L5.21 8.29a.75.75 0 01.02-1.08z",clipRule:"evenodd"}))),d&&F("div",{class:"border-border-default bg-bg-elevated absolute z-10 mt-1 max-h-60 w-full overflow-y-auto rounded border p-1 shadow-lg"},o.map(function(e){var o=i(e)===i(t);return F("button",{ref:o?m:null,key:i(e),class:"hover:bg-interactive-hover block w-full rounded text-left ".concat(o?"bg-interactive-hover":""),onClick:function(){n(e),u(!1)}},a(e,o))})))},qy=function(e){var t=e.children,n=e.className;return F("label",{class:"text-fg-primary mb-2 block text-sm font-medium ".concat(void 0===n?"":n)},t)},Gy=function(e){var t=e.children,n=e.className;return F("span",{class:"text-fg-muted text-xs ".concat(void 0===n?"":n)},t)},Vy=function(e){var t=e.children,n=e.className;return F("section",{class:"mb-6 ".concat(void 0===n?"":n)},t)},Ky=function(e){var t=e.value,n=e.min,o=void 0===n?0:n,i=e.max,r=void 0===i?1:i,a=e.step,s=void 0===a?.1:a,l=e.onChange;return F("input",{type:"range",class:"range-sm bg-border-subtle mb-2 h-1 w-full cursor-pointer appearance-none rounded-lg",value:t,min:o,max:r,step:s,onInput:function(e){return l(parseFloat(e.target.value))}})},Zy=function(e){var t=e.color,n=e.active,o=e.onSelect,i=function(e){return"transparent"===e||/^rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*0\s*\)$/i.test(e)||/^#([0-9a-f]{8})$/i.test(e)&&"00"===e.slice(-2).toLowerCase()||/^#([0-9a-f]{4})$/i.test(e)&&"0"===e.slice(-1).toLowerCase()}(t)?{backgroundColor:"#fff",backgroundImage:"linear-gradient(45deg, transparent 40%, red 40%, red 60%, transparent 60%)",backgroundSize:"100% 100%"}:{backgroundColor:t};return F("button",{title:t,class:"border-border-strong h-5 w-5 rounded-full border ".concat(n?"outline-accent outline outline-2 outline-offset-2":""),style:i,onClick:function(){return o(t)}})},Yy=[{id:Bt.SOLID},{id:Bt.DASHED,dash:[6,2]},{id:Bt.DASHED,dash:[8,4]},{id:Bt.DASHED,dash:[3,3]},{id:Bt.DASHED,dash:[1,2]},{id:Bt.DASHED,dash:[4,2,1,2]},{id:Bt.DASHED,dash:[8,4,1,4]}],Xy=function(e){return F("svg",{width:"80",height:"8",viewBox:"0 0 80 8"},F("line",{x1:"0",y1:"4",x2:"80",y2:"4",style:{strokeDasharray:null==e?void 0:e.join(" "),stroke:"currentColor",strokeWidth:"2"}}))},Qy=function(e){return F(By,h(h({},e),{},{options:Yy,getOptionKey:function(e){var t;return e.id+((null===(t=e.dash)||void 0===t?void 0:t.join("-"))||"")},renderValue:function(e){return Xy(e.dash)},renderOption:function(e){return F("div",{class:"px-1 py-2"},Xy(e.dash))}}))},Jy=[Ft.None,Ft.Square,Ft.Circle,Ft.Diamond,Ft.OpenArrow,Ft.ClosedArrow,Ft.ROpenArrow,Ft.RClosedArrow,Ft.Butt,Ft.Slash],eb=function(e){var t,n=e.ending,o=e.position,i=s(s(s(s(s(s(s(s(s({},Ft.Square,F("path",{d:"M68 -4 L76 -4 L76 4 L68 4 Z"})),Ft.Circle,F("circle",{cx:"72",cy:"0",r:"4"})),Ft.Diamond,F("path",{d:"M72 -5 L77 0 L72 5 L67 0 Z"})),Ft.OpenArrow,F("path",{d:"M67 -5 L77 0 L67 5",fill:"none"})),Ft.ClosedArrow,F("path",{d:"M67 -5 L77 0 L67 5 Z"})),Ft.ROpenArrow,F("path",{d:"M77 -5 L67 0 L77 5",fill:"none"})),Ft.RClosedArrow,F("path",{d:"M77 -5 L67 0 L77 5 Z"})),Ft.Butt,F("path",{d:"M72 -5 L72 5",fill:"none"})),Ft.Slash,F("path",{d:"M67 -5 L77 5",fill:"none"})),r=s(s(s(s(s(s(s(s(s({},Ft.Square,68),Ft.Circle,68),Ft.Diamond,67),Ft.OpenArrow,76),Ft.ClosedArrow,67),Ft.ROpenArrow,67),Ft.RClosedArrow,67),Ft.Butt,72),Ft.Slash,72),a=i[n];return F("svg",{width:"80",height:"20",viewBox:"0 0 80 20",class:"text-fg-primary"},F("g",{transform:"start"===o?"rotate(180 40 10)":""},F("line",{x1:"4",y1:"10",x2:null!==(t=r[n])&&void 0!==t?t:77,y2:"10",stroke:"currentColor","stroke-width":"1.5"}),a&&F("g",{transform:"translate(0, 10)",fill:"currentColor",stroke:"currentColor","stroke-width":"1.5"},a)))},tb=function(e){var t=e.position,n=m(e,Hy);return F(By,h(h({},n),{},{options:Jy,getOptionKey:function(e){return e},triggerClass:"px-3 py-1",renderValue:function(e){return F(eb,{ending:e,position:t})},renderOption:function(e){return F("div",{class:"px-1 py-1"},F(eb,{ending:e,position:t}))}}))},nb=function(e){return F(By,h(h({},e),{},{options:Sn,getOptionKey:function(e){return e},triggerClass:"px-2 py-1 text-sm",renderValue:function(e){return F("span",null,An(e))},renderOption:function(e){return F("div",{class:"px-2 py-1"},An(e))}}))},ob=function(e){var t=e.value,n=e.onChange,o=(t%360+360)%360,i=function(e){n(((o+e)%360+360)%360)};return F("div",{class:"flex items-center gap-1"},F("button",{type:"button",title:"-90°",class:"border-border-default bg-bg-input text-fg-primary hover:bg-interactive-hover flex h-8 w-8 shrink-0 items-center justify-center rounded border",onClick:function(){return i(-90)}},F("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"},F("path",{d:"M1 4v6h6"}),F("path",{d:"M3.51 15a9 9 0 1 0 2.13-9.36L1 10"}))),F("div",{class:"relative flex-1"},F("input",{type:"number",min:"0",max:"359",class:"border-border-default bg-bg-input text-fg-primary h-8 w-full rounded border px-2 pr-6 text-center text-sm",value:o,onInput:function(e){var t=parseInt(e.target.value,10);Number.isFinite(t)&&n((t%360+360)%360)}}),F("span",{class:"text-fg-muted pointer-events-none absolute inset-y-0 right-2 flex items-center text-xs"},"°")),F("button",{type:"button",title:"+90°",class:"border-border-default bg-bg-input text-fg-primary hover:bg-interactive-hover flex h-8 w-8 shrink-0 items-center justify-center rounded border",onClick:function(){return i(90)}},F("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"},F("path",{d:"M23 4v6h-6"}),F("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"}))))},ib=function(e){var t=e.value,n=e.onChange,o=e.options,i=void 0===o?[8,9,10,11,12,14,16,18,24,36,48,72]:o,r=Wy(),a=r.open,s=r.setOpen,l=r.rootRef,c=r.selectedItemRef;return F("div",{ref:l,class:"relative w-full"},F("input",{type:"number",min:"1",class:"border-border-default bg-bg-input w-full rounded border px-2 py-1 pr-7 text-sm",value:t,onInput:function(e){var t=parseInt(e.target.value,10);Number.isFinite(t)&&t>0&&n(t)},onClick:function(){return s(!0)}}),F("button",{type:"button",class:"absolute inset-y-0 right-1 flex items-center",onClick:function(){return s(function(e){return!e})},tabIndex:-1},F("svg",{class:"text-fg-secondary h-4 w-4",viewBox:"0 0 20 20",fill:"currentColor"},F("path",{"fill-rule":"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 10.94l3.71-3.71a.75.75 0 111.06 1.06l-4.24 4.24a.75.75 0 01-1.06 0L5.21 8.29a.75.75 0 01.02-1.08z","clip-rule":"evenodd"}))),a&&F("div",{class:"border-border-default bg-bg-elevated absolute z-10 mt-1 max-h-48 w-full overflow-y-auto rounded border shadow-lg"},i.map(function(e){var o=e===t;return F("button",{ref:o?c:null,key:e,class:"hover:bg-interactive-hover block w-full px-2 py-1 text-left text-sm ".concat(o?"bg-interactive-hover":""),onClick:function(){n(e),s(!1)}},e)})))};function rb(e){var t=e.active,n=void 0!==t&&t,o=e.disabled,i=void 0!==o&&o,r=e.onClick,a=e.title,s=e.children,l=e.className,c=void 0===l?"":l;return F("button",{type:"button",title:a,disabled:i,onClick:r,className:"h-9 w-9 rounded border px-2 py-1 text-sm transition-colors ".concat(n?"border-accent bg-accent text-fg-on-accent":"border-border-default bg-bg-input text-fg-primary hover:bg-interactive-hover"," disabled:cursor-not-allowed disabled:opacity-40 ").concat(c)},s)}function ab(e){switch(e.config.type){case"color":return He(sb,h(h({},e),{},{allowTransparent:!1}));case"colorWithTransparent":return He(sb,h(h({},e),{},{allowTransparent:!0}));case"opacity":return He(lb,h({},e));case"slider":return He(cb,h({},e));case"strokeStyle":return He(db,h({},e));case"lineEndings":return He(ub,h({},e));case"fontFamily":return He(hb,h({},e));case"fontSize":return He(mb,h({},e));case"fontColor":return He(gb,h({},e));case"textAlign":return He(pb,h({},e));case"verticalAlign":return He(fb,h({},e));case"blendMode":return He(yb,h({},e));case"text":return He(bb,h({},e));case"rotation":return He(wb,h({},e));default:return null}}function sb(e){var t=e.config,n=e.value,o=e.onChange,i=e.colorPresets,r=e.translate,a=e.allowTransparent,s=v(Se(null!=n?n:"#000000"),2),l=s[0],c=s[1];Me(function(){return c(null!=n?n:"#000000")},[n]);var d=function(e){c(e),o(e)};return He(Vy,{children:[He(qy,{className:"mb-3",children:r(t.labelKey)}),He("div",{class:"grid grid-cols-6 gap-x-1 gap-y-4",children:[i.map(function(e){return He(Zy,{color:e,active:e.toLowerCase()===(null==l?void 0:l.toLowerCase()),onSelect:d},e)}),a&&He(Zy,{color:"transparent",active:"transparent"===l,onSelect:d})]})]})}function lb(e){var t,n,o,i=e.config,r=e.value,a=e.onChange,s=e.translate,l=v(Se(null!=r?r:1),2),c=l[0],d=l[1];Me(function(){return d(null!=r?r:1)},[r]);var u=hy(c,300);return Me(function(){u!==r&&a(u)},[u]),He(Vy,{children:[He(qy,{children:s(i.labelKey)}),He(Ky,{value:c,min:null!==(t=i.min)&&void 0!==t?t:.1,max:null!==(n=i.max)&&void 0!==n?n:1,step:null!==(o=i.step)&&void 0!==o?o:.05,onChange:d}),He(Gy,{children:[Math.round(100*c),"%"]})]})}function cb(e){var t,n,o,i,r,a=e.config,s=e.value,l=e.onChange,c=e.translate,d=v(Se(null!==(t=null!=s?s:a.min)&&void 0!==t?t:1),2),u=d[0],h=d[1];Me(function(){var e;return h(null!==(e=null!=s?s:a.min)&&void 0!==e?e:1)},[s]);var m=hy(u,300);return Me(function(){m!==s&&l(m)},[m]),He(Vy,{children:[He(qy,{children:c(a.labelKey)}),He(Ky,{value:u,min:null!==(n=a.min)&&void 0!==n?n:1,max:null!==(o=a.max)&&void 0!==o?o:30,step:null!==(i=a.step)&&void 0!==i?i:1,onChange:h}),He(Gy,{children:[u,null!==(r=a.unit)&&void 0!==r?r:""]})]})}function db(e){var t=e.config,n=e.value,o=e.onChange,i=e.translate,r=v(Se("object"===w(n)&&null!==n?n:{id:null!=n?n:Bt.SOLID}),2),a=r[0],s=r[1];Me(function(){var e="object"===w(n)&&null!==n?n:{id:null!=n?n:Bt.SOLID};s(e)},[n]);return He(Vy,{children:[He(qy,{className:"mb-3",children:i(t.labelKey)}),He(Qy,{value:a,onChange:function(e){s(e),o({strokeStyle:e.id,strokeDashArray:e.dash})}})]})}function ub(e){e.config;var t=e.value,n=e.onChange,o=e.translate,i=null!=t?t:{start:Ft.None,end:Ft.None},r=v(Se(i.start),2),a=r[0],s=r[1],l=v(Se(i.end),2),c=l[0],d=l[1];Me(function(){s(i.start),d(i.end)},[t]);return He(Vy,{children:He("div",{class:"grid grid-cols-2 gap-4",children:[He("div",{children:[He(qy,{className:"mb-3",children:o("annotation.lineStart")}),He(tb,{value:a,onChange:function(e){s(e),n({start:e,end:c})},position:"start"})]}),He("div",{children:[He(qy,{className:"mb-3",children:o("annotation.lineEnd")}),He(tb,{value:c,onChange:function(e){d(e),n({start:a,end:e})},position:"end"})]})]})})}function hb(e){var t=e.config,n=e.value,o=e.onChange,i=e.translate,r=null!=n?n:Pt.Helvetica,a=wn(r),s=xn(r),l=Cn(r),c=v(Se(a),2),d=c[0],u=c[1],h=v(Se(s),2),m=h[0],g=h[1],p=v(Se(l),2),f=p[0],y=p[1];Me(function(){var e=null!=n?n:Pt.Helvetica;u(wn(e)),g(xn(e)),y(Cn(e))},[n]);var b=function(e,t,n){var i=kn(e,{bold:t,italic:n});o(i)};return He(Vy,{children:[He(qy,{children:i(t.labelKey)}),He("div",{class:"mb-3",children:He(nb,{value:d,onChange:function(e){var t=xn(kn(e,{bold:!0,italic:!1})),n=Cn(kn(e,{bold:!1,italic:!0})),o=!!t&&m,i=!!n&&f;u(e),g(o),y(i),b(e,o,i)}})}),He("div",{class:"flex gap-2",children:[He(rb,{title:"Bold",active:m,disabled:!xn(kn(d,{bold:!0,italic:!1})),onClick:function(){if(xn(kn(d,{bold:!0,italic:!1}))){var e=!m;g(e),b(d,e,f)}},className:"font-bold",children:He(gf,{icon:"bold",size:18})}),He(rb,{title:"Italic",active:f,disabled:!Cn(kn(d,{bold:!1,italic:!0})),onClick:function(){if(Cn(kn(d,{bold:!1,italic:!0}))){var e=!f;y(e),b(d,m,e)}},className:"italic",children:He(gf,{icon:"italic",size:18})})]})]})}function mb(e){var t=e.config,n=e.value,o=e.onChange,i=e.translate,r=v(Se(null!=n?n:12),2),a=r[0],s=r[1];Me(function(){return s(null!=n?n:12)},[n]);return He(Vy,{children:[He(qy,{children:i(t.labelKey)}),He(ib,{value:a,onChange:function(e){!Number.isFinite(e)||e<=0||(s(e),o(e))}})]})}function gb(e){var t=e.config,n=e.value,o=e.onChange,i=e.colorPresets,r=e.translate,a=v(Se(null!=n?n:"#000000"),2),s=a[0],l=a[1];Me(function(){return l(null!=n?n:"#000000")},[n]);var c=function(e){l(e),o(e)};return He(Vy,{children:[He(qy,{className:"mb-3",children:r(t.labelKey)}),He("div",{class:"grid grid-cols-6 gap-x-1 gap-y-4",children:i.map(function(e){return He(Zy,{color:e,active:e.toLowerCase()===(null==s?void 0:s.toLowerCase()),onSelect:c},e)})})]})}function pb(e){var t=e.config,n=e.value,o=e.onChange,i=e.translate,r=v(Se(null!=n?n:Dt.Left),2),a=r[0],s=r[1];Me(function(){return s(null!=n?n:Dt.Left)},[n]);var l=function(e){s(e),o(e)};return He(Vy,{children:[He(qy,{children:i(t.labelKey)}),He("div",{class:"flex gap-2",children:[He(rb,{title:"Align left",active:a===Dt.Left,onClick:function(){return l(Dt.Left)},children:He(gf,{icon:"alignLeft",size:18})}),He(rb,{title:"Align center",active:a===Dt.Center,onClick:function(){return l(Dt.Center)},children:He(gf,{icon:"alignCenter",size:18})}),He(rb,{title:"Align right",active:a===Dt.Right,onClick:function(){return l(Dt.Right)},children:He(gf,{icon:"alignRight",size:18})})]})]})}function fb(e){var t=e.config,n=e.value,o=e.onChange,i=e.translate,r=v(Se(null!=n?n:Rt.Top),2),a=r[0],s=r[1];Me(function(){return s(null!=n?n:Rt.Top)},[n]);var l=function(e){s(e),o(e)};return He(Vy,{children:[He(qy,{children:i(t.labelKey)}),He("div",{class:"flex gap-2",children:[He(rb,{title:"Align top",active:a===Rt.Top,onClick:function(){return l(Rt.Top)},children:He(gf,{icon:"alignTop",size:18})}),He(rb,{title:"Align middle",active:a===Rt.Middle,onClick:function(){return l(Rt.Middle)},children:He(gf,{icon:"alignMiddle",size:18})}),He(rb,{title:"Align bottom",active:a===Rt.Bottom,onClick:function(){return l(Rt.Bottom)},children:He(gf,{icon:"alignBottom",size:18})})]})]})}var vb=(s(s(s(s(s(s(s(s(s(s(Uy={},zt.Normal,"blendMode.normal"),zt.Multiply,"blendMode.multiply"),zt.Screen,"blendMode.screen"),zt.Overlay,"blendMode.overlay"),zt.Darken,"blendMode.darken"),zt.Lighten,"blendMode.lighten"),zt.ColorDodge,"blendMode.colorDodge"),zt.ColorBurn,"blendMode.colorBurn"),zt.HardLight,"blendMode.hardLight"),zt.SoftLight,"blendMode.softLight"),s(s(s(s(s(s(Uy,zt.Difference,"blendMode.difference"),zt.Exclusion,"blendMode.exclusion"),zt.Hue,"blendMode.hue"),zt.Saturation,"blendMode.saturation"),zt.Color,"blendMode.color"),zt.Luminosity,"blendMode.luminosity"));function yb(e){var t=e.config,n=e.value,o=e.onChange,i=e.translate,r=v(Se(null!=n?n:zt.Normal),2),a=r[0],s=r[1];Me(function(){return s(null!=n?n:zt.Normal)},[n]);return He(Vy,{children:[He(qy,{children:i(t.labelKey)}),He("select",{class:"border-border-default bg-bg-input text-fg-primary w-full rounded border px-2 py-1 text-sm",value:a,onChange:function(e){var t=parseInt(e.target.value,10);s(t),o(t)},children:Rn.map(function(e){return He("option",{value:e,children:i(vb[e])},e)})})]})}function bb(e){var t=e.config,n=e.value,o=e.onChange,i=e.translate,r=v(Se(null!=n?n:""),2),a=r[0],s=r[1];Me(function(){return s(null!=n?n:"")},[n]);var l=hy(a,300);Me(function(){l!==n&&o(l)},[l]);return He(Vy,{children:[He(qy,{children:i(t.labelKey)}),He("input",{type:"text",class:"border-border-default bg-bg-input text-fg-primary w-full rounded border px-2 py-1 text-sm",value:a,onInput:function(e){var t=e.target.value;s(t)},placeholder:t.placeholderKey?i(t.placeholderKey):void 0})]})}function wb(e){var t=e.config,n=e.value,o=e.onChange,i=e.translate,r=v(Se(null!=n?n:0),2),a=r[0],s=r[1];Me(function(){return s(null!=n?n:0)},[n]);var l=hy(a,300);return Me(function(){l!==(null!=n?n:0)&&o(l)},[l]),He(Vy,{children:[He(qy,{children:i(t.labelKey)}),He(ob,{value:a,onChange:s})]})}function xb(e){var t=e.documentId,n=e.annotations,o=e.activeTool,i=e.colorPresets,r=xh().provides,l=Ha(t).translate;if(!r)return null;var c=n.length>0,d=c?y(new Set(n.map(function(e){return e.object.type}).filter(function(e){return void 0!==e}))):void 0!==(null==o?void 0:o.defaults.type)?[o.defaults.type]:[];if(0===d.length)return null;var u=function(e){var t;if(0===e.length)return[];for(var n=e.map(function(e){var t;return new Set(null!==(t=Fy[e])&&void 0!==t?t:[])}),o=n[0],i=1;i0,h="";if(c.length>1)h=s("annotation.multiSelect",{params:{count:String(c.length)}});else if(u){var m=c[0].object.type,g=Cb[m],p=g?s(g):"";h=p?s("annotation.styles",{params:{type:p}}):""}else if(d){var f=d.defaults.type;if(void 0!==f){var v=Cb[f],b=v?s(v):"";h=b?s("annotation.defaults",{params:{type:b}}):""}}var w=u?y(new Set(c.map(function(e){return e.object.type}))):void 0!==(null==d?void 0:d.defaults.type)?[d.defaults.type]:[],x=w.length>0&&w.some(function(e){var t,n;return(null!==(t=null===(n=Fy[e])||void 0===n?void 0:n.length)&&void 0!==t?t:0)>0});return x||u||d?He("div",{class:"h-full overflow-y-auto p-4",children:[h&&He("h2",{class:"text-md mb-4 font-medium",children:h}),He(xb,{documentId:n,annotations:c,activeTool:d,colorPresets:l})]}):He($y,{documentId:n})}var Ib=function(e){var t=e.item,n=e.pageNumber,o=e.isSelected,i=e.onSelect,r="text"===t.kind?rf:af;return F("div",{onClick:i,class:"border-border-subtle hover:bg-interactive-hover flex cursor-pointer items-start gap-3 rounded-lg border p-3 transition-colors ".concat(o?"bg-interactive-selected ring-accent ring-1":"")},F("div",{class:"flex-shrink-0"},F(r,{size:20,primaryColor:t.markColor,secondaryColor:t.redactionColor})),F("div",{class:"min-w-0 flex-1"},F("div",{class:"text-fg-muted text-xs"},"Page ",n),F("div",{class:"text-fg-primary text-sm font-medium"},"text"===t.kind?"Text Redaction":"Area Redaction"),"text"===t.kind&&t.text&&F("div",{class:"text-fg-muted mt-1 truncate text-xs italic"},'"',t.text,'"')))},Sb=function(e){var t=e.documentId,n=Ha(t).translate;return F("div",{class:"text-fg-muted flex flex-col items-center gap-2 p-4"},F(gf,{icon:"redact",className:"h-18 w-18 text-fg-muted"}),F("div",{className:"text-fg-muted max-w-[150px] text-center text-sm"},n("redaction.emptyState",{fallback:"No pending redactions"})))};function Ab(e){var t=e.documentId,n=(e=>{const{provides:t}=Ag(),[n,o]=Se(gg),i=Re(()=>t?t.forDocument(e):null,[t,e]);return Me(()=>{if(i){try{o(i.getState())}catch(e){o(gg)}return i.onStateChange(e=>{o(e)})}o(gg)},[i]),{state:n,provides:i}})(t),o=n.state,i=n.provides,r=Bo(t),a=r.canModifyAnnotations,s=r.canModifyContents,l=Di().provides,c=Ha(t).translate,d=Object.entries(o.pending).flatMap(function(e){var t=v(e,2),n=t[0];return t[1].map(function(e){return{item:e,pageNumber:Number(n)+1}})}).sort(function(e,t){return e.pageNumber-t.pageNumber});return F("div",{class:"flex h-full flex-col"},F("div",{class:"border-border-subtle border-b p-3"},F("h2",{class:"text-fg-primary text-md font-semibold"},c("redaction.panel.title",{fallback:"Redactions"})),d.length>0&&F("p",{class:"text-fg-muted text-sm"},1===d.length?c("redaction.panel.itemCount",{fallback:"1 pending redaction",params:{count:1}}):c("redaction.panel.itemCountPlural",{fallback:"".concat(d.length," pending redactions"),params:{count:d.length}}))),F("div",{class:"flex-1 overflow-y-auto p-3"},0===d.length?F(Sb,{documentId:t}):F("div",{class:"space-y-2"},d.map(function(e){var t,n=e.item,r=e.pageNumber;return F(Ib,{key:n.id,item:n,pageNumber:r,onSelect:function(){return function(e){null==i||i.selectPending(e.page,e.id),null==l||l.scrollToPage({pageNumber:e.page+1,pageCoordinates:{x:e.rect.origin.x,y:e.rect.origin.y},alignX:50,alignY:25,behavior:"smooth"})}(n)},isSelected:(null===(t=o.selected)||void 0===t?void 0:t.id)===n.id})}))),d.length>0&&F("div",{class:"border-border-subtle flex gap-2 border-t p-3"},F(ff,{onClick:function(){null==i||i.clearPending()},disabled:!a,className:"border-border-default bg-bg-surface text-fg-secondary hover:bg-interactive-hover flex-1 rounded-md border px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},c("redaction.panel.clearAll",{fallback:"Clear All"})),F(ff,{onClick:function(){null==i||i.commitAllPending()},disabled:!s,className:"bg-accent text-fg-on-accent hover:!bg-accent-hover flex-1 rounded-md border border-transparent px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},c("redaction.panel.redactAll",{fallback:"Redact All"}))))}function Mb(e){var t=e.schema,n=e.documentId,o=e.props,i=o.menuWrapperProps,r=o.rect,a=o.placement,s={position:"absolute",pointerEvents:"auto",cursor:"default",left:"50%",transform:"translateX(-50%)"};return null!=a&&a.suggestTop?s.top=-50:s.top=r.size.height+8,F("div",h(h({},i),Hr(t)),F("div",{style:s,className:"border-border-subtle bg-bg-elevated rounded-lg border shadow-lg"},F("div",{className:"flex items-center gap-1 p-1"},t.items.map(function(e){return F(Db,{key:e.id,item:e,documentId:n,props:o})}))))}function Pb(e){var t=e.item,n=e.documentId,o=Ra(t.commandId,n);return null!=o&&o.visible?F("div",h({},Hr(t)),F(Wv,{commandId:t.commandId,documentId:n,variant:t.variant})):null}function Db(e){var t,n=e.item,o=e.documentId,i=e.props;switch(n.type){case"command-button":return F(Pb,{item:n,documentId:o});case"divider":return F("div",h({},Hr(n)),F("div",{className:"bg-border-default h-6 w-px","aria-hidden":"true"}));case"group":return F("div",h({className:"flex items-center gap-".concat(null!==(t=n.gap)&&void 0!==t?t:1)},Hr(n)),n.items.map(function(e){return F(Db,{key:e.id,item:e,documentId:o,props:i})}));default:return null}}function Rb(e){var t,n,o=e.schema,i=e.documentId,r=e.className,a=o.content,s=o.position,l=la().renderCustomComponent,c=(t=s.anchor,(n={"top-left":"top-0 left-0","top-center":"top-0 left-1/2 -translate-x-1/2","top-right":"top-0 right-0","center-left":"top-1/2 left-0 -translate-y-1/2",center:"top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2","center-right":"top-1/2 right-0 -translate-y-1/2","bottom-left":"bottom-0 left-0","bottom-center":"bottom-0 left-1/2 -translate-x-1/2","bottom-right":"bottom-0 right-0"})[t]||n["bottom-center"]),d=function(e){if(e){var t={};return e.top&&(t.top=e.top),e.right&&(t.right=e.right),e.bottom&&(t.bottom=e.bottom),e.left&&(t.left=e.left),Object.keys(t).length>0?t:void 0}}(s.offset);return F("div",{className:"z-3 absolute ".concat(c," ").concat(r||""),style:d,"data-overlay-id":o.id},l(a.componentId,i))}function zb(e){var t=e.open,n=e.title,o=e.children,i=e.onClose,r=e.onExited,a=e.className,s=e.showCloseButton,l=void 0===s||s,c=De(null),d=v(Se(t),2),u=d[0],h=d[1],m=v(Se(!1),2),g=m[0],p=m[1];Me(function(){if(t)h(!0),requestAnimationFrame(function(){p(!0)});else if(u){p(!1);var e=setTimeout(function(){h(!1),null==r||r()},200);return function(){return clearTimeout(e)}}},[t,u,r]),Me(function(){if(t){var e=function(e){"Escape"===e.key&&(null==i||i())};return document.addEventListener("keydown",e),function(){return document.removeEventListener("keydown",e)}}},[t,i]);return Me(function(){return document.body.style.overflow=u?"hidden":"",function(){document.body.style.overflow=""}},[u]),u?He("div",{ref:c,className:"fixed inset-0 z-50 transition-opacity duration-200 md:flex md:items-center md:justify-center ".concat(g&&t?"bg-bg-overlay":"bg-transparent"),onClick:function(e){e.target===c.current&&(null==i||i())},children:He("div",{className:Yp("bg-bg-surface md:border-border-subtle relative flex h-full w-full flex-col transition-all duration-200 md:h-auto md:w-[28rem] md:max-w-[90vw] md:rounded-lg md:border md:shadow-lg",g&&t?"scale-100 opacity-100":"scale-95 opacity-0",a),onClick:function(e){return e.stopPropagation()},children:[(n||l)&&He("div",{className:"border-border-subtle flex flex-shrink-0 items-center justify-between border-b px-6 py-4",children:[n&&He("h2",{className:"text-fg-primary text-lg font-semibold",children:n}),l&&He(ff,{onClick:i,className:"hover:bg-interactive-hover p-1",children:He(gf,{icon:"x",className:"h-5 w-5"})})]}),He("div",{className:"flex-1 overflow-y-auto px-6 py-4 md:max-h-[80vh] md:flex-none",children:o})]})}):null}function Tb(e){var t=e.documentId,n=e.isOpen,o=e.onClose,i=e.onExited,r=Di().provides,a=nm().provides,s=Ha(t).translate,l=v(Se("all"),2),c=l[0],d=l[1],u=v(Se(""),2),h=u[0],m=u[1],g=v(Se(!0),2),p=g[0],f=g[1],y=v(Se(!1),2),b=y[0],w=y[1],x=v(Se(""),2),C=x[0],k=x[1],I=null==r?void 0:r.forDocument(t).getMetrics(),S=(null==I?void 0:I.currentPage)||1,A=(null==r?void 0:r.forDocument(t).getTotalPages())||0;Me(function(){n&&(d("all"),m(""),f(!0),w(!1),k(""))},[n]);var M=("custom"!==c||h.trim().length>0)&&!b;return F(zb,{open:null!=n&&n,title:s("print.title"),onClose:o,onExited:i,className:"md:w-[32rem]"},F("div",{className:"space-y-6"},F("div",null,F("label",{className:"text-fg-secondary mb-3 block text-sm font-medium"},s("print.pages")),F("div",{className:"space-y-2"},F("label",{className:"flex items-center"},F("input",{type:"radio",name:"pageRange",value:"all",checked:"all"===c,onChange:function(){return d("all")},disabled:b,className:"accent-accent mr-2"}),F("span",{className:"text-fg-primary text-sm"},s("print.all"))),F("label",{className:"flex items-center"},F("input",{type:"radio",name:"pageRange",value:"current",checked:"current"===c,onChange:function(){return d("current")},disabled:b,className:"accent-accent mr-2"}),F("span",{className:"text-fg-primary text-sm"},s("print.current",{params:{currentPage:S}}))),F("label",{className:"flex items-start"},F("input",{type:"radio",name:"pageRange",value:"custom",checked:"custom"===c,onChange:function(){return d("custom")},disabled:b,className:"accent-accent mr-2 mt-0.5"}),F("div",{className:"flex-1"},F("span",{className:"text-fg-primary mb-1 block text-sm"},s("print.specify")),F("input",{type:"text",placeholder:s("print.specifyEG"),value:h,onInput:function(e){return m(e.target.value)},disabled:"custom"!==c||b,className:"w-full rounded-md border px-3 py-1 text-base ".concat("custom"!==c||b?"bg-interactive-disabled text-fg-muted":"border-border-default bg-bg-input text-fg-primary focus:border-accent focus:ring-accent"," focus:outline-none focus:ring-1")}),"custom"===c&&h.trim()&&A>0&&F("p",{className:"text-fg-muted mt-1 text-xs"},s("print.current",{params:{totalPages:A}})))))),F("div",null,F("label",{className:"flex items-center"},F("input",{type:"checkbox",checked:p,onChange:function(e){return f(e.target.checked)},disabled:b,className:"accent-accent mr-2"}),F("span",{className:"text-fg-secondary text-sm font-medium"},s("print.annotation")))),b&&F("div",{className:"bg-state-info-light flex items-center space-x-3 rounded-md p-3"},F(yy,{className:"text-accent"}),F("span",{className:"text-accent text-sm"},C)),F("div",{className:"border-border-subtle flex justify-end space-x-3 border-t pt-4"},F(ff,{onClick:o,disabled:b,className:"border-border-default bg-bg-surface text-fg-secondary hover:bg-interactive-hover rounded-md border px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},s("print.cancel")),F(ff,{onClick:function(){var e;"current"===c?e=String(S):"custom"===c&&(e=h.trim()||void 0);var n={includeAnnotations:p,pageRange:e};try{w(!0),k(s("print.loading"));var i=null==a?void 0:a.forDocument(t).print(n);i&&(i.onProgress(function(e){k(e.message)}),i.wait(function(){w(!1),k(""),null==o||o()},function(e){console.error("Print failed:",e),w(!1),k("")}))}catch(e){console.error("Print failed:",e),w(!1),k("")}},disabled:!M,className:"bg-accent text-fg-on-accent hover:!bg-accent-hover flex items-center space-x-2 rounded-md border border-transparent px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},b&&F(yy,{size:"sm"}),F("span",null,s(b?"print.printing":"print.print"))))))}function Eb(e){var t,n=e.documentId,o=e.isOpen,i=e.onClose,r=e.onExited,s=e.source,l=Di().provides,c=xh().provides,d=Ul().provides,u=Ha(n).translate,h=v(Se("url"),2),m=h[0],g=h[1],p=v(Se(""),2),f=p[0],y=p[1],b=v(Se(1),2),w=b[0],x=b[1],C=(null==l?void 0:l.forDocument(n).getTotalPages())||1,k=null==c?void 0:c.forDocument(n),I=null==d?void 0:d.forDocument(n),S=null==k?void 0:k.getSelectedAnnotation(),A=null!==(t=null==I?void 0:I.getFormattedSelection())&&void 0!==t?t:[];Me(function(){o&&(g("url"),y(""),x(1))},[o]);var M="page"===m||f.trim().length>0;return F(zb,{open:null!=o&&o,title:u("link.title")||"Insert Link or Page",onClose:i,onExited:r,className:"md:w-[28rem]"},F("form",{onSubmit:function(e){e.preventDefault(),function(){var e;if("url"===m){if(!f.trim())return;e={type:"action",action:{type:Et.URI,uri:f.trim()}}}else e={type:"destination",destination:{pageIndex:w-1,zoom:{mode:At.FitPage},view:[]}};var t=function(){if(!S)return!1;var t,n="segmentRects"in S.object?S.object.segmentRects:[S.object.rect],o=a(null!=n?n:[]);try{for(o.s();!(t=o.n()).done;){var i=t.value;null==k||k.createAnnotation(S.object.pageIndex,{id:_n(),type:Ot.LINK,pageIndex:S.object.pageIndex,rect:i,inReplyToId:S.object.id,replyType:Ut.Group,target:e,strokeStyle:Bt.UNDERLINE,strokeColor:"#0000FF",strokeWidth:2})}}catch(e){o.e(e)}finally{o.f()}return!0},n=function(){if(0===A.length)return!1;var t,n=null==I?void 0:I.getSelectedText(),o=a(A);try{var i=function(){var o=t.value;null==n||n.wait(function(t){var n,i=_n();null==k||k.createAnnotation(o.pageIndex,{id:i,created:new Date,flags:["print"],type:Ot.HIGHLIGHT,blendMode:zt.Multiply,pageIndex:o.pageIndex,rect:o.rect,segmentRects:o.segmentRects,strokeColor:"#FFFFFF",opacity:0,custom:{text:t.join("\n")}});var r,s=a(null!==(n=o.segmentRects)&&void 0!==n?n:[o.rect]);try{for(s.s();!(r=s.n()).done;){var l=r.value;null==k||k.createAnnotation(o.pageIndex,{id:_n(),type:Ot.LINK,pageIndex:o.pageIndex,rect:l,inReplyToId:i,replyType:Ut.Group,target:e,strokeStyle:Bt.UNDERLINE,strokeColor:"#0000FF",strokeWidth:2})}}catch(e){s.e(e)}finally{s.f()}null==k||k.selectAnnotation(o.pageIndex,i)},Ln)};for(o.s();!(t=o.n()).done;)i()}catch(e){o.e(e)}finally{o.f()}return null==I||I.clear(),!0};"annotation"===s?t():"selection"===s?n():t()||n(),null==i||i()}()},className:"space-y-6"},F("div",{className:"border-border-subtle flex border-b"},F(Qp,{active:"url"===m,onClick:function(){return g("url")}},u("link.url")||"URL"),F(Qp,{active:"page"===m,onClick:function(){return g("page")}},u("link.page")||"Page")),F("div",{className:"bg-bg-muted rounded-lg"},"url"===m?F("div",null,F("label",{className:"text-fg-secondary mb-2 block text-sm font-medium"},u("link.enterUrl")||"Enter URL"),F("input",{type:"url",value:f,onInput:function(e){return y(e.target.value)},placeholder:"https://example.com",className:"border-border-default bg-bg-input text-fg-primary focus:border-accent focus:ring-accent w-full rounded-md border px-3 py-2 text-base focus:outline-none focus:ring-1",autoFocus:!0})):F("div",null,F("label",{className:"text-fg-secondary mb-2 block text-sm font-medium"},u("link.enterPage")||"Enter Page Number"),F("input",{type:"number",min:1,max:C,value:w,onInput:function(e){var t=parseInt(e.target.value,10);isNaN(t)||x(Math.max(1,Math.min(C,t)))},className:"border-border-default bg-bg-input text-fg-primary focus:border-accent focus:ring-accent w-full rounded-md border px-3 py-2 text-base focus:outline-none focus:ring-1",autoFocus:!0}),F("p",{className:"text-fg-muted mt-1 text-xs"},u("link.pageRange",{params:{totalPages:C}})||"Page 1 to ".concat(C)))),F("div",{className:"border-border-subtle flex justify-end space-x-3 border-t pt-4"},F(ff,{type:"button",onClick:i,className:"border-border-default bg-bg-surface text-fg-secondary hover:bg-interactive-hover rounded-md border px-4 py-2 text-sm"},u("common.cancel")||"Cancel"),F(ff,{type:"submit",disabled:!M,className:"bg-accent text-fg-on-accent hover:!bg-accent-hover rounded-md border border-transparent px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},u("link.link")||"Link"))))}function _b(e){var t=e.documentId,n=hi().provides,o=Ri(t),i=o.provides,r=o.state,a=r.currentPage,s=r.totalPages,l=v(Se(!1),2),c=l[0],d=l[1],u=v(Se(!1),2),h=u[0],m=u[1],g=De(null),p=v(Se(a.toString()),2),f=p[0],y=p[1],b=De(null);Me(function(){y(a.toString())},[a]);var w=ze(function(){g.current&&clearTimeout(g.current),g.current=setTimeout(function(){h||d(!1)},4e3)},[h]);Me(function(){if(n)return n.onScrollActivity(function(e){e.documentId===t&&(d(!0),w())})},[n,t,w]),Me(function(){return function(){g.current&&clearTimeout(g.current)}},[]);return s<=1?null:F("div",{onMouseEnter:function(){m(!0),d(!0),g.current&&clearTimeout(g.current)},onMouseLeave:function(){m(!1),w()},className:"pointer-events-auto"},F("div",{className:"border-border-default bg-bg-surface flex items-center gap-1 rounded-lg border p-1 shadow-lg transition-opacity duration-300 ".concat(c?"opacity-100":"opacity-0")},F(Wv,{commandId:"scroll:previous-page",documentId:t,variant:"icon"}),F("div",{className:"flex items-center gap-1 px-1"},F("input",{ref:b,type:"text",inputMode:"numeric",pattern:"[0-9]*",value:f,onChange:function(e){var t=e.target.value.replace(/[^0-9]/g,"");y(t)},onFocus:function(){setTimeout(function(){var e;return null===(e=b.current)||void 0===e?void 0:e.select()},0)},onBlur:function(){var e,t=parseInt(f,10);!isNaN(t)&&t>=1&&t<=s?null==i||null===(e=i.scrollToPage)||void 0===e||e.call(i,{pageNumber:t}):y(a.toString())},onKeyDown:function(e){"Enter"===e.key?e.target.blur():"Escape"===e.key&&(y(a.toString()),e.target.blur())},className:"border-border-default bg-bg-input text-fg-primary focus:border-accent focus:ring-accent h-7 w-10 rounded border px-1 text-center text-base focus:outline-none focus:ring-1"}),F("span",{className:"text-fg-secondary text-sm"},"  ",s)),F(Wv,{commandId:"scroll:next-page",documentId:t,variant:"icon"})))}var Nb=function(e,t,n){return!function(e,t,n){return ho(e.core,t,n)}(e,t,n)},Lb={"zoom:in":{id:"zoom:in",labelKey:"zoom.in",icon:"zoomIn",shortcuts:["Ctrl+=","Meta+=","Ctrl+NumpadAdd","Meta+NumpadAdd"],categories:["zoom","zoom-in"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).zoomIn()}},"zoom:out":{id:"zoom:out",labelKey:"zoom.out",icon:"zoomOut",shortcuts:["Ctrl+-","Meta+-","Ctrl+NumpadSubtract","Meta+NumpadSubtract"],categories:["zoom","zoom-out"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).zoomOut()}},"zoom:fit-page":{id:"zoom:fit-page",labelKey:"zoom.fitPage",icon:"fitToPage",shortcuts:["Ctrl+0","Meta+0"],categories:["zoom","zoom-fit-page"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).requestZoom(Wa.FitPage)},active:function(e){var t,n=e.state,o=e.documentId;return(null===(t=n.plugins.zoom)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.zoomLevel)===Wa.FitPage}},"zoom:fit-width":{id:"zoom:fit-width",labelKey:"zoom.fitWidth",icon:"fitToWidth",shortcuts:["Ctrl+1","Meta+1"],categories:["zoom","zoom-fit-width"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).requestZoom(Wa.FitWidth)},active:function(e){var t,n=e.state,o=e.documentId;return(null===(t=n.plugins.zoom)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.zoomLevel)===Wa.FitWidth}},"zoom:marquee":{id:"zoom:marquee",labelKey:"zoom.marquee",icon:"zoomInArea",shortcuts:["Ctrl+M","Meta+M"],categories:["zoom","zoom-marquee"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).toggleMarqueeZoom()},active:function(e){var t,n,o=e.state,i=e.documentId;return null!==(t=null===(n=o.plugins.zoom)||void 0===n||null===(n=n.documents[i])||void 0===n?void 0:n.isMarqueeZoomActive)&&void 0!==t&&t}},"zoom:25":{id:"zoom:25",label:"25%",categories:["zoom","zoom-level","zoom-level-25"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).requestZoom(.25)},active:function(e){var t,n=e.state,o=e.documentId;return.25===(null===(t=n.plugins.zoom)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.zoomLevel)}},"zoom:50":{id:"zoom:50",label:"50%",categories:["zoom","zoom-level","zoom-level-50"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).requestZoom(.5)},active:function(e){var t,n=e.state,o=e.documentId;return.5===(null===(t=n.plugins.zoom)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.zoomLevel)}},"zoom:100":{id:"zoom:100",label:"100%",categories:["zoom","zoom-level","zoom-level-100"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).requestZoom(1)},active:function(e){var t,n=e.state,o=e.documentId;return 1===(null===(t=n.plugins.zoom)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.zoomLevel)}},"zoom:125":{id:"zoom:125",label:"125%",categories:["zoom","zoom-level","zoom-level-125"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).requestZoom(1.25)},active:function(e){var t,n=e.state,o=e.documentId;return 1.25===(null===(t=n.plugins.zoom)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.zoomLevel)}},"zoom:150":{id:"zoom:150",label:"150%",categories:["zoom","zoom-level","zoom-level-150"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).requestZoom(1.5)},active:function(e){var t,n=e.state,o=e.documentId;return 1.5===(null===(t=n.plugins.zoom)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.zoomLevel)}},"zoom:200":{id:"zoom:200",label:"200%",categories:["zoom","zoom-level","zoom-level-200"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).requestZoom(2)},active:function(e){var t,n=e.state,o=e.documentId;return 2===(null===(t=n.plugins.zoom)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.zoomLevel)}},"zoom:400":{id:"zoom:400",label:"400%",categories:["zoom","zoom-level","zoom-level-400"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).requestZoom(4)},active:function(e){var t,n=e.state,o=e.documentId;return 4===(null===(t=n.plugins.zoom)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.zoomLevel)}},"zoom:800":{id:"zoom:800",label:"800%",categories:["zoom","zoom-level","zoom-level-800"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).requestZoom(8)},active:function(e){var t,n=e.state,o=e.documentId;return 8===(null===(t=n.plugins.zoom)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.zoomLevel)}},"zoom:1600":{id:"zoom:1600",label:"1600%",categories:["zoom","zoom-level","zoom-level-1600"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("zoom"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).requestZoom(16)},active:function(e){var t,n=e.state,o=e.documentId;return 16===(null===(t=n.plugins.zoom)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.zoomLevel)}},"zoom:toggle-menu":{id:"zoom:toggle-menu",labelKey:"zoom.menu",icon:"chevronDown",iconProps:{className:"h-3.5 w-3.5"},categories:["zoom","zoom-menu"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("ui"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).toggleMenu("zoom-menu","zoom:toggle-menu","zoom-menu-button")},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins.ui)||void 0===t?void 0:t.documents[o];return void 0!==(null==i?void 0:i.openMenus["zoom-menu"])}},"zoom:toggle-menu-mobile":{id:"zoom:toggle-menu-mobile",labelKey:"zoom.menu",icon:"zoomIn",categories:["zoom","zoom-menu"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("ui"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).toggleMenu("zoom-menu","zoom:toggle-menu-mobile","zoom-menu-button")},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins.ui)||void 0===t?void 0:t.documents[o];return void 0!==(null==i?void 0:i.openMenus["zoom-menu"])}},"pan:toggle":{id:"pan:toggle",labelKey:"pan.toggle",icon:"hand",shortcuts:["h"],categories:["tools","pan"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("pan"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).togglePan()},active:function(e){var t,n,o=e.state,i=e.documentId;return null!==(t=null===(n=o.plugins.pan)||void 0===n||null===(n=n.documents[i])||void 0===n?void 0:n.isPanMode)&&void 0!==t&&t}},"pointer:toggle":{id:"pointer:toggle",labelKey:"pointer.toggle",icon:"pointer",shortcuts:["p"],categories:["tools","pointer"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("interaction-manager"))||void 0===t?void 0:t.provides();if(i){var r=i.forDocument(o);"pointerMode"===r.getActiveMode()?r.activateDefaultMode():r.activate("pointerMode")}},active:function(e){var t,n=e.state,o=e.documentId;return"pointerMode"===(null===(t=n.plugins["interaction-manager"])||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.activeMode)}},"left-action-menu:overflow-menu":{id:"left-action-menu:overflow-menu",labelKey:"menu.moreOptions",icon:"dots",categories:["ui","ui-menu"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("ui"))||void 0===t?void 0:t.provides();i&&i.toggleMenu("left-action-menu","left-action-menu:overflow-menu","overflow-left-action-menu-button",o)},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins.ui)||void 0===t?void 0:t.documents[o];return void 0!==(null==i?void 0:i.openMenus["left-action-menu"])}},"capture:screenshot":{id:"capture:screenshot",labelKey:"capture.screenshot",icon:"screenshot",shortcuts:["Ctrl+Shift+S","Meta+Shift+S"],categories:["tools","capture","capture-screenshot"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("capture"))||void 0===t?void 0:t.provides();if(i){var r=i.forDocument(o);r.isMarqueeCaptureActive()?r.disableMarqueeCapture():r.enableMarqueeCapture()}},active:function(e){var t,n=e.state,o=e.documentId;return"marqueeCapture"===(null===(t=n.plugins["interaction-manager"].documents[o])||void 0===t?void 0:t.activeMode)}},"document:menu":{id:"document:menu",labelKey:"document.menu",icon:"menu",categories:["document","document-menu"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin(Bi);if(o&&o.provides){var i=o.provides();if(i)i.forDocument(n).toggleMenu("document-menu","document:menu","document-menu-button")}},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins.ui)||void 0===t?void 0:t.documents[o];return void 0!==(null==i?void 0:i.openMenus["document-menu"])}},"document:open":{id:"document:open",labelKey:"document.open",icon:"fileImport",shortcuts:["Ctrl+O","Meta+O"],categories:["document","document-open"],action:function(e){var t,n=null===(t=e.registry.getPlugin("document-manager"))||void 0===t?void 0:t.provides();null==n||n.openFileDialog()}},"document:close":{id:"document:close",labelKey:"document.close",icon:"x",shortcuts:["Ctrl+W","Meta+W"],categories:["document","document-close"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("document-manager"))||void 0===t?void 0:t.provides();null==i||i.closeDocument(o)}},"document:print":{id:"document:print",labelKey:"document.print",icon:"print",shortcuts:["Ctrl+P","Meta+P"],categories:["document","document-print"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin(Bi);if(o&&o.provides){var i=o.provides();if(i)i.forDocument(n).openModal("print-modal")}},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.Print)}},"document:protect":{id:"document:protect",labelKey:"document.protect",icon:"lock",categories:["document","document-protect"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("ui"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).openModal("protect-modal")}},"document:export":{id:"document:export",labelKey:"document.export",icon:"download",categories:["document","document-export"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("export"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).download()}},"document:capture":{id:"document:capture",labelKey:"capture.screenshot",icon:"screenshot",categories:["document","document-capture"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("capture"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).toggleMarqueeCapture()},active:function(e){var t,n=e.state,o=e.documentId;return"marqueeCapture"===(null===(t=n.plugins["interaction-manager"])||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.activeMode)}},"document:fullscreen":{id:"document:fullscreen",labelKey:"document.fullscreen",icon:function(e){var t;return null!==(t=e.state.plugins.fullscreen)&&void 0!==t&&t.isFullscreen?"fullscreenExit":"fullscreen"},shortcuts:["F11"],categories:["document","document-fullscreen"],action:function(e){var t,n=null===(t=e.registry.getPlugin("fullscreen"))||void 0===t?void 0:t.provides();n&&(n.isFullscreen()?n.exitFullscreen():n.enableFullscreen())},active:function(e){var t,n;return null!==(t=null===(n=e.state.plugins.fullscreen)||void 0===n?void 0:n.isFullscreen)&&void 0!==t&&t}},"panel:toggle-sidebar":{id:"panel:toggle-sidebar",labelKey:"panel.sidebar",icon:"sidebar",categories:["panel","panel-sidebar"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin(Bi);if(o&&o.provides){var i=o.provides();if(i)i.forDocument(n).toggleSidebar("left","main","sidebar-panel")}},active:function(e){var t=e.state,n=e.documentId;return Yr(t.plugins,n,"left","main","sidebar-panel")}},"panel:toggle-search":{id:"panel:toggle-search",labelKey:"panel.search",icon:"search",shortcuts:["Ctrl+F","Meta+F"],categories:["panel","panel-search"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin(Bi);if(o&&o.provides){var i=o.provides();if(i)i.forDocument(n).toggleSidebar("right","main","search-panel")}},active:function(e){var t=e.state,n=e.documentId;return Yr(t.plugins,n,"right","main","search-panel")}},"panel:toggle-comment":{id:"panel:toggle-comment",labelKey:"panel.comment",icon:"comment",categories:["panel","panel-comment"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin(Bi);if(o&&o.provides){var i=o.provides();if(i)i.forDocument(n).toggleSidebar("right","main","comment-panel")}},active:function(e){var t=e.state,n=e.documentId;return Yr(t.plugins,n,"right","main","comment-panel")}},"panel:toggle-redaction":{id:"panel:toggle-redaction",labelKey:"panel.redaction",icon:"redactionSidebar",categories:["panel","panel-redaction","redaction"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin(Bi);if(o&&o.provides){var i=o.provides();if(i)i.forDocument(n).toggleSidebar("right","main","redaction-panel")}},active:function(e){var t=e.state,n=e.documentId;return Yr(t.plugins,n,"right","main","redaction-panel")}},"panel:toggle-annotation-style":{id:"panel:toggle-annotation-style",labelKey:"panel.annotationStyle",icon:"palette",categories:["panel","panel-annotation-style"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin(Bi);if(o&&o.provides){var i=o.provides();if(i)i.forDocument(n).toggleSidebar("left","main","annotation-panel")}},active:function(e){var t=e.state,n=e.documentId;return Yr(t.plugins,n,"left","main","annotation-panel")},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"page:settings":{id:"page:settings",labelKey:"page.settings",icon:"viewSettings",categories:["page","page-settings"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin(Bi);if(o&&o.provides){var i=o.provides();if(i)i.forDocument(n).toggleMenu("page-settings-menu","page:settings","page-settings-button")}},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins.ui)||void 0===t?void 0:t.documents[o];return void 0!==(null==i?void 0:i.openMenus["page-settings-menu"])}},"spread:none":{id:"spread:none",labelKey:"page.single",icon:"singlePage",categories:["page","spread","spread-none"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("spread"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).setSpreadMode(Ti.None)},active:function(e){var t,n=e.state,o=e.documentId;return(null===(t=n.plugins.spread)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.spreadMode)===Ti.None}},"spread:odd":{id:"spread:odd",labelKey:"page.twoOdd",icon:"doublePage",categories:["page","spread","spread-odd"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("spread"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).setSpreadMode(Ti.Odd)},active:function(e){var t,n=e.state,o=e.documentId;return(null===(t=n.plugins.spread)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.spreadMode)===Ti.Odd}},"spread:even":{id:"spread:even",labelKey:"page.twoEven",icon:"book2",categories:["page","spread","spread-even"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("spread"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).setSpreadMode(Ti.Even)},active:function(e){var t,n=e.state,o=e.documentId;return(null===(t=n.plugins.spread)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.spreadMode)===Ti.Even}},"rotate:clockwise":{id:"rotate:clockwise",labelKey:"rotate.clockwise",icon:"rotateClockwise",shortcuts:["Ctrl+]","Meta+]"],categories:["page","rotate","rotate-clockwise"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("rotate"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).rotateForward()}},"rotate:counter-clockwise":{id:"rotate:counter-clockwise",labelKey:"rotate.counterClockwise",icon:"rotateCounterClockwise",shortcuts:["Ctrl+[","Meta+["],categories:["page","rotate","rotate-counter-clockwise"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("rotate"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).rotateBackward()}},"scroll:vertical":{id:"scroll:vertical",labelKey:"page.vertical",icon:"vertical",categories:["page","scroll","scroll-vertical"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("scroll"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).setScrollStrategy(pi.Vertical)},active:function(e){var t,n=e.state,o=e.documentId;return(null===(t=n.plugins.scroll)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.strategy)===pi.Vertical}},"scroll:horizontal":{id:"scroll:horizontal",labelKey:"page.horizontal",icon:"horizontal",categories:["page","scroll","scroll-horizontal"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("scroll"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).setScrollStrategy(pi.Horizontal)},active:function(e){var t,n=e.state,o=e.documentId;return(null===(t=n.plugins.scroll)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.strategy)===pi.Horizontal}},"scroll:next-page":{id:"scroll:next-page",labelKey:"page.next",icon:"chevronRight",categories:["page","navigation","navigation-next"],shortcuts:["Ctrl+]","Meta+]","ArrowRight"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("scroll"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).scrollToNextPage()},disabled:function(e){var t,n,o=e.state,i=e.documentId;return(null===(t=o.plugins.scroll)||void 0===t||null===(t=t.documents[i])||void 0===t?void 0:t.currentPage)>=(null===(n=o.plugins.scroll)||void 0===n||null===(n=n.documents[i])||void 0===n?void 0:n.totalPages)}},"scroll:previous-page":{id:"scroll:previous-page",labelKey:"page.previous",icon:"chevronLeft",categories:["page","navigation","navigation-previous"],shortcuts:["Ctrl+[","Meta+[","ArrowLeft"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("scroll"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).scrollToPreviousPage()},disabled:function(e){var t,n=e.state,o=e.documentId;return(null===(t=n.plugins.scroll)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.currentPage)<=1}},"mode:view":{id:"mode:view",labelKey:"mode.view",categories:["mode","mode-view"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin("ui"))||void 0===t?void 0:t.provides(),a=null===(n=o.getPlugin("interaction-manager"))||void 0===n?void 0:n.provides();if(r&&a){var s=a.forDocument(i);s&&(s.activateDefaultMode(),r.forDocument(i).closeToolbarSlot("top","secondary"))}},active:function(e){var t=e.state,n=e.documentId;return!Zr(t.plugins,n,"top","secondary")}},"mode:annotate":{id:"mode:annotate",labelKey:"mode.annotate",categories:["mode","mode-annotate","annotation"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("ui"))||void 0===t?void 0:t.provides();i&&i.setActiveToolbar("top","secondary","annotation-toolbar",o)},active:function(e){var t=e.state,n=e.documentId;return Zr(t.plugins,n,"top","secondary","annotation-toolbar")}},"mode:shapes":{id:"mode:shapes",labelKey:"mode.shapes",categories:["mode","mode-shapes","annotation"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("ui"))||void 0===t?void 0:t.provides();i&&i.setActiveToolbar("top","secondary","shapes-toolbar",o)},active:function(e){var t=e.state,n=e.documentId;return Zr(t.plugins,n,"top","secondary","shapes-toolbar")}},"mode:redact":{id:"mode:redact",labelKey:"mode.redact",categories:["mode","mode-redact","redaction"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("ui"))||void 0===t?void 0:t.provides();i&&i.setActiveToolbar("top","secondary","redaction-toolbar",o)},active:function(e){var t=e.state,n=e.documentId;return Zr(t.plugins,n,"top","secondary","redaction-toolbar")}},"tabs:overflow-menu":{id:"tabs:overflow-menu",labelKey:"tabs.overflowMenu",icon:"dots",categories:["ui","ui-menu"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("ui"))||void 0===t?void 0:t.provides();i&&i.toggleMenu("mode-tabs-overflow-menu","tabs:overflow-menu","overflow-tabs-button",o)},active:function(e){var t,n=e.state,o=e.documentId;return void 0!==(null===(t=n.plugins.ui)||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.openMenus["mode-tabs-overflow-menu"])}},"annotation:add-highlight":{id:"annotation:add-highlight",labelKey:"annotation.highlight",icon:"highlight",iconProps:function(e){var t;return{primaryColor:null===(t=ad(e.state.plugins.annotation,"highlight"))||void 0===t?void 0:t.strokeColor}},categories:["annotation","annotation-markup","annotation-highlight"],action:function(e){var t,n,o,i=e.registry,r=e.documentId,s=null===(t=i.getPlugin(Ic))||void 0===t?void 0:t.provides(),l=null===(n=i.getPlugin(Bs))||void 0===n?void 0:n.provides(),c=null===(o=i.getPlugin("ui"))||void 0===o?void 0:o.provides();if(l&&s&&c){var d=null==s?void 0:s.forDocument(r),u=null==l?void 0:l.forDocument(r);if(d&&u){var m=s.getTool("highlight");if(m&&du(m)){var g=m.defaults,p=u.getFormattedSelection(),f=u.getSelectedText();if(p.length>0){var v,y=a(p);try{var b=function(){var e=v.value,t=_n(),n=function(n){d.createAnnotation(e.pageIndex,h({id:t,created:new Date,flags:["print"],type:Ot.HIGHLIGHT,blendMode:zt.Multiply,strokeColor:g.strokeColor,opacity:g.opacity,pageIndex:e.pageIndex,rect:e.rect,segmentRects:e.segmentRects},null!=n&&{custom:{text:n}})),d.selectAnnotation(e.pageIndex,t)};f.wait(function(e){return n(e.join("\n"))},function(){return n()})};for(y.s();!(v=y.n()).done;)b()}catch(e){y.e(e)}finally{y.f()}u.clear(),d.setActiveTool("highlight"),c.setActiveToolbar("top","secondary","annotation-toolbar",r)}else{var w;"highlight"===(null===(w=d.getActiveTool())||void 0===w?void 0:w.id)?d.setActiveTool(null):d.setActiveTool("highlight")}}}}},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[Ic])||void 0===t?void 0:t.documents[o];return"highlight"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:add-underline":{id:"annotation:add-underline",labelKey:"annotation.underline",icon:"underline",iconProps:function(e){var t;return{primaryColor:null===(t=ad(e.state.plugins.annotation,"underline"))||void 0===t?void 0:t.strokeColor}},categories:["annotation","annotation-markup","annotation-underline"],action:function(e){var t,n,o,i=e.registry,r=e.documentId,s=null===(t=i.getPlugin(Ic))||void 0===t?void 0:t.provides(),l=null===(n=i.getPlugin(Bs))||void 0===n?void 0:n.provides(),c=null===(o=i.getPlugin("ui"))||void 0===o?void 0:o.provides();if(l&&s&&c){var d=null==s?void 0:s.forDocument(r),u=null==l?void 0:l.forDocument(r);if(d&&u){var m=s.getTool("underline");if(m&&hu(m)){var g=m.defaults,p=u.getFormattedSelection(),f=u.getSelectedText();if(p.length>0){var v,y=a(p);try{var b=function(){var e=v.value,t=_n(),n=function(n){d.createAnnotation(e.pageIndex,h({id:t,created:new Date,flags:["print"],type:Ot.UNDERLINE,strokeColor:g.strokeColor,opacity:g.opacity,pageIndex:e.pageIndex,rect:e.rect,segmentRects:e.segmentRects},null!=n&&{custom:{text:n}})),d.selectAnnotation(e.pageIndex,t)};f.wait(function(e){return n(e.join("\n"))},function(){return n()})};for(y.s();!(v=y.n()).done;)b()}catch(e){y.e(e)}finally{y.f()}u.clear(),d.setActiveTool("underline"),c.setActiveToolbar("top","secondary","annotation-toolbar",r)}else{var w;"underline"===(null===(w=d.getActiveTool())||void 0===w?void 0:w.id)?d.setActiveTool(null):d.setActiveTool("underline")}}}}},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[Ic])||void 0===t?void 0:t.documents[o];return"underline"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:add-strikeout":{id:"annotation:add-strikeout",labelKey:"annotation.strikeout",icon:"strikethrough",iconProps:function(e){var t;return{primaryColor:null===(t=ad(e.state.plugins.annotation,"strikeout"))||void 0===t?void 0:t.strokeColor}},categories:["annotation","annotation-markup","annotation-strikeout"],action:function(e){var t,n,o,i=e.registry,r=e.documentId,s=null===(t=i.getPlugin(Ic))||void 0===t?void 0:t.provides(),l=null===(n=i.getPlugin(Bs))||void 0===n?void 0:n.provides(),c=null===(o=i.getPlugin("ui"))||void 0===o?void 0:o.provides();if(l&&s&&c){var d=null==s?void 0:s.forDocument(r),u=null==l?void 0:l.forDocument(r);if(d&&u){var m=s.getTool("strikeout");if(m&&mu(m)){var g=m.defaults,p=u.getFormattedSelection(),f=u.getSelectedText();if(p.length>0){var v,y=a(p);try{var b=function(){var e=v.value,t=_n(),n=function(n){d.createAnnotation(e.pageIndex,h({id:t,created:new Date,flags:["print"],type:Ot.STRIKEOUT,strokeColor:g.strokeColor,opacity:g.opacity,pageIndex:e.pageIndex,rect:e.rect,segmentRects:e.segmentRects},null!=n&&{custom:{text:n}})),d.selectAnnotation(e.pageIndex,t)};f.wait(function(e){return n(e.join("\n"))},function(){return n()})};for(y.s();!(v=y.n()).done;)b()}catch(e){y.e(e)}finally{y.f()}u.clear(),d.setActiveTool("strikeout"),c.setActiveToolbar("top","secondary","annotation-toolbar",r)}else{var w;"strikeout"===(null===(w=d.getActiveTool())||void 0===w?void 0:w.id)?d.setActiveTool(null):d.setActiveTool("strikeout")}}}}},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[Ic])||void 0===t?void 0:t.documents[o];return"strikeout"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:add-squiggly":{id:"annotation:add-squiggly",labelKey:"annotation.squiggly",icon:"squiggly",iconProps:function(e){var t;return{primaryColor:null===(t=ad(e.state.plugins.annotation,"squiggly"))||void 0===t?void 0:t.strokeColor}},categories:["annotation","annotation-markup","annotation-squiggly"],action:function(e){var t,n,o,i=e.registry,r=e.documentId,s=null===(t=i.getPlugin(Ic))||void 0===t?void 0:t.provides(),l=null===(n=i.getPlugin(Bs))||void 0===n?void 0:n.provides(),c=null===(o=i.getPlugin("ui"))||void 0===o?void 0:o.provides();if(l&&s&&c){var d=null==s?void 0:s.forDocument(r),u=null==l?void 0:l.forDocument(r);if(d&&u){var m=s.getTool("squiggly");if(m&&uu(m)){var g=m.defaults,p=u.getFormattedSelection(),f=u.getSelectedText();if(p.length>0){var v,y=a(p);try{var b=function(){var e=v.value,t=_n(),n=function(n){d.createAnnotation(e.pageIndex,h({id:t,created:new Date,flags:["print"],type:Ot.SQUIGGLY,strokeColor:g.strokeColor,opacity:g.opacity,pageIndex:e.pageIndex,rect:e.rect,segmentRects:e.segmentRects},null!=n&&{custom:{text:n}})),d.selectAnnotation(e.pageIndex,t)};f.wait(function(e){return n(e.join("\n"))},function(){return n()})};for(y.s();!(v=y.n()).done;)b()}catch(e){y.e(e)}finally{y.f()}u.clear(),d.setActiveTool("squiggly"),c.setActiveToolbar("top","secondary","annotation-toolbar",r)}else{var w;"squiggly"===(null===(w=d.getActiveTool())||void 0===w?void 0:w.id)?d.setActiveTool(null):d.setActiveTool("squiggly")}}}}},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[Ic])||void 0===t?void 0:t.documents[o];return"squiggly"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:add-insert-text":{id:"annotation:add-insert-text",labelKey:"annotation.insertText",icon:"insertText",iconProps:function(e){var t;return{primaryColor:null===(t=ad(e.state.plugins.annotation,"insertText"))||void 0===t?void 0:t.strokeColor}},categories:["annotation","annotation-markup","annotation-insert-text"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(Ic))||void 0===t?void 0:t.provides(),a=null==r?void 0:r.forDocument(i);a&&("insertText"===(null===(n=a.getActiveTool())||void 0===n?void 0:n.id)?a.setActiveTool(null):a.setActiveTool("insertText"))},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[Ic])||void 0===t?void 0:t.documents[o];return"insertText"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:add-replace-text":{id:"annotation:add-replace-text",labelKey:"annotation.replaceText",icon:"replaceText",iconProps:function(e){var t;return{primaryColor:null===(t=ad(e.state.plugins.annotation,"replaceText"))||void 0===t?void 0:t.strokeColor}},categories:["annotation","annotation-markup","annotation-replace-text"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(Ic))||void 0===t?void 0:t.provides(),a=null==r?void 0:r.forDocument(i);a&&("replaceText"===(null===(n=a.getActiveTool())||void 0===n?void 0:n.id)?a.setActiveTool(null):a.setActiveTool("replaceText"))},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[Ic])||void 0===t?void 0:t.documents[o];return"replaceText"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:add-ink":{id:"annotation:add-ink",labelKey:"annotation.ink",icon:"pencilMarker",iconProps:function(e){var t;return{primaryColor:null===(t=ad(e.state.plugins.annotation,"ink"))||void 0===t?void 0:t.color}},categories:["annotation","annotation-ink"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(Ic))||void 0===t?void 0:t.provides(),a=null==r?void 0:r.forDocument(i);a&&("ink"===(null===(n=a.getActiveTool())||void 0===n?void 0:n.id)?a.setActiveTool(null):a.setActiveTool("ink"))},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[Ic])||void 0===t?void 0:t.documents[o];return"ink"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:add-text":{id:"annotation:add-text",labelKey:"annotation.text",icon:"freeText",iconProps:function(e){var t;return{primaryColor:null===(t=ad(e.state.plugins.annotation,"freeText"))||void 0===t?void 0:t.fontColor}},categories:["annotation","annotation-text"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(Ic))||void 0===t?void 0:t.provides(),a=null==r?void 0:r.forDocument(i);a&&("freeText"===(null===(n=a.getActiveTool())||void 0===n?void 0:n.id)?a.setActiveTool(null):a.setActiveTool("freeText"))},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[Ic])||void 0===t?void 0:t.documents[o];return"freeText"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:add-comment":{id:"annotation:add-comment",labelKey:"annotation.comment",icon:"message",iconProps:function(e){var t;return{primaryColor:null===(t=ad(e.state.plugins.annotation,"textComment"))||void 0===t?void 0:t.strokeColor}},categories:["annotation","annotation-comment-tool"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(Ic))||void 0===t?void 0:t.provides(),a=null==r?void 0:r.forDocument(i);a&&("textComment"===(null===(n=a.getActiveTool())||void 0===n?void 0:n.id)?a.setActiveTool(null):a.setActiveTool("textComment"))},active:function(e){var t,n=e.state,o=e.documentId;return"textComment"===(null===(t=n.plugins[Ic])||void 0===t||null===(t=t.documents[o])||void 0===t?void 0:t.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:add-stamp":{id:"annotation:add-stamp",labelKey:"annotation.stamp",icon:"photo",categories:["annotation","annotation-stamp"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(Ic))||void 0===t?void 0:t.provides(),a=null==r?void 0:r.forDocument(i);a&&("stamp"===(null===(n=a.getActiveTool())||void 0===n?void 0:n.id)?a.setActiveTool(null):a.setActiveTool("stamp"))},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[Ic])||void 0===t?void 0:t.documents[o];return"stamp"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:add-rectangle":{id:"annotation:add-rectangle",labelKey:"annotation.rectangle",icon:"square",iconProps:function(e){var t,n,o=e.state;return{primaryColor:null===(t=ad(o.plugins.annotation,"square"))||void 0===t?void 0:t.strokeColor,secondaryColor:null===(n=ad(o.plugins.annotation,"square"))||void 0===n?void 0:n.color}},categories:["annotation","annotation-shape","annotation-rectangle"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(Ic))||void 0===t?void 0:t.provides(),a=null==r?void 0:r.forDocument(i);a&&("square"===(null===(n=a.getActiveTool())||void 0===n?void 0:n.id)?a.setActiveTool(null):a.setActiveTool("square"))},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[Ic])||void 0===t?void 0:t.documents[o];return"square"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:add-circle":{id:"annotation:add-circle",labelKey:"annotation.circle",icon:"circle",iconProps:function(e){var t,n,o=e.state;return{primaryColor:null===(t=ad(o.plugins.annotation,"circle"))||void 0===t?void 0:t.strokeColor,secondaryColor:null===(n=ad(o.plugins.annotation,"circle"))||void 0===n?void 0:n.color}},categories:["annotation","annotation-shape","annotation-circle"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(Ic))||void 0===t?void 0:t.provides(),a=null==r?void 0:r.forDocument(i);a&&("circle"===(null===(n=a.getActiveTool())||void 0===n?void 0:n.id)?a.setActiveTool(null):a.setActiveTool("circle"))},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[Ic])||void 0===t?void 0:t.documents[o];return"circle"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:add-line":{id:"annotation:add-line",labelKey:"annotation.line",icon:"line",iconProps:function(e){var t;return{primaryColor:null===(t=ad(e.state.plugins.annotation,"line"))||void 0===t?void 0:t.strokeColor}},categories:["annotation","annotation-shape","annotation-line"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(Ic))||void 0===t?void 0:t.provides(),a=null==r?void 0:r.forDocument(i);a&&("line"===(null===(n=a.getActiveTool())||void 0===n?void 0:n.id)?a.setActiveTool(null):a.setActiveTool("line"))},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[Ic])||void 0===t?void 0:t.documents[o];return"line"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:add-arrow":{id:"annotation:add-arrow",labelKey:"annotation.arrow",icon:"lineArrow",iconProps:function(e){var t;return{primaryColor:null===(t=ad(e.state.plugins.annotation,"line"))||void 0===t?void 0:t.strokeColor}},categories:["annotation","annotation-shape","annotation-arrow"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(Ic))||void 0===t?void 0:t.provides(),a=null==r?void 0:r.forDocument(i);a&&("lineArrow"===(null===(n=a.getActiveTool())||void 0===n?void 0:n.id)?a.setActiveTool(null):a.setActiveTool("lineArrow"))},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[Ic])||void 0===t?void 0:t.documents[o];return"lineArrow"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:add-polygon":{id:"annotation:add-polygon",labelKey:"annotation.polygon",icon:"polygon",iconProps:function(e){var t,n,o=e.state;return{primaryColor:null===(t=ad(o.plugins.annotation,"polygon"))||void 0===t?void 0:t.strokeColor,secondaryColor:null===(n=ad(o.plugins.annotation,"polygon"))||void 0===n?void 0:n.color}},categories:["annotation","annotation-shape","annotation-polygon"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(Ic))||void 0===t?void 0:t.provides(),a=null==r?void 0:r.forDocument(i);a&&("polygon"===(null===(n=a.getActiveTool())||void 0===n?void 0:n.id)?a.setActiveTool(null):a.setActiveTool("polygon"))},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[Ic])||void 0===t?void 0:t.documents[o];return"polygon"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:add-polyline":{id:"annotation:add-polyline",labelKey:"annotation.polyline",icon:"zigzag",iconProps:function(e){var t;return{primaryColor:null===(t=ad(e.state.plugins.annotation,"polyline"))||void 0===t?void 0:t.strokeColor}},categories:["annotation","annotation-shape","annotation-polyline"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(Ic))||void 0===t?void 0:t.provides(),a=null==r?void 0:r.forDocument(i);a&&("polyline"===(null===(n=a.getActiveTool())||void 0===n?void 0:n.id)?a.setActiveTool(null):a.setActiveTool("polyline"))},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[Ic])||void 0===t?void 0:t.documents[o];return"polyline"===(null==i?void 0:i.activeToolId)},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:delete-selected":{id:"annotation:delete-selected",labelKey:"annotation.deleteSelected",icon:"trash",categories:["annotation","annotation-delete"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(Ic))||void 0===t?void 0:t.provides(),r=null==i?void 0:i.forDocument(o);if(r){var a=r.getSelectedAnnotation();a&&r.deleteAnnotation(a.object.pageIndex,a.object.id)}},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:delete-all-selected":{id:"annotation:delete-all-selected",labelKey:"annotation.deleteAllSelected",icon:"trash",categories:["annotation","annotation-delete","annotation-group"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(Ic))||void 0===t?void 0:t.provides(),r=null==i?void 0:i.forDocument(o);if(r){var a=r.getSelectedAnnotations();0!==a.length&&(r.deleteAnnotations(a.map(function(e){return{pageIndex:e.object.pageIndex,id:e.object.id}})),r.deselectAnnotation())}},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:toggle-group":{id:"annotation:toggle-group",labelKey:function(e){var t,n=e.registry,o=e.documentId;return"ungroup"===(null===(t=n.getPlugin(Ic))||void 0===t?void 0:t.provides().forDocument(o).getGroupingAction())?"annotation.ungroup":"annotation.group"},icon:function(e){var t,n=e.registry,o=e.documentId;return"ungroup"===(null===(t=n.getPlugin(Ic))||void 0===t?void 0:t.provides().forDocument(o).getGroupingAction())?"ungroup":"group"},categories:["annotation","annotation-group"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(Ic))||void 0===t?void 0:t.provides().forDocument(o);if(i){var r=i.getGroupingAction();if("ungroup"===r){var a=i.getSelectedAnnotations();a.length>0&&i.ungroupAnnotations(a[0].object.id)}else"group"===r&&i.groupAnnotations()}},disabled:function(e){var t,n=e.registry,o=e.state,i=e.documentId;return!!Nb(o,i,Qt.ModifyAnnotations)||"disabled"===(null===(t=n.getPlugin(Ic))||void 0===t?void 0:t.provides().forDocument(i).getGroupingAction())}},"annotation:overflow-tools":{id:"annotation:overflow-tools",labelKey:"annotation.moreTools",icon:"dots",categories:["annotation","annotation-overflow"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("ui"))||void 0===t?void 0:t.provides();if(i){var r=i.forDocument(o);r&&r.toggleMenu("annotation-tools-menu","annotation:overflow-tools","overflow-annotation-tools")}},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins.ui)||void 0===t?void 0:t.documents[o];return void 0!==(null==i?void 0:i.openMenus["annotation-tools-menu"])},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:overflow-shapes":{id:"annotation:overflow-shapes",labelKey:"annotation.moreTools",icon:"dots",categories:["annotation","annotation-shape","annotation-overflow"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("ui"))||void 0===t?void 0:t.provides();if(i){var r=i.forDocument(o);r&&r.toggleMenu("shapes-tools-menu","annotation:overflow-shapes","overflow-shapes-tools")}},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins.ui)||void 0===t?void 0:t.documents[o];return void 0!==(null==i?void 0:i.openMenus["shapes-tools-menu"])},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:add-link":{id:"annotation:add-link",labelKey:"annotation.addLink",icon:"link",categories:["annotation","annotation-link"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("ui"))||void 0===t?void 0:t.provides();i&&i.forDocument(o).openModal("link-modal",{source:"selection"})},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:toggle-annotation-style":{id:"annotation:toggle-annotation-style",labelKey:"annotation.style",icon:"palette",categories:["annotation","annotation-style"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin(Bi);if(o&&o.provides){var i=o.provides();if(i)i.forDocument(n).toggleSidebar("left","main","annotation-panel")}},active:function(e){var t=e.state,n=e.documentId;return Yr(t.plugins,n,"left","main","annotation-panel")},visible:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(Ic))||void 0===t?void 0:t.provides().forDocument(o),r=null==i?void 0:i.getSelectedAnnotation();return!r||r.object.type!==Ot.LINK},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:toggle-link":{id:"annotation:toggle-link",labelKey:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(Ic))||void 0===t?void 0:t.provides().forDocument(o);if(!i)return"annotation.addLink";var r=i.getSelectedAnnotation();return r&&i.hasAttachedLinks(r.object.id)?"annotation.removeLink":"annotation.addLink"},icon:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(Ic))||void 0===t?void 0:t.provides().forDocument(o);if(!i)return"link";var r=i.getSelectedAnnotation();return r&&i.hasAttachedLinks(r.object.id)?"linkOff":"link"},categories:["annotation","annotation-link"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin(Ic))||void 0===t?void 0:t.provides(),a=null===(n=o.getPlugin("ui"))||void 0===n?void 0:n.provides();if(r&&a){var s=r.forDocument(i),l=s.getSelectedAnnotation();l&&(s.hasAttachedLinks(l.object.id)?s.deleteAttachedLinks(l.object.id):a.forDocument(i).openModal("link-modal",{source:"annotation"}))}},visible:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(Ic))||void 0===t?void 0:t.provides().forDocument(o),r=null==i?void 0:i.getSelectedAnnotation();return!r||r.object.type!==Ot.LINK&&r.object.type!==Ot.REDACT},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyAnnotations)}},"annotation:toggle-comment":{id:"annotation:toggle-comment",labelKey:"annotation.comment",icon:"comment",categories:["annotation","annotation-comment"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin(Bi);if(o&&o.provides){var i=o.provides();if(i)i.forDocument(n).toggleSidebar("right","main","comment-panel")}},active:function(e){var t=e.state,n=e.documentId;return Yr(t.plugins,n,"right","main","comment-panel")},visible:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(Ic))||void 0===t?void 0:t.provides().forDocument(o),r=null==i?void 0:i.getSelectedAnnotation();return!r||r.object.type!==Ot.LINK}},"annotation:goto-link":{id:"annotation:goto-link",labelKey:"annotation.gotoLink",icon:"externalLink",categories:["annotation","annotation-link"],action:function(e){var t,n,o,i=e.registry,r=e.documentId,a=null===(t=i.getPlugin(Ic))||void 0===t?void 0:t.provides(),s=null===(n=i.getPlugin("scroll"))||void 0===n?void 0:n.provides();if(a){var l=a.forDocument(r),c=l.getSelectedAnnotation();if(c){var d=null;if(function(e){return e.object.type===Ot.LINK}(c))d=c.object;else{var u=l.getAttachedLinks(c.object.id);u.length>0&&(d=u[0].object)}if(null!==(o=d)&&void 0!==o&&o.target){var h=d.target;if("action"===h.type){var m=h.action;if(m.type===Et.URI)window.open(m.uri,"_blank","noopener,noreferrer");else if(m.type===Et.Goto&&s){var g=m.destination;s.forDocument(r).scrollToPage({pageNumber:g.pageIndex+1,behavior:"smooth"})}}else if("destination"===h.type&&s){var p=h.destination;s.forDocument(r).scrollToPage({pageNumber:p.pageIndex+1,behavior:"smooth"})}}}}},visible:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(Ic))||void 0===t?void 0:t.provides();if(!i)return!1;var r=i.forDocument(o),a=null==r?void 0:r.getSelectedAnnotation();return!!a&&(a.object.type===Ot.LINK||r.hasAttachedLinks(a.object.id))}},"redaction:redact":{id:"redaction:redact",labelKey:"redaction.redact",icon:"redactArea",categories:["redaction","redaction-combined"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("redaction"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).toggleRedact()},active:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin("redaction"))||void 0===t?void 0:t.provides();return null!==(n=null==r?void 0:r.forDocument(i).isRedactActive())&&void 0!==n&&n},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyContents)}},"redaction:redact-area":{id:"redaction:redact-area",labelKey:"redaction.area",icon:"redactArea",categories:["redaction","redaction-area"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("redaction"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).toggleMarqueeRedact()},active:function(e){var t,n,o=e.registry,i=e.documentId,r=null===(t=o.getPlugin("redaction"))||void 0===t?void 0:t.provides();return null!==(n=null==r?void 0:r.forDocument(i).isMarqueeRedactActive())&&void 0!==n&&n},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyContents)}},"redaction:redact-text":{id:"redaction:redact-text",labelKey:"redaction.text",icon:"redact",categories:["redaction","redaction-text"],action:function(e){var t,n,o,i,r=e.registry,a=e.documentId,s=null===(t=r.getPlugin("redaction"))||void 0===t?void 0:t.provides(),l=null===(n=r.getPlugin(Bs))||void 0===n?void 0:n.provides(),c=null===(o=r.getPlugin("ui"))||void 0===o?void 0:o.provides();if(s&&l&&c){var d=s.forDocument(a),u=null==l?void 0:l.forDocument(a);(null!==(i=null==u?void 0:u.getFormattedSelection())&&void 0!==i?i:[]).length>0?(d.queueCurrentSelectionAsPending(),c.setActiveToolbar("top","secondary","redaction-toolbar",a)):d.toggleRedactSelection()}},active:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[wg])||void 0===t?void 0:t.documents[o];return(null==i?void 0:i.activeType)===Ym.RedactSelection},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyContents)}},"redaction:apply-all":{id:"redaction:apply-all",labelKey:"redaction.applyAll",icon:"check",categories:["redaction","redaction-apply"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("redaction"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).commitAllPending()},disabled:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[wg])||void 0===t?void 0:t.documents[o];return 0===(null==i?void 0:i.pendingCount)||Nb(n,o,Qt.ModifyContents)}},"redaction:clear-all":{id:"redaction:clear-all",labelKey:"redaction.clearAll",icon:"x",categories:["redaction","redaction-clear"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("redaction"))||void 0===t?void 0:t.provides();null==i||i.forDocument(o).clearPending()},disabled:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[wg])||void 0===t?void 0:t.documents[o];return 0===(null==i?void 0:i.pendingCount)||Nb(n,o,Qt.ModifyContents)}},"redaction:delete-selected":{id:"redaction:delete-selected",labelKey:"redaction.deleteSelected",icon:"trash",categories:["redaction","redaction-delete"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("redaction"))||void 0===t?void 0:t.provides(),r=null==i?void 0:i.forDocument(o).getSelectedPending();r&&(null==i||i.forDocument(o).removePending(r.page,r.id))}},"redaction:commit-selected":{id:"redaction:commit-selected",labelKey:"redaction.commitSelected",icon:"check",categories:["redaction","redaction-commit"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin("redaction"))||void 0===t?void 0:t.provides(),r=null==i?void 0:i.forDocument(o).getSelectedPending();r&&(null==i||i.forDocument(o).commitPending(r.page,r.id))}},"annotation:apply-redaction":{id:"annotation:apply-redaction",labelKey:"redaction.apply",icon:"check",categories:["annotation","annotation-redaction","redaction"],action:function(e){var t,n,o=e.registry,i=e.documentId,r=e.logger;r.debug("Command","ApplyRedaction","Starting for document: ".concat(i));var a=null===(t=o.getPlugin(Ic))||void 0===t?void 0:t.provides(),s=null===(n=o.getPlugin(wg))||void 0===n?void 0:n.provides();if(a&&s){var l=a.forDocument(i).getSelectedAnnotation();r.debug("Command","ApplyRedaction","Selected annotation: ".concat(l?JSON.stringify({id:l.object.id,type:l.object.type,pageIndex:l.object.pageIndex}):"none")),l&&l.object.type===Ot.REDACT?(r.debug("Command","ApplyRedaction","Calling commitPending for page ".concat(l.object.pageIndex,", id ").concat(l.object.id)),s.forDocument(i).commitPending(l.object.pageIndex,l.object.id),r.debug("Command","ApplyRedaction","commitPending called successfully")):r.warn("Command","ApplyRedaction","No valid redaction selected - selected: ".concat(!!l,", type: ").concat(null==l?void 0:l.object.type))}else r.warn("Command","ApplyRedaction","Missing plugins - annotation: ".concat(!!a,", redaction: ").concat(!!s))},visible:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(Ic))||void 0===t?void 0:t.provides().forDocument(o),r=null==i?void 0:i.getSelectedAnnotation();return(null==r?void 0:r.object.type)===Ot.REDACT},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.ModifyContents)}},"selection:copy-to-clipboard":{id:"selection:copy-to-clipboard",labelKey:"selection.copyToClipboard",icon:"copy",shortcuts:["Ctrl+C","Meta+C"],categories:["selection","selection-copy-to-clipboard"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin("selection"),i=null==o?void 0:o.provides().forDocument(n);null==i||i.copyToClipboard()},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.CopyContents)}},"selection:copy":{id:"selection:copy",labelKey:"selection.copy",icon:"copy",categories:["selection","selection-copy"],action:function(e){var t=e.registry,n=e.documentId,o=t.getPlugin("selection"),i=null==o?void 0:o.provides().forDocument(n);null==i||i.copyToClipboard(),null==i||i.clear()},disabled:function(e){var t=e.state,n=e.documentId;return Nb(t,n,Qt.CopyContents)}},"history:undo":{id:"history:undo",labelKey:"history.undo",icon:"arrowBackUp",shortcuts:["Ctrl+Z","Meta+Z"],categories:["history","history-undo"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(Fm))||void 0===t?void 0:t.provides();i&&i.forDocument(o).undo()},disabled:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[Fm])||void 0===t?void 0:t.documents[o];return!(null!=i&&i.global.canUndo)}},"history:redo":{id:"history:redo",labelKey:"history.redo",icon:"arrowForwardUp",shortcuts:["Ctrl+Y","Meta+Shift+Z"],categories:["history","history-redo"],action:function(e){var t,n=e.registry,o=e.documentId,i=null===(t=n.getPlugin(Fm))||void 0===t?void 0:t.provides();i&&i.forDocument(o).redo()},disabled:function(e){var t,n=e.state,o=e.documentId,i=null===(t=n.plugins[Fm])||void 0===t?void 0:t.documents[o];return!(null!=i&&i.global.canRedo)}}},Ob={"zoom.level":function(e){var t,n,o=e.state,i=e.documentId,r=i&&null!==(t=null===(n=o.plugins[qa])||void 0===n||null===(n=n.documents[i])||void 0===n?void 0:n.currentZoomLevel)&&void 0!==t?t:1;return{level:Math.round(100*r)}}},$b={colors:{background:{app:"#f3f4f6",surface:"#ffffff",surfaceAlt:"#f1f3f5",elevated:"#ffffff",overlay:"rgba(0, 0, 0, 0.5)",input:"#ffffff"},foreground:{primary:"#111827",secondary:"#374151",muted:"#6b7280",disabled:"#9ca3af",onAccent:"#ffffff"},border:{default:"#d1d5db",subtle:"#e5e7eb",strong:"#9ca3af"},accent:{primary:"#3b82f6",primaryHover:"#2563eb",primaryActive:"#1d4ed8",primaryLight:"#eff6ff",primaryForeground:"#ffffff"},interactive:{hover:"#f3f4f6",active:"#e5e7eb",selected:"#eff6ff",focus:"#3b82f6",focusRing:"#bfdbfe"},state:{error:"#ef4444",errorLight:"#fef2f2",warning:"#f59e0b",warningLight:"#fffbeb",success:"#22c55e",successLight:"#f0fdf4",info:"#3b82f6",infoLight:"#eff6ff"},tooltip:{background:"#111827",foreground:"#ffffff"},scrollbar:{track:"#f3f4f6",thumb:"#d1d5db",thumbHover:"#9ca3af"}}},jb={colors:{background:{app:"#111827",surface:"#1f2937",surfaceAlt:"#374151",elevated:"#1f2937",overlay:"rgba(0, 0, 0, 0.7)",input:"#374151"},foreground:{primary:"#f9fafb",secondary:"#e5e7eb",muted:"#9ca3af",disabled:"#6b7280",onAccent:"#111827"},border:{default:"#4b5563",subtle:"#374151",strong:"#6b7280"},accent:{primary:"#60a5fa",primaryHover:"#3b82f6",primaryActive:"#2563eb",primaryLight:"#1e3a5f",primaryForeground:"#111827"},interactive:{hover:"#374151",active:"#4b5563",selected:"#1e3a5f",focus:"#60a5fa",focusRing:"#1e40af"},state:{error:"#f87171",errorLight:"#7f1d1d",warning:"#fbbf24",warningLight:"#78350f",success:"#4ade80",successLight:"#14532d",info:"#60a5fa",infoLight:"#1e3a5f"},tooltip:{background:"#f9fafb",foreground:"#111827"},scrollbar:{track:"#1f2937",thumb:"#4b5563",thumbHover:"#6b7280"}}};function Fb(e,t){var n=h({},e);for(var o in t){var i=t[o];i&&"object"===w(i)&&!Array.isArray(i)?n[o]=Fb(e[o]||{},i):void 0!==i&&(n[o]=i)}return n}function Ub(e,t){return{colors:Fb(e.colors,t)}}function Hb(e){return"system"===e?"undefined"==typeof window?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":e}function Wb(e){return e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Bb(e){return":host {\n".concat(function(e){var t=[];return function e(n,o){for(var i=0,r=Object.entries(n);i1?F("div",{className:"bg-bg-surface-alt flex items-end pr-2 pt-2"},F("div",{className:"flex flex-1 items-end overflow-x-auto pl-4"},t.map(function(e){var t,o,i=n===e.id;return F("div",{key:e.id,onClick:function(){return l(e.id)},role:"tab",tabIndex:0,"aria-selected":i,onKeyDown:function(t){"Enter"!==t.key&&" "!==t.key||(t.preventDefault(),l(e.id))},className:"group relative flex min-w-[120px] max-w-[240px] cursor-pointer items-center gap-2 rounded-t-lg px-4 py-2 text-sm font-medium transition-all ".concat(i?"bg-bg-surface text-fg-primary z-10":"bg-bg-surface-alt text-fg-secondary hover:bg-interactive-hover hover:text-fg-primary")},F("span",{className:"min-w-0 flex-1 truncate"},null!==(t=e.name)&&void 0!==t?t:"Document ".concat(e.id.slice(0,8))),i&&F("button",{onClick:function(t){t.stopPropagation(),c(e.id)},"aria-label":"Close ".concat(null!==(o=e.name)&&void 0!==o?o:"document"),className:"hover:bg-interactive-hover flex-shrink-0 cursor-pointer rounded-full p-1 transition-all ".concat(i?"opacity-100":"opacity-0 group-hover:opacity-100")},F(gf,{icon:"x",size:14})))}),a&&F("button",{onClick:d,className:"text-fg-secondary hover:bg-interactive-hover hover:text-fg-primary mb-1.5 ml-1 flex-shrink-0 cursor-pointer rounded p-1.5 transition-colors","aria-label":"Open File",title:"Open File"},F(gf,{icon:"plus",size:14})))):null}function Gb(){var e=wa().provides,t=Ha().translate;return F("div",{className:"bg-bg-app flex h-full w-full items-center justify-center"},F("div",{className:"flex max-w-sm flex-col items-center text-center"},F("div",{className:"bg-accent-light mb-6 rounded-full p-5"},F(gf,{icon:"file",size:48,className:"text-accent"})),F("h2",{className:"text-fg-primary mb-2 text-xl font-semibold"},t("emptyState.title")),F("p",{className:"text-fg-secondary mb-6 text-sm leading-relaxed"},t("emptyState.description"),F("br",null),t("emptyState.descriptionMulti")),F("button",{onClick:function(){null==e||e.openFileDialog()},className:"bg-accent hover:bg-accent-hover text-accent-fg inline-flex cursor-pointer items-center gap-2 rounded-md px-5 py-2.5 text-sm font-medium shadow-sm transition-all"},F(gf,{icon:"plus",size:16}),t("emptyState.openButton")),F("p",{className:"text-fg-muted mt-4 text-xs"},t("emptyState.supportedFormats"))))}function Vb(e){var t=e.documentState,o=wa().provides,i=Ha().translate,r=v(Se(""),2),a=r[0],s=r[1],l=v(Se(!1),2),c=l[0],d=l[1];if(!t)return null;var u=t.name,h=t.errorCode,m=t.passwordProvided,p=h===tn.Password,f=p&&!m,y=p&&m;if(!p)return F("div",{className:"bg-bg-app flex h-full items-center justify-center p-8"},F("div",{className:"bg-bg-surface border-border-default flex max-w-sm flex-col items-center rounded-xl border p-6 text-center shadow-lg"},F("div",{className:"bg-state-error-light mb-4 rounded-full p-4"},F(gf,{icon:"alertTriangle",size:28,className:"text-state-error"})),F("h3",{className:"text-fg-primary text-lg font-semibold"},i("documentError.title")),F("p",{className:"text-fg-secondary mt-2 text-sm"},t.error||i("documentError.unknown")),h&&F("p",{className:"text-fg-muted mt-1 text-xs"},i("documentError.errorCode",{params:{code:String(h)}})),F("button",{onClick:function(){return null==o?void 0:o.closeDocument(t.id)},className:"bg-accent hover:bg-accent-hover text-accent-fg mt-5 w-full cursor-pointer rounded-md px-4 py-2.5 text-sm font-medium transition-colors"},i("documentError.close"))));var b=function(){var e=n(g().m(function e(){return g().w(function(e){for(;;)switch(e.n){case 0:if(o&&a.trim()){e.n=1;break}return e.a(2);case 1:d(!0),o.retryDocument(t.id,{password:a}).wait(function(){s(""),d(!1)},function(e){console.error("Retry failed:",e),d(!1)});case 2:return e.a(2)}},e)}));return function(){return e.apply(this,arguments)}}();return F("div",{className:"bg-bg-app flex h-full items-center justify-center p-8"},F("div",{className:"bg-bg-surface border-border-default w-full max-w-sm rounded-xl border p-6 shadow-lg"},F("div",{className:"flex flex-col items-center text-center"},F("div",{className:"bg-accent-light mb-4 rounded-full p-4"},F(gf,{icon:"lock",size:28,className:"text-accent"})),F("h3",{className:"text-fg-primary text-lg font-semibold"},i("passwordPrompt.title")),u&&F("p",{className:"text-fg-muted mt-1 text-sm"},u)),F("p",{className:"text-fg-secondary mt-4 text-center text-sm"},f&&i("passwordPrompt.required"),y&&i("passwordPrompt.incorrect")),F("div",{className:"mt-5"},F("label",{className:"text-fg-primary mb-1.5 block text-sm font-medium"},i("passwordPrompt.label")),F("input",{type:"password",value:a,onInput:function(e){return s(e.target.value)},onKeyDown:function(e){return"Enter"===e.key&&!c&&a.trim()&&b()},disabled:c,placeholder:i("passwordPrompt.placeholder"),className:"bg-bg-input border-border-default focus:border-accent focus:ring-accent text-fg-primary placeholder:text-fg-muted block w-full rounded-md border px-3 py-2.5 text-sm focus:outline-none focus:ring-1 disabled:opacity-50",autoFocus:!0})),y&&F("div",{className:"bg-state-error-light border-state-error mt-3 flex items-center gap-2 rounded-md border p-3"},F(gf,{icon:"alertTriangle",size:16,className:"text-state-error flex-shrink-0"}),F("p",{className:"text-state-error text-sm"},i("passwordPrompt.incorrectWarning"))),F("div",{className:"mt-6 flex gap-3"},F("button",{onClick:function(){return null==o?void 0:o.closeDocument(t.id)},disabled:c,className:"border-border-default text-fg-secondary hover:bg-interactive-hover flex-1 cursor-pointer rounded-md border px-4 py-2.5 text-sm font-medium transition-colors disabled:opacity-50"},i("passwordPrompt.cancel")),F("button",{onClick:b,disabled:c||!a.trim(),className:"bg-accent hover:bg-accent-hover text-accent-fg flex-1 cursor-pointer rounded-md px-4 py-2.5 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50"},i(c?"passwordPrompt.opening":"passwordPrompt.open")))))}function Kb(e){var t=e.documentId,n=e.className,o=Ra("mode:view",t),i=Ra("mode:annotate",t),r=Ra("mode:shapes",t),a=Ra("mode:redact",t),s=Ra("tabs:overflow-menu",t),l=Re(function(){return[o,i,r,a].find(function(e){return null==e?void 0:e.active})||o},[o,i,r,a]),c=ze(function(e){e.preventDefault(),e.stopPropagation(),s&&!s.disabled&&s.execute()},[s]);if(!s||!s.visible)return null;var d=s.active;return F("div",{style:{maxWidth:"100px",width:"100px"},className:n},F(ff,{className:"bg-bg-surface col-start-1 row-start-1 !w-full appearance-none rounded-md py-1.5 pl-3 pr-2 text-[13px] ".concat(d?"bg-interactive-selected ring-accent border-none shadow ring":"border-border-default outline-border-default hover:bg-interactive-hover hover:ring-accent outline outline-1 -outline-offset-1 hover:ring"," flex flex-row items-center justify-between gap-2"),onClick:c,disabled:s.disabled,style:{height:34}},F("span",{className:"min-w-0 flex-1 truncate text-left ".concat(d?"text-accent":"text-fg-primary")},null==l?void 0:l.label),F(gf,{icon:"chevronDown",className:"h-4 w-4 ".concat(d?"text-accent":"text-fg-secondary")})))}function Zb(e){var t=e.documentId,n=$m().provides,o=v(Se(!1),2),i=o[0],r=o[1],a=v(Se(null),2),s=a[0],l=a[1],c=v(Se(null),2),d=c[0],u=c[1],h=v(Se(null),2),m=h[0],g=h[1],p=De(null),f=De(null),y=Ha(t).translate,b=function(){p.current&&(URL.revokeObjectURL(p.current),p.current=null),m&&(URL.revokeObjectURL(m),g(null)),r(!1),l(null),u(null)};Me(function(){if(n)return n.onCaptureArea(function(e){var t=e.pageIndex,n=e.rect,o=e.blob;l({pageIndex:t,rect:n,blob:o});var i=URL.createObjectURL(o);p.current=i,u(i),r(!0)})},[n]);return F(H,null,F(zb,{open:i,onClose:b,title:y("capture.title"),className:"md:w-[48rem]"},F("div",{className:"space-y-6"},F("div",{className:"flex justify-center"},d&&F("img",{src:d,onLoad:function(){p.current&&(URL.revokeObjectURL(p.current),p.current=null)},alt:"Captured PDF area",style:{maxWidth:"100%",maxHeight:"400px",border:"1px solid #e5e7eb",borderRadius:"4px",display:"block"}})),F("div",{className:"border-border-subtle flex justify-end space-x-3 border-t pt-4"},F(ff,{onClick:b,className:"border-border-default bg-bg-surface text-fg-secondary hover:bg-interactive-hover rounded-md border px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},y("capture.cancel")),F(ff,{onClick:function(){if(s&&f.current){var e=URL.createObjectURL(s.blob);g(e),f.current.href=e,f.current.download="pdf-capture-page-".concat(s.pageIndex+1,".png"),f.current.click(),b()}},disabled:!s,className:"bg-accent text-fg-on-accent hover:!bg-accent-hover flex items-center space-x-2 rounded-md border border-transparent px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},y("capture.download"))))),F("a",{ref:f,style:{display:"none"},href:"",download:""}))}var Yb=[{flag:Qt.Print,labelKey:"protect.permissions.print"},{flag:Qt.PrintHighQuality,labelKey:"protect.permissions.printHighQuality"},{flag:Qt.CopyContents,labelKey:"protect.permissions.copy"},{flag:Qt.ExtractForAccessibility,labelKey:"protect.permissions.accessibility"},{flag:Qt.ModifyContents,labelKey:"protect.permissions.modify"},{flag:Qt.ModifyAnnotations,labelKey:"protect.permissions.annotations"},{flag:Qt.FillForms,labelKey:"protect.permissions.fillForms"},{flag:Qt.AssembleDocument,labelKey:"protect.permissions.assemble"}];function Xb(e){var t=e.permissions,n=e.translate,o=e.label;return F("div",null,F("label",{className:"text-fg-secondary mb-2 block text-sm font-medium"},null!=o?o:n("security.viewPermissions.restrictedActions")),F("div",{className:"grid grid-cols-1 gap-1 sm:grid-cols-2"},Yb.map(function(e){var o,i=(o=e.flag,0!==(t&o));return F("div",{key:e.flag,className:"flex items-center rounded-md p-2 ".concat(i?"text-fg-primary":"text-fg-muted")},F(gf,{icon:i?"check":"x",className:"mr-2 h-4 w-4 flex-shrink-0 ".concat(i?"text-state-success":"text-state-error")}),F("span",{className:"text-sm"},n(e.labelKey)))})))}function Qb(e){var t,n,o,i=e.documentId,r=e.isOpen,s=e.onClose,l=e.onExited,c=Ha(i).translate,d=wa().provides,u=jo(i),h=null==u?void 0:u.document,m=null!==(t=null==h?void 0:h.isEncrypted)&&void 0!==t&&t,g=null!==(n=null==h?void 0:h.isOwnerUnlocked)&&void 0!==n&&n,p=null!==(o=null==h?void 0:h.permissions)&&void 0!==o?o:0,f=v(Se("edit-protection"),2),y=f[0],b=f[1],w=v(Se(""),2),x=w[0],C=w[1],k=v(Se(!1),2),I=k[0],S=k[1],A=v(Se(!1),2),M=A[0],P=A[1],D=v(Se(null),2),R=D[0],z=D[1],T=v(Se(!1),2),E=T[0],_=T[1],N=v(Se(""),2),L=N[0],O=N[1],$=v(Se(""),2),j=$[0],U=$[1],H=v(Se(!1),2),W=H[0],B=H[1],q=v(Se(!1),2),G=q[0],V=q[1],K=v(Se(""),2),Z=K[0],Y=K[1],X=v(Se(""),2),Q=X[0],J=X[1],ee=v(Se(!1),2),te=ee[0],ne=ee[1],oe=Se(new Set(Yb.map(function(e){return e.flag}))),ie=v(oe,2),re=ie[0],ae=ie[1],se=v(Se(!1),2),le=se[0],ce=se[1],de=v(Se(null),2),ue=de[0],he=de[1];Me(function(){r&&(C(""),S(!1),P(!1),z(null),_(!1),O(""),U(""),B(!1),V(!1),Y(""),J(""),ne(!1),ae(new Set(Yb.map(function(e){return e.flag}))),ce(!1),he(null),b(m&&!g?"unlock":m&&g?"choose-action":"edit-protection"))},[r,m,g]);var me=L===j,ge=Z===Q,pe=!E||L.length>0&&me,fe=!G||Z.length>0&&ge,ve=(E||G)&&pe&&fe&&!le,ye=function(){d&&x&&(P(!0),z(null),d.unlockOwnerPermissions(i,x).wait(function(e){P(!1),e?b("choose-action"):z(c("security.unlock.invalidPassword"))},function(e){var t,n;P(!1),z(null!==(t=null===(n=e.reason)||void 0===n?void 0:n.message)&&void 0!==t?t:c("security.unlock.failed"))}))},be=function(){if(ve&&d){var e=0;if(G){var t,n=a(re);try{for(n.s();!(t=n.n()).done;){e|=t.value}}catch(e){n.e(e)}finally{n.f()}}else e=Qt.AllowAll;var o=E?L:"",r=G?Z:E?L:"";ce(!0),he(null),d.setDocumentEncryption(i,{userPassword:o,ownerPassword:r,allowedFlags:e}).wait(function(e){ce(!1),e?null==s||s():he(c("protect.applyFailed"))},function(e){var t,n;ce(!1),he(null!==(t=null===(n=e.reason)||void 0===n?void 0:n.message)&&void 0!==t?t:c("protect.applyFailed"))})}},we=function(){d&&(ce(!0),he(null),d.removeEncryption(i).wait(function(e){ce(!1),e?null==s||s():he(c("protect.removeFailed"))},function(e){var t,n;ce(!1),he(null!==(t=null===(n=e.reason)||void 0===n?void 0:n.message)&&void 0!==t?t:c("protect.removeFailed"))}))},xe=function(){return F("div",{className:"space-y-6"},F("div",{className:"bg-bg-subtle rounded-lg"},F("label",{className:"flex cursor-pointer items-start"},F("input",{type:"checkbox",checked:E,onChange:function(e){return _(e.target.checked)},className:"accent-accent mr-3 mt-0.5"}),F("div",{className:"flex-1"},F("span",{className:"text-fg-primary block font-medium"},c("protect.openPassword.title")),F("span",{className:"text-fg-muted text-sm"},c("protect.openPassword.description")))),E&&F("div",{className:"mt-4 space-y-3 pl-6"},F("div",null,F("label",{className:"text-fg-secondary mb-1 block text-sm"},c("protect.openPassword.label")),F("div",{className:"relative"},F("input",{type:W?"text":"password",value:L,onInput:function(e){return O(e.target.value)},placeholder:c("protect.openPassword.placeholder"),className:"border-border-default bg-bg-input text-fg-primary focus:border-accent focus:ring-accent w-full rounded-md border px-3 py-2 pr-10 text-sm focus:outline-none focus:ring-1"}),F("button",{type:"button",onClick:function(){return B(!W)},className:"text-fg-muted hover:text-fg-secondary absolute right-2 top-1/2 -translate-y-1/2"},F(gf,{icon:W?"eye-off":"eye",className:"h-4 w-4"})))),F("div",null,F("label",{className:"text-fg-secondary mb-1 block text-sm"},c("protect.openPassword.confirm")),F("input",{type:W?"text":"password",value:j,onInput:function(e){return U(e.target.value)},placeholder:c("protect.openPassword.confirmPlaceholder"),className:"border-border-default bg-bg-input text-fg-primary focus:ring-accent w-full rounded-md border px-3 py-2 text-sm focus:outline-none focus:ring-1 ".concat(j&&!me?"border-state-error focus:border-state-error":"focus:border-accent")}),j&&!me&&F("p",{className:"text-state-error mt-1 text-xs"},c("protect.passwordMismatch"))))),F("div",{className:"bg-bg-subtle rounded-lg"},F("label",{className:"flex cursor-pointer items-start"},F("input",{type:"checkbox",checked:G,onChange:function(e){return V(e.target.checked)},className:"accent-accent mr-3 mt-0.5"}),F("div",{className:"flex-1"},F("span",{className:"text-fg-primary block font-medium"},c("protect.permissions.title")),F("span",{className:"text-fg-muted text-sm"},c("protect.permissions.description")))),G&&F("div",{className:"mt-4 space-y-4 pl-6"},F("div",{className:"border-border-subtle border-b pb-4"},F("div",null,F("label",{className:"text-fg-secondary mb-1 block text-sm"},c("protect.ownerPassword.label")),F("div",{className:"relative"},F("input",{type:te?"text":"password",value:Z,onInput:function(e){return Y(e.target.value)},placeholder:c("protect.ownerPassword.placeholder"),className:"border-border-default bg-bg-input text-fg-primary focus:border-accent focus:ring-accent w-full rounded-md border px-3 py-2 pr-10 text-sm focus:outline-none focus:ring-1"}),F("button",{type:"button",onClick:function(){return ne(!te)},className:"text-fg-muted hover:text-fg-secondary absolute right-2 top-1/2 -translate-y-1/2"},F(gf,{icon:te?"eye-off":"eye",className:"h-4 w-4"})))),F("div",{className:"mt-3"},F("label",{className:"text-fg-secondary mb-1 block text-sm"},c("protect.ownerPassword.confirm")),F("input",{type:te?"text":"password",value:Q,onInput:function(e){return J(e.target.value)},placeholder:c("protect.ownerPassword.confirmPlaceholder"),className:"border-border-default bg-bg-input text-fg-primary focus:ring-accent w-full rounded-md border px-3 py-2 text-sm focus:outline-none focus:ring-1 ".concat(Q&&!ge?"border-state-error focus:border-state-error":"focus:border-accent")}),Q&&!ge&&F("p",{className:"text-state-error mt-1 text-xs"},c("protect.passwordMismatch")))),F("div",null,F("label",{className:"text-fg-secondary mb-2 block text-sm font-medium"},c("protect.permissions.allowedActions")),F("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-2"},Yb.map(function(e){return F("label",{key:e.flag,className:"hover:bg-bg-surface flex cursor-pointer items-center rounded-md p-2 transition-colors"},F("input",{type:"checkbox",checked:re.has(e.flag),onChange:function(){return t=e.flag,void ae(function(e){var n=new Set(e);return n.has(t)?n.delete(t):(n.add(t),t===Qt.PrintHighQuality&&n.add(Qt.Print)),n});var t},className:"accent-accent mr-2"}),F("span",{className:"text-fg-primary text-sm"},c(e.labelKey)))}))))),E&&G&&F("div",{className:"bg-state-info-light flex items-start space-x-2 rounded-md p-3"},F(gf,{icon:"info",className:"text-accent mt-0.5 h-4 w-4 flex-shrink-0"}),F("p",{className:"text-fg-secondary text-sm"},c("protect.bothPasswordsNote"))),!E&&!G&&!ue&&F("div",{className:"bg-state-warning-light flex items-start space-x-2 rounded-md p-3"},F(gf,{icon:"alertTriangle",className:"text-state-warning mt-0.5 h-4 w-4 flex-shrink-0"}),F("p",{className:"text-fg-secondary text-sm"},c("protect.noProtectionSelected"))),ue&&F("div",{className:"bg-state-error-light flex items-start space-x-2 rounded-md p-3"},F(gf,{icon:"alertTriangle",className:"text-state-error mt-0.5 h-4 w-4 flex-shrink-0"}),F("p",{className:"text-state-error text-sm"},ue)),F("div",{className:"border-border-subtle flex justify-end space-x-3 border-t pt-4"},m&&g&&F(ff,{onClick:function(){return b("choose-action")},disabled:le,className:"border-border-default bg-bg-surface text-fg-secondary hover:bg-interactive-hover rounded-md border px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},c("common.back")),F(ff,{onClick:be,disabled:!ve,className:"bg-accent text-fg-on-accent hover:!bg-accent-hover flex items-center space-x-2 rounded-md border border-transparent px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},le&&F(yy,{size:"sm"}),F("span",null,c(le?"protect.applying":"protect.apply")))))};return F(zb,{open:null!=r&&r,title:function(){switch(y){case"unlock":return c("protect.encrypted.title");case"choose-action":return c("protect.modifyProtection.title");case"remove-protection":return c("protect.removeProtection.title");default:return c("protect.title")}}(),onClose:s,onExited:l,className:"md:w-[36rem]"},function(){switch(y){case"unlock":return F("div",{className:"space-y-5"},F("p",{className:"text-fg-secondary text-sm"},c("protect.encrypted.description")),F("div",null,F("label",{className:"text-fg-primary mb-2 block text-sm font-medium"},c("protect.encrypted.enterOwnerPassword")),F("div",{className:"relative"},F("input",{type:I?"text":"password",value:x,onInput:function(e){return C(e.target.value)},placeholder:c("protect.ownerPassword.placeholder"),className:"border-border-default bg-bg-input text-fg-primary focus:border-accent focus:ring-accent w-full rounded-md border px-3 py-2 pr-10 text-sm focus:outline-none focus:ring-1",onKeyDown:function(e){"Enter"===e.key&&x&&ye()}}),F("button",{type:"button",onClick:function(){return S(!I)},className:"text-fg-muted hover:text-fg-secondary absolute right-2 top-1/2 -translate-y-1/2"},F(gf,{icon:I?"eye-off":"eye",className:"h-4 w-4"}))),R&&F("p",{className:"text-state-error mt-2 text-xs"},R)),F(Xb,{permissions:p,translate:c}),F("div",{className:"border-border-subtle flex justify-end space-x-3 border-t pt-4"},F(ff,{onClick:ye,disabled:!x||M,className:"bg-accent text-fg-on-accent hover:!bg-accent-hover flex items-center space-x-2 rounded-md border border-transparent px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},M&&F(yy,{size:"sm"}),F("span",null,c("protect.encrypted.unlockAndEdit")))));case"choose-action":return F("div",{className:"space-y-5"},F("p",{className:"text-fg-secondary text-sm"},c("protect.modifyProtection.description")),F("div",{className:"space-y-3"},F("button",{type:"button",onClick:function(){return b("edit-protection")},className:"border-border-default hover:border-accent hover:bg-bg-subtle flex w-full items-center rounded-lg border p-4 text-left transition-colors"},F("div",{className:"bg-accent/10 mr-4 rounded-full p-2"},F(gf,{icon:"lock",size:20,className:"text-accent"})),F("div",null,F("span",{className:"text-fg-primary block font-medium"},c("protect.modifyProtection.changeOption")),F("span",{className:"text-fg-muted text-sm"},c("protect.modifyProtection.changeDescription")))),F("button",{type:"button",onClick:function(){return b("remove-protection")},className:"border-border-default hover:border-state-error hover:bg-state-error-light flex w-full items-center rounded-lg border p-4 text-left transition-colors"},F("div",{className:"bg-state-error-light mr-4 rounded-full p-2"},F(gf,{icon:"unlock",size:20,className:"text-state-error"})),F("div",null,F("span",{className:"text-fg-primary block font-medium"},c("protect.modifyProtection.removeOption")),F("span",{className:"text-fg-muted text-sm"},c("protect.modifyProtection.removeDescription"))))),F("div",{className:"border-border-subtle flex justify-end border-t pt-4"},F(ff,{onClick:s,className:"border-border-default bg-bg-surface text-fg-secondary hover:bg-interactive-hover rounded-md border px-4 py-2 text-sm"},c("protect.cancel"))));case"remove-protection":return F("div",{className:"space-y-5"},F("div",{className:"bg-state-warning-light flex items-start space-x-3 rounded-lg p-4"},F(gf,{icon:"alertTriangle",className:"text-state-warning mt-0.5 h-5 w-5 flex-shrink-0"}),F("div",null,F("p",{className:"text-fg-primary font-medium"},c("protect.removeProtection.warning")),F("p",{className:"text-fg-secondary mt-1 text-sm"},c("protect.removeProtection.description")))),ue&&F("div",{className:"bg-state-error-light flex items-start space-x-2 rounded-md p-3"},F(gf,{icon:"alertTriangle",className:"text-state-error mt-0.5 h-4 w-4 flex-shrink-0"}),F("p",{className:"text-state-error text-sm"},ue)),F("div",{className:"border-border-subtle flex justify-end space-x-3 border-t pt-4"},F(ff,{onClick:function(){return b("choose-action")},disabled:le,className:"border-border-default bg-bg-surface text-fg-secondary hover:bg-interactive-hover rounded-md border px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},c("common.back")),F(ff,{onClick:we,disabled:le,className:"bg-state-error text-fg-on-accent hover:bg-state-error/90 flex items-center space-x-2 rounded-md border border-transparent px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},le&&F(yy,{size:"sm"}),F("span",null,c("protect.removeProtection.confirm")))));default:return xe()}}())}function Jb(e){var t,n,o,i=e.documentId,r=Ha(i).translate,a=Qr().provides,s=jo(i),l=null==s?void 0:s.document,c=null!==(t=null==l?void 0:l.isEncrypted)&&void 0!==t&&t,d=null!==(n=null==l?void 0:l.isOwnerUnlocked)&&void 0!==n&&n,u=((null!==(o=null==l?void 0:l.permissions)&&void 0!==o?o:Qt.AllowAll)&Qt.AllowAll)!==Qt.AllowAll,h=c&&!d&&u,m=ze(function(){null==a||a.forDocument(i).disableOverlay("unlock-owner-overlay")},[i,a]),g=ze(function(){null==a||a.forDocument(i).disableOverlay("unlock-owner-overlay"),null==a||a.forDocument(i).openModal("view-permissions-modal")},[i,a]);return h?F("div",{className:""},F("div",{className:"bg-bg-surface border-border-default flex max-w-sm items-start gap-3 rounded-lg border p-4 shadow-lg"},F("div",{className:"bg-accent/10 flex-shrink-0 rounded-full p-2"},F(gf,{icon:"lock",size:20,className:"text-accent"})),F("div",{className:"min-w-0 flex-1"},F("h3",{className:"text-fg-primary text-sm font-semibold"},r("security.protected.title")),F("p",{className:"text-fg-secondary mt-1 text-xs leading-relaxed"},r("security.protected.description")),F("button",{type:"button",onClick:g,className:"text-accent hover:text-accent-hover mt-2 text-xs font-medium"},r("security.protected.viewPermissions"))),F("button",{type:"button",onClick:m,className:"text-fg-muted hover:text-fg-secondary -mr-1 -mt-1 flex-shrink-0 p-1","aria-label":r("common.close")},F(gf,{icon:"x",size:16})))):null}function ew(e){var t,n,o=e.documentId,i=e.isOpen,r=e.onClose,a=e.onExited,s=Ha(o).translate,l=jo(o),c=wa().provides,d=v(Se(""),2),u=d[0],h=d[1],m=v(Se(!1),2),g=m[0],p=m[1],f=v(Se(!1),2),y=f[0],b=f[1],w=v(Se(null),2),x=w[0],C=w[1],k=null==l?void 0:l.document,I=null!==(t=null==k?void 0:k.permissions)&&void 0!==t?t:0,S=null!==(n=null==k?void 0:k.isOwnerUnlocked)&&void 0!==n&&n;Me(function(){i&&(h(""),p(!1),b(!1),C(null))},[i]);var A=function(){c&&u&&(b(!0),C(null),c.unlockOwnerPermissions(o,u).wait(function(e){b(!1),e?h(""):C(s("security.unlock.invalidPassword"))},function(e){var t,n;b(!1),C(null!==(t=null===(n=e.reason)||void 0===n?void 0:n.message)&&void 0!==t?t:s("security.unlock.failed"))}))};return F(zb,{open:null!=i&&i,title:s("security.viewPermissions.title"),onClose:r,onExited:a,className:"md:w-[32rem]"},F("div",{className:"space-y-5"},F("p",{className:"text-fg-secondary text-sm"},s("security.viewPermissions.description")),!S&&F("div",null,F("label",{className:"text-fg-primary mb-2 block text-sm font-medium"},s("security.unlock.label")),F("div",{className:"relative"},F("input",{type:g?"text":"password",value:u,onInput:function(e){return h(e.target.value)},placeholder:s("security.unlock.placeholder"),className:"border-border-default bg-bg-input text-fg-primary focus:border-accent focus:ring-accent w-full rounded-md border px-3 py-2 pr-10 text-sm focus:outline-none focus:ring-1",onKeyDown:function(e){"Enter"===e.key&&u&&A()}}),F("button",{type:"button",onClick:function(){return p(!g)},className:"text-fg-muted hover:text-fg-secondary absolute right-2 top-1/2 -translate-y-1/2"},F(gf,{icon:g?"eye-off":"eye",className:"h-4 w-4"}))),x&&F("p",{className:"text-state-error mt-2 text-xs"},x),F(ff,{onClick:A,disabled:!u||y,className:"bg-accent text-fg-on-accent hover:!bg-accent-hover mt-3 flex items-center space-x-2 rounded-md px-4 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-50"},y&&F(yy,{size:"sm"}),F("span",null,s("security.unlock.button")))),S&&F("div",{className:"bg-state-success-light flex items-center space-x-2 rounded-md p-3"},F(gf,{icon:"check",className:"text-state-success h-4 w-4 flex-shrink-0"}),F("p",{className:"text-fg-secondary text-sm"},s("security.unlock.success"))),F(Xb,{permissions:I,translate:s}),F("div",{className:"border-border-subtle flex justify-end border-t pt-4"},F(ff,{onClick:r,className:"border-border-default bg-bg-surface text-fg-secondary hover:bg-interactive-hover rounded-md border px-4 py-2 text-sm"},s("common.close")))))}var tw={documentManager:{},commands:{commands:Lb},i18n:{defaultLocale:"en",locales:[{code:"en",name:"English",translations:{search:{placeholder:"Search",caseSensitive:"Case sensitive",wholeWord:"Whole word",resultsFound:"{count} results found",page:"Page {page}"},zoom:{in:"Zoom In",out:"Zoom Out",fitWidth:"Fit to Width",fitPage:"Fit to Page",marquee:"Marquee Zoom",menu:"Zoom Menu",level:"Zoom Level ({level}%)",dragTip:"Drag to select area to zoom"},pan:{toggle:"Toggle Pan Mode"},pointer:{toggle:"Toggle Pointer Mode"},capture:{screenshot:"Screenshot",dragTip:"Drag to select area to capture",title:"Screenshot Preview",download:"Download",cancel:"Cancel"},document:{menu:"Document Menu",open:"Open",close:"Close",print:"Print",protect:"Security",export:"Export",fullscreen:"Fullscreen",loading:"Loading document..."},emptyState:{title:"No Documents Open",description:"Open a PDF document to get started.",descriptionMulti:"You can view multiple documents using tabs.",openButton:"Open Document",supportedFormats:"Supported format: PDF"},passwordPrompt:{title:"Password Required",required:"This document is password protected. Please enter the password to open it.",incorrect:"The password you entered was incorrect. Please try again.",incorrectWarning:"Incorrect password. Please check and try again.",label:"Password",placeholder:"Enter document password",open:"Open",opening:"Opening...",cancel:"Cancel",close:"Close"},documentError:{title:"Error loading document",unknown:"An unknown error occurred",errorCode:"Error Code: {code}",close:"Close Document"},panel:{sidebar:"Sidebar",search:"Search",comment:"Comment",thumbnails:"Thumbnails",outline:"Outline",annotationStyle:"Annotation Style",redaction:"Redaction Sidebar"},menu:{viewControls:"View Controls",zoomControls:"Zoom Controls",moreOptions:"More Options"},outline:{title:"Outline",loading:"Loading outline...",noOutline:"No outline available",noBookmarks:"This document doesn't contain bookmarks"},page:{settings:"Page Settings",single:"Single Page",twoOdd:"Two Page (Odd)",twoEven:"Two Page (Even)",vertical:"Vertical",horizontal:"Horizontal",spreadMode:"Spread Mode",scrollLayout:"Scroll Layout",rotation:"Page Rotation",next:"Next Page",previous:"Previous Page"},rotate:{clockwise:"Rotate Clockwise",counterClockwise:"Rotate Counter-Clockwise"},selection:{copy:"Copy Selection"},mode:{view:"View",annotate:"Annotate",shapes:"Shapes",redact:"Redact"},annotation:{text:"Text",highlight:"Highlight",strikeout:"Strikethrough",underline:"Underline",squiggly:"Squiggly",rectangle:"Rectangle",circle:"Circle",line:"Line",arrow:"Arrow",polygon:"Polygon",polyline:"Polyline",ink:"Ink",stamp:"Stamp",caret:"Caret",insertText:"Insert Text",replaceText:"Replace Text",freeText:"Free Text",square:"Square",style:"Annotation Style",styles:"{type} Styles",defaults:"{type} Defaults",color:"Color",opacity:"Opacity",blendMode:"Blend mode",strokeWidth:"Stroke width",strokeColor:"Stroke color",borderStyle:"Border style",fillColor:"Fill color",fontSize:"Font size",fontFamily:"Font",textAlign:"Text alignment",verticalAlign:"Vertical alignment",lineEnding:"Line ending",lineStart:"Line start",lineEnd:"Line end",font:"Font",fontColor:"Font color",backgroundColor:"Background color",noStyles:"There are no styles for this annotation.",noStylesStamp:"There are no styles for stamps.",selectAnnotation:"Select an annotation to see styles",deleteSelected:"Delete selected annotation",deleteAllSelected:"Delete Selected",multiSelect:"{count} annotations selected",group:"Group",ungroup:"Ungroup",moreTools:"More Tools",addLink:"Add Link",removeLink:"Remove Link",gotoLink:"Go to Link",comment:"Comment",redact:"Redact",overlayText:"Overlay Text",overlayTextPlaceholder:"e.g., REDACTED",rotation:"Rotation"},redaction:{redact:"Redact",area:"Redact Area",text:"Redact Text",apply:"Apply Redaction",applyAll:"Apply All",clearAll:"Clear All",deleteSelected:"Delete selected redaction",commitSelected:"Apply selected redaction",emptyState:"No pending redactions",panel:{title:"Redactions",itemCount:"{count} pending redaction",itemCountPlural:"{count} pending redactions",clearAll:"Clear All",redactAll:"Redact All"}},history:{undo:"Undo",redo:"Redo"},comments:{page:"Page {page}",commentCount:"{count} comment",commentCountPlural:"{count} comments",addComment:"Add comment...",addReply:"Add reply...",showAllAnnotations:"Show All Annotations",closeAllAnnotations:"Close All Annotations",save:"Save",cancel:"Cancel",edit:"Edit",delete:"Delete",showMore:"more",showLess:"less",emptyState:"Add annotations to be able to comment on them."},blendMode:{normal:"Normal",multiply:"Multiply",screen:"Screen",overlay:"Overlay",darken:"Darken",lighten:"Lighten",colorDodge:"Color Dodge",colorBurn:"Color Burn",hardLight:"Hard Light",softLight:"Soft Light",difference:"Difference",exclusion:"Exclusion",hue:"Hue",saturation:"Saturation",color:"Color",luminosity:"Luminosity"},print:{title:"Print Settings",loading:"Preparing document...",pages:"Pages to print",all:"All pages",current:"Current page ({currentPage})",specify:"Specify pages",specifyEG:"e.g., 1-3, 5, 8-10",total:"Total pages in document: {totalPages}",annotation:"Include annotations",printing:"Printing...",print:"Print",cancel:"Cancel"},protect:{title:"Protect Document",cancel:"Cancel",apply:"Apply Protection",applying:"Applying...",applyFailed:"Failed to apply protection. Please try again.",removeFailed:"Failed to remove protection. Please try again.",passwordMismatch:"Passwords do not match",noProtectionSelected:"Select at least one protection option to apply.",bothPasswordsNote:"Users who open with the document password will have restricted permissions. Use the owner password to unlock full access.",openPassword:{title:"Require password to open",description:"Users must enter a password to view this document.",label:"Document Password",placeholder:"Enter password",confirm:"Confirm Password",confirmPlaceholder:"Confirm password"},ownerPassword:{label:"Owner Password",placeholder:"Enter owner password",confirm:"Confirm Owner Password",confirmPlaceholder:"Confirm owner password"},permissions:{title:"Restrict permissions",description:"Limit what users can do with this document.",allowedActions:"Allowed actions",print:"Print",printHighQuality:"Print high quality",copy:"Copy content",accessibility:"Extract for accessibility",modify:"Modify content",annotations:"Add/modify annotations & comments",fillForms:"Fill forms & sign",assemble:"Assemble & extract pages"},encrypted:{title:"Document is Protected",description:"This document is protected by the owner. Enter the owner password to modify security settings.",enterOwnerPassword:"Enter Owner Password to Modify",unlockAndEdit:"Unlock & Edit"},modifyProtection:{title:"Modify Protection",description:"Choose how you want to modify the document protection.",changeOption:"Change Passwords or Permissions",changeDescription:"Update the document password or permission settings.",removeOption:"Remove All Protection",removeDescription:"Remove password protection from this document."},removeProtection:{title:"Remove Protection",warning:"Are you sure you want to remove protection?",description:"This will remove all password protection from the document. Anyone will be able to open and modify it.",confirm:"Remove Protection"}},security:{protected:{title:"This Document is Protected",description:"This file is protected and some features may be disabled. Go to Security in the document menu to view or unlock permissions.",viewPermissions:"View permissions"},viewPermissions:{title:"Document Permissions",description:"This file is restricted by the owner and requires a password to unlock certain actions.",restrictedActions:"Restricted Actions"},unlock:{label:"Enter Owner Password to Unlock File",placeholder:"Enter owner password",button:"Unlock file",invalidPassword:"Invalid password. Please try again.",failed:"Failed to unlock. Please try again.",success:"Owner permissions unlocked! You now have full access."}},common:{close:"Close",back:"Back",cancel:"Cancel"},link:{title:"Insert Link",url:"URL",page:"Page",enterUrl:"Enter URL",enterPage:"Enter Page Number",pageRange:"Page 1 to {totalPages}",link:"Link"}}},{code:"nl",name:"Nederlands",translations:{search:{placeholder:"Zoeken",caseSensitive:"Hoofdlettergevoelig",wholeWord:"Heel woord",resultsFound:"{count} resultaten gevonden",page:"Pagina {page}"},zoom:{in:"Inzoomen",out:"Uitzoomen",fitWidth:"Aanbreedte aanpassen",fitPage:"Aan pagina aanpassen",marquee:"Lijstzoom",menu:"Zoommenu",level:"Zoomniveau ({level}%)",dragTip:"Drag to select area to zoom"},pan:{toggle:"Pan-modus wisselen"},pointer:{toggle:"Aanwijzermodus wisselen"},capture:{screenshot:"Schermafbeelding",dragTip:"Sleep om een gebied te selecteren om vast te leggen",title:"Screenshot voorbeeld",download:"Downloaden",cancel:"Annuleren"},document:{menu:"Documentmenu",open:"Openen",close:"Sluiten",print:"Afdrukken",protect:"Beveiliging",export:"Exporteren",fullscreen:"Volledig scherm",loading:"Document laden..."},emptyState:{title:"Geen documenten geopend",description:"Open een PDF-document om te beginnen.",descriptionMulti:"U kunt meerdere documenten bekijken met tabs.",openButton:"Document openen",supportedFormats:"Ondersteund formaat: PDF"},passwordPrompt:{title:"Wachtwoord vereist",required:"Dit document is beveiligd met een wachtwoord. Voer het wachtwoord in om te openen.",incorrect:"Het ingevoerde wachtwoord was onjuist. Probeer het opnieuw.",incorrectWarning:"Onjuist wachtwoord. Controleer en probeer opnieuw.",label:"Wachtwoord",placeholder:"Voer documentwachtwoord in",open:"Openen",opening:"Openen...",cancel:"Annuleren",close:"Sluiten"},documentError:{title:"Fout bij laden van document",unknown:"Er is een onbekende fout opgetreden",errorCode:"Foutcode: {code}",close:"Document sluiten"},panel:{sidebar:"Zijbalk",search:"Zoeken",comment:"Opmerking",thumbnails:"Miniaturen",outline:"Overzicht",annotationStyle:"Annotatiestijl",redaction:"Redactie Zijbalk"},menu:{viewControls:"Weergave-instellingen",zoomControls:"Zoom-instellingen",moreOptions:"Meer opties"},outline:{title:"Overzicht",loading:"Overzicht laden...",noOutline:"Geen overzicht beschikbaar",noBookmarks:"Dit document bevat geen bladwijzers"},page:{settings:"Pagina-instellingen",single:"Enkele pagina",twoOdd:"Twee pagina's (Oneven)",twoEven:"Twee pagina's (Even)",vertical:"Verticaal",horizontal:"Horizontaal",spreadMode:"Spreidingsmodus",scrollLayout:"Scrollindeling",rotation:"Paginarotatie",next:"Volgende pagina",previous:"Vorige pagina"},rotate:{clockwise:"Met de klok mee draaien",counterClockwise:"Tegen de klok in draaien"},selection:{copy:"Selectie kopiëren"},mode:{view:"Weergave",annotate:"Annoteren",shapes:"Vormen",redact:"Redigeren"},annotation:{text:"Tekst",highlight:"Markeren",strikeout:"Doorhalen",underline:"Onderstrepen",squiggly:"Golflijn",rectangle:"Rechthoek",circle:"Cirkel",line:"Lijn",arrow:"Pijl",polygon:"Veelhoek",polyline:"Polylijn",ink:"Inkt",stamp:"Stempel",caret:"Invoegpunt",insertText:"Tekst invoegen",replaceText:"Tekst vervangen",freeText:"Vrije tekst",square:"Vierkant",style:"Annotatiestijl",styles:"{type} stijlen",defaults:"{type} standaardwaarden",color:"Kleur",opacity:"Dekking",blendMode:"Overvloeimodus",strokeWidth:"Lijndikte",strokeColor:"Lijnkleur",borderStyle:"Randstijl",fillColor:"Vulkleur",fontSize:"Lettergrootte",fontFamily:"Lettertype",textAlign:"Tekstuitlijning",verticalAlign:"Verticale uitlijning",lineEnding:"Lijneinde",lineStart:"Lijnbegin",lineEnd:"Lijneinde",font:"Lettertype",fontColor:"Tekstkleur",backgroundColor:"Achtergrondkleur",noStyles:"Er zijn geen stijlen voor deze annotatie.",noStylesStamp:"Er zijn geen stijlen voor stempels.",selectAnnotation:"Selecteer een annotatie om stijlen te zien",deleteSelected:"Geselecteerde annotatie verwijderen",deleteAllSelected:"Selectie verwijderen",multiSelect:"{count} annotaties geselecteerd",group:"Groeperen",ungroup:"Groepering opheffen",moreTools:"Meer gereedschappen",addLink:"Link toevoegen",removeLink:"Link verwijderen",gotoLink:"Ga naar link",comment:"Opmerking",redact:"Redigeren",overlayText:"Overlaytekst",overlayTextPlaceholder:"bijv. GEREDIGEERD",rotation:"Rotatie"},redaction:{redact:"Redigeren",area:"Gebied redigeren",text:"Tekst redigeren",apply:"Redactie toepassen",applyAll:"Alles toepassen",clearAll:"Alles wissen",deleteSelected:"Geselecteerde redactie verwijderen",commitSelected:"Geselecteerde redactie toepassen",emptyState:"Geen openstaande redacties",panel:{title:"Redacties",itemCount:"{count} openstaande redactie",itemCountPlural:"{count} openstaande redacties",clearAll:"Alles wissen",redactAll:"Alles redigeren"}},history:{undo:"Ongedaan maken",redo:"Opnieuw doen"},comments:{page:"Pagina {page}",commentCount:"{count} opmerking",commentCountPlural:"{count} opmerkingen",addComment:"Opmerking toevoegen...",addReply:"Antwoord toevoegen...",showAllAnnotations:"Alle annotaties tonen",closeAllAnnotations:"Alle annotaties sluiten",save:"Opslaan",cancel:"Annuleren",edit:"Bewerken",delete:"Verwijderen",showMore:"meer",showLess:"minder",emptyState:"Voeg annotaties toe om erop te kunnen reageren."},blendMode:{normal:"Normaal",multiply:"Vermenigvuldigen",screen:"Bleken",overlay:"Bedekken",darken:"Donkerder",lighten:"Lichter",colorDodge:"Kleur tegenhouden",colorBurn:"Kleur doordrukken",hardLight:"Hard licht",softLight:"Zacht licht",difference:"Verschil",exclusion:"Uitsluiting",hue:"Kleurtoon",saturation:"Verzadiging",color:"Kleur",luminosity:"Helderheid"},print:{title:"Afdrukinstellingen",loading:"Document voorbereiden...",pages:"Af te drukken pagina's",all:"Alle pagina's",current:"Huidige pagina ({currentPage})",specify:"Pagina's",specifyEG:"bijv. 1-3, 5, 8-10",total:"Totaal aantal pagina's in document: {totalPages}",annotation:"Inclusief annotaties",printing:"Afdrukken...",print:"Afdrukken",cancel:"Annuleren"},protect:{title:"Document beveiligen",cancel:"Annuleren",apply:"Beveiliging toepassen",applying:"Bezig met toepassen...",applyFailed:"Beveiliging kon niet worden toegepast. Probeer het opnieuw.",removeFailed:"Beveiliging kon niet worden verwijderd. Probeer het opnieuw.",passwordMismatch:"Wachtwoorden komen niet overeen",noProtectionSelected:"Selecteer minimaal één beveiligingsoptie.",bothPasswordsNote:"Gebruikers die openen met het documentwachtwoord hebben beperkte rechten. Gebruik het eigenaarswachtwoord voor volledige toegang.",openPassword:{title:"Wachtwoord vereist om te openen",description:"Gebruikers moeten een wachtwoord invoeren om dit document te bekijken.",label:"Documentwachtwoord",placeholder:"Wachtwoord invoeren",confirm:"Wachtwoord bevestigen",confirmPlaceholder:"Wachtwoord bevestigen"},ownerPassword:{label:"Eigenaarswachtwoord",placeholder:"Eigenaarswachtwoord invoeren",confirm:"Eigenaarswachtwoord bevestigen",confirmPlaceholder:"Eigenaarswachtwoord bevestigen"},permissions:{title:"Rechten beperken",description:"Beperk wat gebruikers met dit document kunnen doen.",allowedActions:"Toegestane acties",print:"Afdrukken",printHighQuality:"Hoge kwaliteit afdrukken",copy:"Inhoud kopiëren",accessibility:"Extraheren voor toegankelijkheid",modify:"Inhoud wijzigen",annotations:"Annotaties & opmerkingen toevoegen/wijzigen",fillForms:"Formulieren invullen & ondertekenen",assemble:"Document samenstellen & pagina's extraheren"},encrypted:{title:"Document is beveiligd",description:"Dit document is beveiligd door de eigenaar. Voer het eigenaarswachtwoord in om beveiligingsinstellingen te wijzigen.",enterOwnerPassword:"Voer eigenaarswachtwoord in om te wijzigen",unlockAndEdit:"Ontgrendelen & Bewerken"},modifyProtection:{title:"Beveiliging wijzigen",description:"Kies hoe u de documentbeveiliging wilt wijzigen.",changeOption:"Wachtwoorden of rechten wijzigen",changeDescription:"Update het documentwachtwoord of rechtinstellingen.",removeOption:"Alle beveiliging verwijderen",removeDescription:"Verwijder wachtwoordbeveiliging van dit document."},removeProtection:{title:"Beveiliging verwijderen",warning:"Weet u zeker dat u de beveiliging wilt verwijderen?",description:"Dit verwijdert alle wachtwoordbeveiliging van het document. Iedereen kan het openen en wijzigen.",confirm:"Beveiliging verwijderen"}},security:{protected:{title:"Dit document is beveiligd",description:"Dit bestand is beveiligd en sommige functies zijn mogelijk uitgeschakeld. Ga naar Beveiliging in het documentmenu om rechten te bekijken of te ontgrendelen.",viewPermissions:"Rechten bekijken"},viewPermissions:{title:"Documentrechten",description:"Dit bestand is beperkt door de eigenaar en vereist een wachtwoord om bepaalde acties te ontgrendelen.",restrictedActions:"Beperkte acties"},unlock:{label:"Voer eigenaarswachtwoord in om te ontgrendelen",placeholder:"Eigenaarswachtwoord invoeren",button:"Bestand ontgrendelen",invalidPassword:"Ongeldig wachtwoord. Probeer het opnieuw.",failed:"Ontgrendelen mislukt. Probeer het opnieuw.",success:"Eigenaarrechten ontgrendeld! U heeft nu volledige toegang."}},common:{close:"Sluiten",back:"Terug",cancel:"Annuleren"},link:{title:"Link invoegen",url:"URL",page:"Pagina",enterUrl:"URL invoeren",enterPage:"Paginanummer invoeren",pageRange:"Pagina 1 tot {totalPages}",link:"Koppelen"}}},{code:"de",name:"Deutsch",translations:{search:{placeholder:"Suchen",caseSensitive:"Groß-/Kleinschreibung",wholeWord:"Ganzes Wort",resultsFound:"{count} Ergebnisse gefunden",page:"Seite {page}"},zoom:{in:"Vergrößern",out:"Verkleinern",fitWidth:"An Breite anpassen",fitPage:"An Seite anpassen",marquee:"Laufrahmen-Zoom",menu:"Zoom-Menü",level:"Zoomstufe ({level}%)",dragTip:"Drag to select area to zoom"},pan:{toggle:"Verschieben-Modus umschalten"},pointer:{toggle:"Zeiger-Modus umschalten"},capture:{screenshot:"Screenshot",dragTip:"Ziehen Sie, um den Bereich zum Erfassen auszuwählen",title:"Screenshot-Vorschau",download:"Herunterladen",cancel:"Abbrechen"},document:{menu:"Dokument-Menü",open:"Öffnen",close:"Schließen",print:"Drucken",protect:"Sicherheit",export:"Exportieren",fullscreen:"Vollbild",loading:"Dokument wird geladen..."},emptyState:{title:"Keine Dokumente geöffnet",description:"Öffnen Sie ein PDF-Dokument, um zu beginnen.",descriptionMulti:"Sie können mehrere Dokumente mit Tabs anzeigen.",openButton:"Dokument öffnen",supportedFormats:"Unterstütztes Format: PDF"},passwordPrompt:{title:"Passwort erforderlich",required:"Dieses Dokument ist passwortgeschützt. Bitte geben Sie das Passwort ein.",incorrect:"Das eingegebene Passwort war falsch. Bitte versuchen Sie es erneut.",incorrectWarning:"Falsches Passwort. Bitte überprüfen und erneut versuchen.",label:"Passwort",placeholder:"Dokumentpasswort eingeben",open:"Öffnen",opening:"Öffnen...",cancel:"Abbrechen",close:"Schließen"},documentError:{title:"Fehler beim Laden des Dokuments",unknown:"Ein unbekannter Fehler ist aufgetreten",errorCode:"Fehlercode: {code}",close:"Dokument schließen"},panel:{sidebar:"Seitenleiste",search:"Suchen",comment:"Kommentar",thumbnails:"Miniaturansichten",outline:"Gliederung",annotationStyle:"Anmerkungsstil",redaction:"Schwärzungs-Seitenleiste"},menu:{viewControls:"Ansichtseinstellungen",zoomControls:"Zoom-Einstellungen",moreOptions:"Weitere Optionen"},outline:{title:"Gliederung",loading:"Gliederung wird geladen...",noOutline:"Keine Gliederung verfügbar",noBookmarks:"Dieses Dokument enthält keine Lesezeichen"},page:{settings:"Seiteneinstellungen",single:"Einzelseite",twoOdd:"Zwei Seiten (Ungerade)",twoEven:"Zwei Seiten (Gerade)",vertical:"Vertikal",horizontal:"Horizontal",spreadMode:"Doppelseiten-Modus",scrollLayout:"Scroll-Layout",rotation:"Seitendrehung",next:"Nächste Seite",previous:"Vorherige Seite"},rotate:{clockwise:"Im Uhrzeigersinn drehen",counterClockwise:"Gegen den Uhrzeigersinn drehen"},selection:{copy:"Auswahl kopieren"},mode:{view:"Ansicht",annotate:"Annotieren",shapes:"Formen",redact:"Schwärzen"},annotation:{text:"Text",highlight:"Markieren",strikeout:"Durchstreichen",underline:"Unterstreichen",squiggly:"Wellenlinie",rectangle:"Rechteck",circle:"Kreis",line:"Linie",arrow:"Pfeil",polygon:"Polygon",polyline:"Polylinie",ink:"Freihand",stamp:"Stempel",caret:"Einfügemarke",insertText:"Text einfügen",replaceText:"Text ersetzen",freeText:"Freitext",square:"Quadrat",style:"Anmerkungsstil",styles:"{type}-Stile",defaults:"{type}-Standardwerte",color:"Farbe",opacity:"Deckkraft",blendMode:"Mischmodus",strokeWidth:"Strichstärke",strokeColor:"Strichfarbe",borderStyle:"Rahmenstil",fillColor:"Füllfarbe",fontSize:"Schriftgröße",fontFamily:"Schriftart",textAlign:"Textausrichtung",verticalAlign:"Vertikale Ausrichtung",lineEnding:"Linienende",lineStart:"Linienanfang",lineEnd:"Linienende",font:"Schriftart",fontColor:"Schriftfarbe",backgroundColor:"Hintergrundfarbe",noStyles:"Für diese Anmerkung gibt es keine Stile.",noStylesStamp:"Für Stempel gibt es keine Stile.",selectAnnotation:"Wählen Sie eine Anmerkung aus, um Stile anzuzeigen",deleteSelected:"Ausgewählte Anmerkung löschen",deleteAllSelected:"Ausgewählte löschen",multiSelect:"{count} Anmerkungen ausgewählt",group:"Gruppieren",ungroup:"Gruppierung aufheben",moreTools:"Weitere Werkzeuge",addLink:"Link hinzufügen",removeLink:"Link entfernen",gotoLink:"Zum Link gehen",comment:"Kommentar",redact:"Schwärzen",overlayText:"Überlagerungstext",overlayTextPlaceholder:"z.B. GESCHWÄRZT",rotation:"Drehung"},redaction:{redact:"Schwärzen",area:"Bereich schwärzen",text:"Text schwärzen",apply:"Schwärzung anwenden",applyAll:"Alle anwenden",clearAll:"Alle löschen",deleteSelected:"Ausgewählte Schwärzung löschen",commitSelected:"Ausgewählte Schwärzung anwenden",emptyState:"Keine ausstehenden Schwärzungen",panel:{title:"Schwärzungen",itemCount:"{count} ausstehende Schwärzung",itemCountPlural:"{count} ausstehende Schwärzungen",clearAll:"Alle löschen",redactAll:"Alle schwärzen"}},history:{undo:"Rückgängig",redo:"Wiederholen"},comments:{page:"Seite {page}",commentCount:"{count} Kommentar",commentCountPlural:"{count} Kommentare",addComment:"Kommentar hinzufügen...",addReply:"Antwort hinzufügen...",showAllAnnotations:"Alle Anmerkungen anzeigen",closeAllAnnotations:"Alle Anmerkungen schließen",save:"Speichern",cancel:"Abbrechen",edit:"Bearbeiten",delete:"Löschen",showMore:"mehr",showLess:"weniger",emptyState:"Fügen Sie Anmerkungen hinzu, um sie kommentieren zu können."},blendMode:{normal:"Normal",multiply:"Multiplizieren",screen:"Negativ multiplizieren",overlay:"Ineinanderkopieren",darken:"Abdunkeln",lighten:"Aufhellen",colorDodge:"Farbig abwedeln",colorBurn:"Farbig nachbelichten",hardLight:"Hartes Licht",softLight:"Weiches Licht",difference:"Differenz",exclusion:"Ausschluss",hue:"Farbton",saturation:"Sättigung",color:"Farbe",luminosity:"Luminanz"},print:{title:"Druckeinstellungen",loading:"Dokument wird vorbereitet...",pages:"Zu druckende Seiten",all:"Alle Seiten",current:"Aktuelle Seite ({currentPage})",specify:"Seiten angeben",specifyEG:"z.B. 1-3, 5, 8-10",total:"Gesamtseitenzahl im Dokument: {totalPages}",annotation:"Anmerkungen einbeziehen",printing:"Drucken...",print:"Drucken",cancel:"Abbrechen"},protect:{title:"Dokument schützen",cancel:"Abbrechen",apply:"Schutz anwenden",applying:"Wird angewendet...",applyFailed:"Schutz konnte nicht angewendet werden. Bitte versuchen Sie es erneut.",removeFailed:"Schutz konnte nicht entfernt werden. Bitte versuchen Sie es erneut.",passwordMismatch:"Passwörter stimmen nicht überein",noProtectionSelected:"Wählen Sie mindestens eine Schutzoption aus.",bothPasswordsNote:"Benutzer, die das Dokumentpasswort eingeben, haben eingeschränkte Berechtigungen. Verwenden Sie das Eigentümerpasswort für vollen Zugriff.",openPassword:{title:"Passwort zum Öffnen erforderlich",description:"Benutzer müssen ein Passwort eingeben, um dieses Dokument anzuzeigen.",label:"Dokumentpasswort",placeholder:"Passwort eingeben",confirm:"Passwort bestätigen",confirmPlaceholder:"Passwort bestätigen"},ownerPassword:{label:"Eigentümerpasswort",placeholder:"Eigentümerpasswort eingeben",confirm:"Eigentümerpasswort bestätigen",confirmPlaceholder:"Eigentümerpasswort bestätigen"},permissions:{title:"Berechtigungen einschränken",description:"Beschränken Sie, was Benutzer mit diesem Dokument tun können.",allowedActions:"Erlaubte Aktionen",print:"Drucken",printHighQuality:"In hoher Qualität drucken",copy:"Inhalt kopieren",accessibility:"Für Barrierefreiheit extrahieren",modify:"Inhalt ändern",annotations:"Anmerkungen & Kommentare hinzufügen/ändern",fillForms:"Formulare ausfüllen & unterschreiben",assemble:"Dokument zusammenstellen & Seiten extrahieren"},encrypted:{title:"Dokument ist geschützt",description:"Dieses Dokument ist vom Eigentümer geschützt. Geben Sie das Eigentümerpasswort ein, um die Sicherheitseinstellungen zu ändern.",enterOwnerPassword:"Eigentümerpasswort eingeben zum Ändern",unlockAndEdit:"Entsperren & Bearbeiten"},modifyProtection:{title:"Schutz ändern",description:"Wählen Sie, wie Sie den Dokumentschutz ändern möchten.",changeOption:"Passwörter oder Berechtigungen ändern",changeDescription:"Aktualisieren Sie das Dokumentpasswort oder die Berechtigungseinstellungen.",removeOption:"Gesamten Schutz entfernen",removeDescription:"Passwortschutz von diesem Dokument entfernen."},removeProtection:{title:"Schutz entfernen",warning:"Sind Sie sicher, dass Sie den Schutz entfernen möchten?",description:"Dadurch wird der gesamte Passwortschutz vom Dokument entfernt. Jeder kann es öffnen und bearbeiten.",confirm:"Schutz entfernen"}},security:{protected:{title:"Dieses Dokument ist geschützt",description:"Diese Datei ist geschützt und einige Funktionen sind möglicherweise deaktiviert. Gehen Sie zu Sicherheit im Dokumentmenü, um Berechtigungen anzuzeigen oder freizuschalten.",viewPermissions:"Berechtigungen anzeigen"},viewPermissions:{title:"Dokumentberechtigungen",description:"Diese Datei ist vom Eigentümer eingeschränkt und erfordert ein Passwort, um bestimmte Aktionen freizuschalten.",restrictedActions:"Eingeschränkte Aktionen"},unlock:{label:"Eigentümerpasswort eingeben zum Entsperren",placeholder:"Eigentümerpasswort eingeben",button:"Datei entsperren",invalidPassword:"Ungültiges Passwort. Bitte versuchen Sie es erneut.",failed:"Entsperren fehlgeschlagen. Bitte versuchen Sie es erneut.",success:"Eigentümerberechtigungen entsperrt! Sie haben jetzt vollen Zugriff."}},common:{close:"Schließen",back:"Zurück",cancel:"Abbrechen"},link:{title:"Link einfügen",url:"URL",page:"Seite",enterUrl:"URL eingeben",enterPage:"Seitennummer eingeben",pageRange:"Seite 1 bis {totalPages}",link:"Verknüpfen"}}},{code:"fr",name:"Français",translations:{search:{placeholder:"Rechercher",caseSensitive:"Respecter la casse",wholeWord:"Mot entier",resultsFound:"{count} résultats trouvés",page:"Page {page}"},zoom:{in:"Zoom avant",out:"Zoom arrière",fitWidth:"Ajuster à la largeur",fitPage:"Ajuster à la page",marquee:"Zoom de sélection",menu:"Menu Zoom",level:"Niveau de zoom ({level}%)",dragTip:"Drag to select area to zoom"},pan:{toggle:"Basculer le mode déplacement"},pointer:{toggle:"Basculer le mode pointeur"},capture:{screenshot:"Capture d'écran",dragTip:"Faites glisser pour sélectionner la zone à capturer",title:"Aperçu de la capture",download:"Télécharger",cancel:"Annuler"},document:{menu:"Menu Document",open:"Ouvrir",close:"Fermer",print:"Imprimer",protect:"Sécurité",export:"Exporter",fullscreen:"Plein écran",loading:"Chargement du document..."},emptyState:{title:"Aucun document ouvert",description:"Ouvrez un document PDF pour commencer.",descriptionMulti:"Vous pouvez afficher plusieurs documents avec des onglets.",openButton:"Ouvrir un document",supportedFormats:"Format pris en charge : PDF"},passwordPrompt:{title:"Mot de passe requis",required:"Ce document est protégé par mot de passe. Veuillez entrer le mot de passe.",incorrect:"Le mot de passe saisi est incorrect. Veuillez réessayer.",incorrectWarning:"Mot de passe incorrect. Veuillez vérifier et réessayer.",label:"Mot de passe",placeholder:"Entrer le mot de passe du document",open:"Ouvrir",opening:"Ouverture...",cancel:"Annuler",close:"Fermer"},documentError:{title:"Erreur lors du chargement du document",unknown:"Une erreur inconnue est survenue",errorCode:"Code erreur : {code}",close:"Fermer le document"},panel:{sidebar:"Barre latérale",search:"Rechercher",comment:"Commentaire",thumbnails:"Miniatures",outline:"Plan",annotationStyle:"Style d'annotation",redaction:"Barre latérale de caviardage"},menu:{viewControls:"Contrôles d'affichage",zoomControls:"Contrôles de zoom",moreOptions:"Plus d'options"},outline:{title:"Plan",loading:"Chargement du plan...",noOutline:"Aucun plan disponible",noBookmarks:"Ce document ne contient pas de signets"},page:{settings:"Paramètres de page",single:"Page unique",twoOdd:"Deux pages (Impair)",twoEven:"Deux pages (Pair)",vertical:"Vertical",horizontal:"Horizontal",spreadMode:"Mode double page",scrollLayout:"Disposition de défilement",rotation:"Rotation de page",next:"Page suivante",previous:"Page précédente"},rotate:{clockwise:"Tourner dans le sens horaire",counterClockwise:"Tourner dans le sens antihoraire"},selection:{copy:"Copier la sélection"},mode:{view:"Affichage",annotate:"Annoter",shapes:"Formes",redact:"Caviarder"},annotation:{text:"Texte",highlight:"Surligner",strikeout:"Barrer",underline:"Souligner",squiggly:"Ondulé",rectangle:"Rectangle",circle:"Cercle",line:"Ligne",arrow:"Flèche",polygon:"Polygone",polyline:"Polyligne",ink:"Encre",stamp:"Tampon",caret:"Curseur",insertText:"Insérer du texte",replaceText:"Remplacer le texte",freeText:"Texte libre",square:"Carré",style:"Style d'annotation",styles:"Styles de {type}",defaults:"Valeurs par défaut de {type}",color:"Couleur",opacity:"Opacité",blendMode:"Mode de fusion",strokeWidth:"Épaisseur du trait",strokeColor:"Couleur du trait",borderStyle:"Style de bordure",fillColor:"Couleur de remplissage",fontSize:"Taille de police",fontFamily:"Police",textAlign:"Alignement du texte",verticalAlign:"Alignement vertical",lineEnding:"Fin de ligne",lineStart:"Début de ligne",lineEnd:"Fin de ligne",font:"Police",fontColor:"Couleur du texte",backgroundColor:"Couleur de fond",noStyles:"Il n'y a pas de styles pour cette annotation.",noStylesStamp:"Il n'y a pas de styles pour les tampons.",selectAnnotation:"Sélectionnez une annotation pour voir les styles",deleteSelected:"Supprimer l'annotation sélectionnée",deleteAllSelected:"Supprimer la sélection",multiSelect:"{count} annotations sélectionnées",group:"Grouper",ungroup:"Dissocier",moreTools:"Plus d'outils",addLink:"Ajouter un lien",removeLink:"Supprimer le lien",gotoLink:"Aller au lien",comment:"Commentaire",redact:"Caviarder",overlayText:"Texte de superposition",overlayTextPlaceholder:"ex: CAVIARDÉ",rotation:"Rotation"},redaction:{redact:"Caviarder",area:"Caviarder la zone",text:"Caviarder le texte",apply:"Appliquer le caviardage",applyAll:"Tout appliquer",clearAll:"Tout effacer",deleteSelected:"Supprimer la rédaction sélectionnée",commitSelected:"Appliquer la rédaction sélectionnée",emptyState:"Aucun caviardage en attente",panel:{title:"Caviardages",itemCount:"{count} caviardage en attente",itemCountPlural:"{count} caviardages en attente",clearAll:"Tout effacer",redactAll:"Tout caviarder"}},history:{undo:"Annuler",redo:"Refaire"},comments:{page:"Page {page}",commentCount:"{count} commentaire",commentCountPlural:"{count} commentaires",addComment:"Ajouter un commentaire...",addReply:"Ajouter une réponse...",showAllAnnotations:"Afficher toutes les annotations",closeAllAnnotations:"Fermer toutes les annotations",save:"Enregistrer",cancel:"Annuler",edit:"Modifier",delete:"Supprimer",showMore:"plus",showLess:"moins",emptyState:"Ajoutez des annotations pour pouvoir les commenter."},blendMode:{normal:"Normal",multiply:"Produit",screen:"Superposition",overlay:"Incrustation",darken:"Obscurcir",lighten:"Éclaircir",colorDodge:"Densité couleur -",colorBurn:"Densité couleur +",hardLight:"Lumière crue",softLight:"Lumière tamisée",difference:"Différence",exclusion:"Exclusion",hue:"Teinte",saturation:"Saturation",color:"Couleur",luminosity:"Luminosité"},print:{title:"Paramètres d'impression",loading:"Préparation du document...",pages:"Pages à imprimer",all:"Toutes les pages",current:"Page actuelle ({currentPage})",specify:"Spécifier les pages",specifyEG:"ex : 1-3, 5, 8-10",total:"Nombre total de pages dans le document : {totalPages}",annotation:"Inclure les annotations",printing:"Impression...",print:"Imprimer",cancel:"Annuler"},protect:{title:"Protéger le document",cancel:"Annuler",apply:"Appliquer la protection",applying:"Application en cours...",applyFailed:"Échec de l'application de la protection. Veuillez réessayer.",removeFailed:"Échec de la suppression de la protection. Veuillez réessayer.",passwordMismatch:"Les mots de passe ne correspondent pas",noProtectionSelected:"Sélectionnez au moins une option de protection.",bothPasswordsNote:"Les utilisateurs qui ouvrent avec le mot de passe du document auront des permissions limitées. Utilisez le mot de passe propriétaire pour un accès complet.",openPassword:{title:"Mot de passe requis pour l'ouverture",description:"Les utilisateurs doivent entrer un mot de passe pour voir ce document.",label:"Mot de passe du document",placeholder:"Entrer le mot de passe",confirm:"Confirmer le mot de passe",confirmPlaceholder:"Confirmer le mot de passe"},ownerPassword:{label:"Mot de passe propriétaire",placeholder:"Entrer le mot de passe propriétaire",confirm:"Confirmer le mot de passe propriétaire",confirmPlaceholder:"Confirmer le mot de passe propriétaire"},permissions:{title:"Restreindre les permissions",description:"Limitez ce que les utilisateurs peuvent faire avec ce document.",allowedActions:"Actions autorisées",print:"Imprimer",printHighQuality:"Imprimer en haute qualité",copy:"Copier le contenu",accessibility:"Extraire pour l'accessibilité",modify:"Modifier le contenu",annotations:"Ajouter/modifier les annotations et commentaires",fillForms:"Remplir les formulaires et signer",assemble:"Assembler le document et extraire les pages"},encrypted:{title:"Document protégé",description:"Ce document est protégé par le propriétaire. Entrez le mot de passe propriétaire pour modifier les paramètres de sécurité.",enterOwnerPassword:"Entrer le mot de passe propriétaire pour modifier",unlockAndEdit:"Déverrouiller & Modifier"},modifyProtection:{title:"Modifier la protection",description:"Choisissez comment vous voulez modifier la protection du document.",changeOption:"Modifier les mots de passe ou les permissions",changeDescription:"Mettre à jour le mot de passe du document ou les paramètres de permissions.",removeOption:"Supprimer toute la protection",removeDescription:"Supprimer la protection par mot de passe de ce document."},removeProtection:{title:"Supprimer la protection",warning:"Êtes-vous sûr de vouloir supprimer la protection ?",description:"Cela supprimera toute la protection par mot de passe du document. Tout le monde pourra l'ouvrir et le modifier.",confirm:"Supprimer la protection"}},security:{protected:{title:"Ce document est protégé",description:"Ce fichier est protégé et certaines fonctionnalités peuvent être désactivées. Allez dans Sécurité dans le menu document pour afficher ou déverrouiller les permissions.",viewPermissions:"Voir les permissions"},viewPermissions:{title:"Permissions du document",description:"Ce fichier est restreint par le propriétaire et nécessite un mot de passe pour débloquer certaines actions.",restrictedActions:"Actions restreintes"},unlock:{label:"Entrer le mot de passe propriétaire pour déverrouiller",placeholder:"Entrer le mot de passe propriétaire",button:"Déverrouiller le fichier",invalidPassword:"Mot de passe invalide. Veuillez réessayer.",failed:"Échec du déverrouillage. Veuillez réessayer.",success:"Permissions propriétaire déverrouillées ! Vous avez maintenant un accès complet."}},common:{close:"Fermer",back:"Retour",cancel:"Annuler"},link:{title:"Insérer un lien",url:"URL",page:"Page",enterUrl:"Entrer l'URL",enterPage:"Entrer le numéro de page",pageRange:"Page 1 à {totalPages}",link:"Lier"}}},{code:"es",name:"Español",translations:{search:{placeholder:"Buscar",caseSensitive:"Distinguir mayúsculas",wholeWord:"Palabra completa",resultsFound:"{count} resultados encontrados",page:"Página {page}"},zoom:{in:"Acercar",out:"Alejar",fitWidth:"Ajustar al ancho",fitPage:"Ajustar a la página",marquee:"Zoom de selección",menu:"Menú de zoom",level:"Nivel de zoom ({level}%)",dragTip:"Drag to select area to zoom"},pan:{toggle:"Alternar modo desplazamiento"},pointer:{toggle:"Alternar modo puntero"},capture:{screenshot:"Captura de pantalla",dragTip:"Arrastre para seleccionar el área a capturar",title:"Vista previa de la captura",download:"Descargar",cancel:"Cancelar"},document:{menu:"Menú del documento",open:"Abrir",close:"Cerrar",print:"Imprimir",protect:"Seguridad",export:"Exportar",fullscreen:"Pantalla completa",loading:"Cargando documento..."},emptyState:{title:"No hay documentos abiertos",description:"Abra un documento PDF para comenzar.",descriptionMulti:"Puede ver varios documentos usando pestañas.",openButton:"Abrir documento",supportedFormats:"Formato compatible: PDF"},passwordPrompt:{title:"Contraseña requerida",required:"Este documento está protegido con contraseña. Por favor, ingrese la contraseña para abrirlo.",incorrect:"La contraseña ingresada es incorrecta. Por favor, inténtelo de nuevo.",incorrectWarning:"Contraseña incorrecta. Por favor, verifique e inténtelo de nuevo.",label:"Contraseña",placeholder:"Ingrese la contraseña del documento",open:"Abrir",opening:"Abriendo...",cancel:"Cancelar",close:"Cerrar"},documentError:{title:"Error al cargar el documento",unknown:"Ha ocurrido un error desconocido",errorCode:"Código de error: {code}",close:"Cerrar documento"},panel:{sidebar:"Barra lateral",search:"Buscar",comment:"Comentario",thumbnails:"Miniaturas",outline:"Esquema",annotationStyle:"Estilo de anotación",redaction:"Barra lateral de redacción"},menu:{viewControls:"Controles de vista",zoomControls:"Controles de zoom",moreOptions:"Más opciones"},outline:{title:"Esquema",loading:"Cargando esquema...",noOutline:"No hay esquema disponible",noBookmarks:"Este documento no contiene marcadores"},page:{settings:"Configuración de página",single:"Página única",twoOdd:"Dos páginas (Impar)",twoEven:"Dos páginas (Par)",vertical:"Vertical",horizontal:"Horizontal",spreadMode:"Modo de doble página",scrollLayout:"Diseño de desplazamiento",rotation:"Rotación de página",next:"Página siguiente",previous:"Página anterior"},rotate:{clockwise:"Rotar en sentido horario",counterClockwise:"Rotar en sentido antihorario"},selection:{copy:"Copiar selección"},mode:{view:"Ver",annotate:"Anotar",shapes:"Formas",redact:"Redactar"},annotation:{text:"Texto",highlight:"Resaltar",strikeout:"Tachar",underline:"Subrayar",squiggly:"Ondulado",rectangle:"Rectángulo",circle:"Círculo",line:"Línea",arrow:"Flecha",polygon:"Polígono",polyline:"Polilínea",ink:"Tinta",stamp:"Sello",caret:"Cursor",insertText:"Insertar texto",replaceText:"Reemplazar texto",freeText:"Texto libre",square:"Cuadrado",style:"Estilo de anotación",styles:"Estilos de {type}",defaults:"Valores predeterminados de {type}",color:"Color",opacity:"Opacidad",blendMode:"Modo de fusión",strokeWidth:"Grosor del trazo",strokeColor:"Color del trazo",borderStyle:"Estilo del borde",fillColor:"Color de relleno",fontSize:"Tamaño de fuente",fontFamily:"Fuente",textAlign:"Alineación del texto",verticalAlign:"Alineación vertical",lineEnding:"Final de línea",lineStart:"Inicio de línea",lineEnd:"Final de línea",font:"Fuente",fontColor:"Color de fuente",backgroundColor:"Color de fondo",noStyles:"No hay estilos para esta anotación.",noStylesStamp:"No hay estilos para los sellos.",selectAnnotation:"Seleccione una anotación para ver los estilos",deleteSelected:"Eliminar anotación seleccionada",deleteAllSelected:"Eliminar selección",multiSelect:"{count} anotaciones seleccionadas",group:"Agrupar",ungroup:"Desagrupar",moreTools:"Más herramientas",addLink:"Agregar enlace",removeLink:"Eliminar enlace",gotoLink:"Ir al enlace",comment:"Comentario",redact:"Redactar",overlayText:"Texto superpuesto",overlayTextPlaceholder:"ej: REDACTADO",rotation:"Rotación"},redaction:{redact:"Redactar",area:"Redactar área",text:"Redactar texto",apply:"Aplicar redacción",applyAll:"Aplicar todo",clearAll:"Borrar todo",deleteSelected:"Eliminar redacción seleccionada",commitSelected:"Aplicar redacción seleccionada",emptyState:"No hay redacciones pendientes",panel:{title:"Redacciones",itemCount:"{count} redacción pendiente",itemCountPlural:"{count} redacciones pendientes",clearAll:"Borrar todo",redactAll:"Redactar todo"}},history:{undo:"Deshacer",redo:"Rehacer"},comments:{page:"Página {page}",commentCount:"{count} comentario",commentCountPlural:"{count} comentarios",addComment:"Añadir comentario...",addReply:"Añadir respuesta...",showAllAnnotations:"Mostrar todas las anotaciones",closeAllAnnotations:"Cerrar todas las anotaciones",save:"Guardar",cancel:"Cancelar",edit:"Editar",delete:"Eliminar",showMore:"más",showLess:"menos",emptyState:"Añada anotaciones para poder comentarlas."},blendMode:{normal:"Normal",multiply:"Multiplicar",screen:"Trama",overlay:"Superponer",darken:"Oscurecer",lighten:"Aclarar",colorDodge:"Sobreexponer color",colorBurn:"Subexponer color",hardLight:"Luz fuerte",softLight:"Luz suave",difference:"Diferencia",exclusion:"Exclusión",hue:"Tono",saturation:"Saturación",color:"Color",luminosity:"Luminosidad"},print:{title:"Configuración de impresión",loading:"Preparando documento...",pages:"Páginas a imprimir",all:"Todas las páginas",current:"Página actual ({currentPage})",specify:"Especificar páginas",specifyEG:"ej: 1-3, 5, 8-10",total:"Total de páginas en el documento: {totalPages}",annotation:"Incluir anotaciones",printing:"Imprimiendo...",print:"Imprimir",cancel:"Cancelar"},protect:{title:"Proteger documento",cancel:"Cancelar",apply:"Aplicar protección",applying:"Aplicando...",applyFailed:"No se pudo aplicar la protección. Por favor, inténtelo de nuevo.",removeFailed:"No se pudo eliminar la protección. Por favor, inténtelo de nuevo.",passwordMismatch:"Las contraseñas no coinciden",noProtectionSelected:"Seleccione al menos una opción de protección.",bothPasswordsNote:"Los usuarios que abran con la contraseña del documento tendrán permisos restringidos. Use la contraseña de propietario para acceso completo.",openPassword:{title:"Contraseña requerida para abrir",description:"Los usuarios deben ingresar una contraseña para ver este documento.",label:"Contraseña del documento",placeholder:"Ingresar contraseña",confirm:"Confirmar contraseña",confirmPlaceholder:"Confirmar contraseña"},ownerPassword:{label:"Contraseña de propietario",placeholder:"Ingresar contraseña de propietario",confirm:"Confirmar contraseña de propietario",confirmPlaceholder:"Confirmar contraseña de propietario"},permissions:{title:"Restringir permisos",description:"Limite lo que los usuarios pueden hacer con este documento.",allowedActions:"Acciones permitidas",print:"Imprimir",printHighQuality:"Imprimir alta calidad",copy:"Copiar contenido",accessibility:"Extraer para accesibilidad",modify:"Modificar contenido",annotations:"Añadir/modificar anotaciones y comentarios",fillForms:"Rellenar formularios y firmar",assemble:"Ensamblar documento y extraer páginas"},encrypted:{title:"Documento protegido",description:"Este documento está protegido por el propietario. Ingrese la contraseña de propietario para modificar la configuración de seguridad.",enterOwnerPassword:"Ingrese la contraseña de propietario para modificar",unlockAndEdit:"Desbloquear y Editar"},modifyProtection:{title:"Modificar protección",description:"Elija cómo desea modificar la protección del documento.",changeOption:"Cambiar contraseñas o permisos",changeDescription:"Actualizar la contraseña del documento o la configuración de permisos.",removeOption:"Eliminar toda la protección",removeDescription:"Eliminar la protección por contraseña de este documento."},removeProtection:{title:"Eliminar protección",warning:"¿Está seguro de que desea eliminar la protección?",description:"Esto eliminará toda la protección por contraseña del documento. Cualquiera podrá abrirlo y modificarlo.",confirm:"Eliminar protección"}},security:{protected:{title:"Este documento está protegido",description:"Este archivo está protegido y algunas funciones pueden estar deshabilitadas. Vaya a Seguridad en el menú del documento para ver o desbloquear los permisos.",viewPermissions:"Ver permisos"},viewPermissions:{title:"Permisos del documento",description:"Este archivo está restringido por el propietario y requiere una contraseña para desbloquear ciertas acciones.",restrictedActions:"Acciones restringidas"},unlock:{label:"Ingrese la contraseña de propietario para desbloquear",placeholder:"Ingresar contraseña de propietario",button:"Desbloquear archivo",invalidPassword:"Contraseña inválida. Por favor, inténtelo de nuevo.",failed:"Error al desbloquear. Por favor, inténtelo de nuevo.",success:"¡Permisos de propietario desbloqueados! Ahora tiene acceso completo."}},common:{close:"Cerrar",back:"Atrás",cancel:"Cancelar"},link:{title:"Insertar enlace",url:"URL",page:"Página",enterUrl:"Introducir URL",enterPage:"Introducir número de página",pageRange:"Página 1 a {totalPages}",link:"Enlazar"}}},{code:"zh-CN",name:"简体中文",translations:{search:{placeholder:"搜索",caseSensitive:"大小写敏感",wholeWord:"全词匹配",resultsFound:"{count} 个结果",page:"第{page}页"},zoom:{in:"放大",out:"缩小",fitWidth:"适合宽度",fitPage:"适合页面",marquee:"框选放大",menu:"缩放菜单",level:"缩放比例 ({level}%)",dragTip:"拖动鼠标选择要放大的区域"},pan:{toggle:"拖动模式"},pointer:{toggle:"光标模式"},capture:{screenshot:"截图",dragTip:"拖动鼠标选择要截取的区域",title:"截取的PDF区域",download:"下载",cancel:"取消"},document:{menu:"文件选项",open:"打开",close:"关闭",print:"打印",protect:"安全",export:"导出",fullscreen:"全屏",loading:"文件加载中..."},emptyState:{title:"尚无打开的文件",description:"请点击“+ 打开文件”按钮选择并打开一个PDF文件。",descriptionMulti:"您可以使用标签页同时打开多个文件。",openButton:"打开文件",supportedFormats:"支持的文件格式为: PDF"},passwordPrompt:{title:"请输入密码",required:"该文件设置有密码保护,要打开文件请输入密码。",incorrect:"你输入的密码错误,请重新输入。",incorrectWarning:"密码错误,请检查后重新输入。",label:"密码",placeholder:"请输入文件密码",open:"打开",opening:"打开中...",cancel:"取消",close:"关闭"},documentError:{title:"文件加载出错",unknown:"未知错误",errorCode:"错误码: {code}",close:"关闭文件"},panel:{sidebar:"大纲与书签",search:"搜索",comment:"评论",thumbnails:"缩略图",outline:"大纲",annotationStyle:"批注样式",redaction:"遮蔽侧边栏"},menu:{viewControls:"视图控件",zoomControls:"缩放控件",moreOptions:"更多选项"},outline:{title:"大纲",loading:"大纲加载中...",noOutline:"没有大纲",noBookmarks:"该文件不含书签"},page:{settings:"页面设置",single:"单页视图",twoOdd:"双页视图",twoEven:"书籍视图",vertical:"垂直滚动",horizontal:"水平滚动",spreadMode:"跨页模式",scrollLayout:"滚动布局",rotation:"页面转向",next:"下一页",previous:"上一页"},rotate:{clockwise:"顺时针旋转",counterClockwise:"逆时针旋转"},selection:{copy:"复制"},mode:{view:"阅读",annotate:"批注",shapes:"形状",redact:"遮蔽"},annotation:{text:"任意文本",highlight:"高亮",strikeout:"删除线",underline:"下划线",squiggly:"下划曲线",rectangle:"矩形",circle:"圆形",line:"直线",arrow:"带箭头直线",polygon:"多边形",polyline:"多段线",ink:"自由绘制",stamp:"印章",caret:"插入符号",insertText:"插入文本",replaceText:"替换文本",freeText:"任意文本",square:"矩形",style:"批注样式",styles:"{type} 样式",defaults:"{type} 默认值",color:"颜色",opacity:"透明度",blendMode:"混合模式",strokeWidth:"线条宽度",strokeColor:"线条颜色",borderStyle:"线条样式",fillColor:"填充色",fontSize:"字号",fontFamily:"字体",textAlign:"左右对齐",verticalAlign:"上下对齐",lineEnding:"行尾",lineStart:"线条起点",lineEnd:"线条结尾",font:"字体",fontColor:"字色",backgroundColor:"背景色",noStyles:"该批注无需设置样式。",noStylesStamp:"印章无需设置样式。",selectAnnotation:"在此处查看选中批注的样式。",deleteSelected:"删除选中的批注",deleteAllSelected:"删除选中",multiSelect:"已选择 {count} 个批注",group:"分组",ungroup:"取消分组",moreTools:"更多工具",addLink:"添加链接",removeLink:"移除链接",gotoLink:"跳转到链接",comment:"评论",redact:"遮蔽",overlayText:"覆盖文字",overlayTextPlaceholder:"例如:已遮蔽",rotation:"旋转"},redaction:{redact:"遮蔽",area:"遮蔽区域",text:"遮蔽文本",apply:"应用遮蔽",applyAll:"全部应用",clearAll:"全部取消",deleteSelected:"取消遮蔽",commitSelected:"应用遮蔽",emptyState:"暂无待处理的遮蔽",panel:{title:"遮蔽",itemCount:"{count} 个待处理遮蔽",itemCountPlural:"{count} 个待处理遮蔽",clearAll:"全部取消",redactAll:"全部遮蔽"}},history:{undo:"撤销",redo:"恢复"},comments:{page:"第{page}页",commentCount:"{count}条评论",commentCountPlural:"{count}条评论",addComment:"新增评论...",addReply:"新增回复...",showAllAnnotations:"显示所有注释",closeAllAnnotations:"关闭所有注释",save:"保存",cancel:"取消",edit:"编辑",delete:"删除",showMore:"展开",showLess:"收起",emptyState:"添加批注后,可以在这里对批注进行评论。"},blendMode:{normal:"正常",multiply:"正片",screen:"屏幕",overlay:"叠加",darken:"变暗",lighten:"变亮",colorDodge:"色彩减淡",colorBurn:"颜色加深",hardLight:"强光",softLight:"柔光",difference:"差值",exclusion:"排除",hue:"色相",saturation:"饱和度",color:"颜色",luminosity:"亮度"},print:{title:"打印设置",loading:"正在处理...",pages:"要打印的页码",all:"所有页",current:"当前页({currentPage})",specify:"指定页",specifyEG:"例如:1-3, 5, 8-10",total:"文档总页数:{totalPages}",annotation:"包含批注",printing:"打印中...",print:"打印",cancel:"取消"},protect:{title:"文档保护",cancel:"取消",apply:"应用保护",applying:"正在应用...",applyFailed:"无法应用保护。请重试。",removeFailed:"无法移除保护。请重试。",passwordMismatch:"密码不匹配",noProtectionSelected:"请至少选择一种保护方式。",bothPasswordsNote:"使用文档密码打开的用户将受到权限限制。使用所有者密码可获得完全访问权限。",openPassword:{title:"需要密码才能打开",description:"用户必须输入密码才能查看此文档。",label:"文档密码",placeholder:"输入密码",confirm:"确认密码",confirmPlaceholder:"确认密码"},ownerPassword:{label:"所有者密码",placeholder:"输入所有者密码",confirm:"确认所有者密码",confirmPlaceholder:"确认所有者密码"},permissions:{title:"限制权限",description:"限制用户对此文档的操作。",allowedActions:"允许的操作",print:"打印",printHighQuality:"高质量打印",copy:"复制内容",accessibility:"提取辅助功能",modify:"修改内容",annotations:"添加/修改批注和评论",fillForms:"填写表单和签名",assemble:"组装文档和提取页面"},encrypted:{title:"文档受保护",description:"此文档已被所有者保护。请输入所有者密码以修改安全设置。",enterOwnerPassword:"输入所有者密码以修改",unlockAndEdit:"解锁并编辑"},modifyProtection:{title:"修改保护",description:"选择如何修改文档保护。",changeOption:"更改密码或权限",changeDescription:"更新文档密码或权限设置。",removeOption:"移除所有保护",removeDescription:"移除此文档的密码保护。"},removeProtection:{title:"移除保护",warning:"确定要移除保护吗?",description:"这将移除文档的所有密码保护。任何人都可以打开和修改它。",confirm:"移除保护"}},security:{protected:{title:"此文档受保护",description:'此文件受保护,某些功能可能被禁用。请在文档菜单中点击"安全"以查看或解锁权限。',viewPermissions:"查看权限"},viewPermissions:{title:"文档权限",description:"此文件受所有者限制,需要密码才能解锁某些操作。",restrictedActions:"受限操作"},unlock:{label:"输入所有者密码以解锁文件",placeholder:"输入所有者密码",button:"解锁文件",invalidPassword:"密码无效。请重试。",failed:"解锁失败。请重试。",success:"所有者权限已解锁!您现在拥有完全访问权限。"}},common:{close:"关闭",back:"返回",cancel:"取消"},link:{title:"插入链接",url:"网址",page:"页面",enterUrl:"输入网址",enterPage:"输入页码",pageRange:"第1页到第{totalPages}页",link:"链接"}}},{code:"ja",name:"日本語",translations:{search:{placeholder:"検索",caseSensitive:"大文字小文字を区別",wholeWord:"単語単位で検索",resultsFound:"{count}件見つかりました",page:"{page}ページ"},zoom:{in:"拡大",out:"縮小",fitWidth:"幅に合わせる",fitPage:"ページに合わせる",marquee:"範囲選択ズーム",menu:"ズームメニュー",level:"ズーム ({level}%)",dragTip:"ドラッグしてズーム範囲を選択"},pan:{toggle:"パンモードの切り替え"},pointer:{toggle:"ポインターモードの切り替え"},capture:{screenshot:"スクリーンショット",dragTip:"ドラッグしてキャプチャ範囲を選択",title:"スクリーンショットプレビュー",download:"ダウンロード",cancel:"キャンセル"},document:{menu:"ドキュメントメニュー",open:"開く",close:"閉じる",print:"印刷",protect:"セキュリティ",export:"エクスポート",fullscreen:"全画面表示",loading:"ドキュメントを読み込み中..."},emptyState:{title:"ドキュメントが開かれていません",description:"PDFドキュメントを開いて始めましょう。",descriptionMulti:"タブを使って複数のドキュメントを表示できます。",openButton:"ドキュメントを開く",supportedFormats:"対応フォーマット: PDF"},passwordPrompt:{title:"パスワードが必要です",required:"このドキュメントはパスワードで保護されています。パスワードを入力してください。",incorrect:"入力されたパスワードが正しくありません。もう一度お試しください。",incorrectWarning:"パスワードが正しくありません。確認してもう一度お試しください。",label:"パスワード",placeholder:"ドキュメントのパスワードを入力",open:"開く",opening:"開いています...",cancel:"キャンセル",close:"閉じる"},documentError:{title:"ドキュメントの読み込みエラー",unknown:"不明なエラーが発生しました",errorCode:"エラーコード: {code}",close:"ドキュメントを閉じる"},panel:{sidebar:"サイドバー",search:"検索",comment:"コメント",thumbnails:"サムネイル",outline:"アウトライン",annotationStyle:"注釈スタイル",redaction:"黒塗りサイドバー"},menu:{viewControls:"表示コントロール",zoomControls:"ズームコントロール",moreOptions:"その他のオプション"},outline:{title:"アウトライン",loading:"アウトラインを読み込み中...",noOutline:"アウトラインがありません",noBookmarks:"このドキュメントにはブックマークがありません"},page:{settings:"ページ設定",single:"単一ページ",twoOdd:"見開き(奇数)",twoEven:"見開き(偶数)",vertical:"縦方向",horizontal:"横方向",spreadMode:"見開きモード",scrollLayout:"スクロールレイアウト",rotation:"ページ回転",next:"次のページ",previous:"前のページ"},rotate:{clockwise:"時計回りに回転",counterClockwise:"反時計回りに回転"},selection:{copy:"選択範囲をコピー"},mode:{view:"表示",annotate:"注釈",shapes:"図形",redact:"黒塗り"},annotation:{text:"テキスト",highlight:"ハイライト",strikeout:"取り消し線",underline:"下線",squiggly:"波線",rectangle:"四角形",circle:"円",line:"線",arrow:"矢印",polygon:"多角形",polyline:"折れ線",ink:"インク",stamp:"スタンプ",freeText:"フリーテキスト",square:"正方形",style:"注釈スタイル",styles:"{type}のスタイル",defaults:"{type}のデフォルト",color:"色",opacity:"不透明度",blendMode:"ブレンドモード",strokeWidth:"線の太さ",strokeColor:"線の色",borderStyle:"枠線のスタイル",fillColor:"塗りつぶしの色",fontSize:"フォントサイズ",fontFamily:"フォント",textAlign:"テキスト配置",verticalAlign:"縦方向の配置",lineEnding:"線の端点",lineStart:"始点",lineEnd:"終点",font:"フォント",fontColor:"フォントの色",backgroundColor:"背景色",noStyles:"この注釈にはスタイルがありません。",noStylesStamp:"スタンプにはスタイルがありません。",selectAnnotation:"注釈を選択してスタイルを表示",deleteSelected:"選択した注釈を削除",deleteAllSelected:"選択を削除",multiSelect:"{count}件の注釈が選択されています",group:"グループ化",ungroup:"グループ解除",moreTools:"その他のツール",addLink:"リンクを追加",removeLink:"リンクを削除",gotoLink:"リンク先へ移動",comment:"コメント",redact:"黒塗り",overlayText:"オーバーレイテキスト",overlayTextPlaceholder:"例: 黒塗り済み",rotation:"回転"},redaction:{redact:"黒塗り",area:"範囲の黒塗り",text:"テキストの黒塗り",apply:"黒塗りを適用",applyAll:"すべて適用",clearAll:"すべてクリア",deleteSelected:"選択した黒塗りを削除",commitSelected:"選択した黒塗りを適用",emptyState:"保留中の黒塗りはありません",panel:{title:"黒塗り",itemCount:"{count}件の保留中の黒塗り",itemCountPlural:"{count}件の保留中の黒塗り",clearAll:"すべてクリア",redactAll:"すべて黒塗り"}},history:{undo:"元に戻す",redo:"やり直す"},comments:{page:"{page}ページ",commentCount:"{count}件のコメント",commentCountPlural:"{count}件のコメント",addComment:"コメントを追加...",addReply:"返信を追加...",showAllAnnotations:"すべての注釈を表示",closeAllAnnotations:"すべての注釈を閉じる",save:"保存",cancel:"キャンセル",edit:"編集",delete:"削除",showMore:"もっと見る",showLess:"閉じる",emptyState:"注釈を追加してコメントできるようにしましょう。"},blendMode:{normal:"通常",multiply:"乗算",screen:"スクリーン",overlay:"オーバーレイ",darken:"暗く",lighten:"明るく",colorDodge:"覆い焼きカラー",colorBurn:"焼き込みカラー",hardLight:"ハードライト",softLight:"ソフトライト",difference:"差の絶対値",exclusion:"除外",hue:"色相",saturation:"彩度",color:"カラー",luminosity:"輝度"},print:{title:"印刷設定",loading:"ドキュメントを準備中...",pages:"印刷するページ",all:"すべてのページ",current:"現在のページ ({currentPage})",specify:"ページを指定",specifyEG:"例: 1-3, 5, 8-10",total:"ドキュメントの総ページ数: {totalPages}",annotation:"注釈を含める",printing:"印刷中...",print:"印刷",cancel:"キャンセル"},protect:{title:"ドキュメントの保護",cancel:"キャンセル",apply:"保護を適用",applying:"適用中...",applyFailed:"保護の適用に失敗しました。もう一度お試しください。",removeFailed:"保護の解除に失敗しました。もう一度お試しください。",passwordMismatch:"パスワードが一致しません",noProtectionSelected:"適用する保護オプションを少なくとも1つ選択してください。",bothPasswordsNote:"ドキュメントパスワードで開いたユーザーは権限が制限されます。オーナーパスワードを使用すると完全なアクセスが可能になります。",openPassword:{title:"開くにはパスワードが必要",description:"このドキュメントを表示するにはパスワードの入力が必要です。",label:"ドキュメントパスワード",placeholder:"パスワードを入力",confirm:"パスワードの確認",confirmPlaceholder:"パスワードを確認"},ownerPassword:{label:"オーナーパスワード",placeholder:"オーナーパスワードを入力",confirm:"オーナーパスワードの確認",confirmPlaceholder:"オーナーパスワードを確認"},permissions:{title:"権限を制限",description:"このドキュメントでユーザーが行える操作を制限します。",allowedActions:"許可された操作",print:"印刷",printHighQuality:"高品質印刷",copy:"コンテンツのコピー",accessibility:"アクセシビリティのための抽出",modify:"コンテンツの変更",annotations:"注釈・コメントの追加/変更",fillForms:"フォームの入力と署名",assemble:"ページの組み立てと抽出"},encrypted:{title:"ドキュメントは保護されています",description:"このドキュメントはオーナーによって保護されています。セキュリティ設定を変更するにはオーナーパスワードを入力してください。",enterOwnerPassword:"オーナーパスワードを入力して変更",unlockAndEdit:"ロック解除して編集"},modifyProtection:{title:"保護の変更",description:"ドキュメントの保護をどのように変更するか選択してください。",changeOption:"パスワードまたは権限を変更",changeDescription:"ドキュメントパスワードまたは権限設定を更新します。",removeOption:"すべての保護を解除",removeDescription:"このドキュメントからパスワード保護を解除します。"},removeProtection:{title:"保護の解除",warning:"保護を解除してもよろしいですか?",description:"ドキュメントからすべてのパスワード保護が解除されます。誰でもドキュメントを開いて変更できるようになります。",confirm:"保護を解除"}},security:{protected:{title:"このドキュメントは保護されています",description:"このファイルは保護されており、一部の機能が無効になっている場合があります。ドキュメントメニューのセキュリティから権限を確認またはロック解除できます。",viewPermissions:"権限を表示"},viewPermissions:{title:"ドキュメントの権限",description:"このファイルはオーナーによって制限されており、特定の操作をロック解除するにはパスワードが必要です。",restrictedActions:"制限された操作"},unlock:{label:"オーナーパスワードを入力してロック解除",placeholder:"オーナーパスワードを入力",button:"ファイルのロックを解除",invalidPassword:"パスワードが無効です。もう一度お試しください。",failed:"ロック解除に失敗しました。もう一度お試しください。",success:"オーナー権限がロック解除されました!完全なアクセスが可能になりました。"}},common:{close:"閉じる",back:"戻る",cancel:"キャンセル"},link:{title:"リンクの挿入",url:"URL",page:"ページ",enterUrl:"URLを入力",enterPage:"ページ番号を入力",pageRange:"1~{totalPages}ページ",link:"リンク"}}},{code:"sv",name:"Svenska",translations:{search:{placeholder:"Sök",caseSensitive:"Skiftlägeskänslig",wholeWord:"Hela ord",resultsFound:"{count} träffar",page:"Sida {page}"},zoom:{in:"Zooma in",out:"Zooma ut",fitWidth:"Sidbredd",fitPage:"Sidnivå",marquee:"Zooma till markering",menu:"Zoommeny",level:"Zoomnivå ({level}%)",dragTip:"Dra för att välja ett område att zooma in på"},pan:{toggle:"Panorera"},pointer:{toggle:"Välj"},capture:{screenshot:"Skärmdumpa",dragTip:"Dra för att välja område",title:"Förhandsgranskning",download:"Ladda ned",cancel:"Avbryt"},document:{menu:"Filmeny",open:"Öppna",close:"Stäng",print:"Skriv ut",protect:"Säkerhet",export:"Ladda ned",fullscreen:"Helskärmsläge",loading:"Läser in dokumentet..."},emptyState:{title:"Ingen fil är öppen",description:"Öppna en pdf för att komma igång.",descriptionMulti:"Du kan växla mellan olika filer med hjälp av flikar.",openButton:"Öppna fil",supportedFormats:"Format som stöds: PDF"},passwordPrompt:{title:"Lösenord krävs",required:"Den här filen är lösenordsskyddad. Skriv in lösenordet för att öppna den.",incorrect:"Lösenordet du skrev in var fel. Var god försök igen.",incorrectWarning:"Fel lösenord. Kontrollera att du skrivit rätt och försök igen.",label:"Lösenord",placeholder:"Skriv in filens lösenord",open:"Öppna",opening:"Öppnar...",cancel:"Avbryt",close:"Stäng"},documentError:{title:"Fel när dokumentet lästes in",unknown:"Ett okänt fel inträffade",errorCode:"Felkod: {code}",close:"Stäng dokumentet"},panel:{sidebar:"Sidofält",search:"Sök",comment:"Kommentera",thumbnails:"Miniatyrbilder",outline:"Dokumentdisposition",annotationStyle:"Annoteringsstil",redaction:"Sidofält för maskning"},menu:{viewControls:"Visa kontroller",zoomControls:"Zoomkontroller",moreOptions:"Fler alternativ"},outline:{title:"Dokumentdisposition",loading:"Läser in disposition...",noOutline:"Ingen disposition tillgänglig",noBookmarks:"Det här dokumentet har inga bokmärken"},page:{settings:"Sidinställningar",single:"Enkelsidig vy",twoOdd:"Dubbelsidig vy (Udda)",twoEven:"Dubbelsidig vy (Jämna)",vertical:"Lodrätt",horizontal:"Vågrätt",spreadMode:"Vy",scrollLayout:"Skrollningsläge",rotation:"Rotera",next:"Nästa sida",previous:"Föregående sida"},rotate:{clockwise:"Rotera medurs",counterClockwise:"Rotera moturs"},selection:{copy:"Kopiera markering"},mode:{view:"Läsvy",annotate:"Annotera",shapes:"Rita former",redact:"Maskera"},annotation:{text:"Text",highlight:"Överstrykningspenna",strikeout:"Genomstruken",underline:"Understruken",squiggly:"Vågig",rectangle:"Rektangel",circle:"Cirkel",line:"Linje",arrow:"Pil",polygon:"Polygon",polyline:"Flerpunktslinje",ink:"Bläck",stamp:"Stämpel",freeText:"Fritext",square:"Kvadrat",style:"Annoteringsstil",styles:"{type}stilar",defaults:"{type}förval",color:"Färg",opacity:"Genomskinlighet",blendMode:"Blandningsläge",strokeWidth:"Linjebredd",strokeColor:"Linjefärg",borderStyle:"Kantlinjestil",fillColor:"Fyllningsfärg",fontSize:"Teckenstorlek",fontFamily:"Typsnitt",textAlign:"Justering",verticalAlign:"Vertikal justering",lineEnding:"Linjeslut",lineStart:"Linjestart",lineEnd:"Linjeslut",font:"Typsnitt",fontColor:"Teckenfärg",backgroundColor:"Bakgrundsfärg",noStyles:"Den här annoteringen har inga valda stilar.",noStylesStamp:"Inga stilar finns tillgängliga.",selectAnnotation:"Välj en annotering för att se stilalternativ.",deleteSelected:"Ta bort vald annotering",deleteAllSelected:"Ta bort alla valda",multiSelect:"{count} annoteringar valda",group:"Gruppera",ungroup:"Lös upp grupp",moreTools:"Fler verktyg",addLink:"Lägg till länk",removeLink:"Ta bort länk",gotoLink:"Gå till länk",comment:"Kommentera",redact:"Maskera",overlayText:"Textöverlägg",overlayTextPlaceholder:"t.ex., MASKERAD",rotation:"Rotera"},redaction:{redact:"Maskera",area:"Maskera område",text:"Maskera text",apply:"Tillämpa maskering",applyAll:"Tillämpa alla",clearAll:"Rensa alla",deleteSelected:"Ta bort vald maskering",commitSelected:"Tillämpa vald maskering",emptyState:"Inget väntar på att maskeras",panel:{title:"Maskering",itemCount:"{count} väntar på att maskeras",itemCountPlural:"{count} väntar på att maskeras",clearAll:"Rensa alla",redactAll:"Maskera alla"}},history:{undo:"Ångra",redo:"Gör om"},comments:{page:"Sida {page}",commentCount:"{count} kommentar",commentCountPlural:"{count} kommentarer",addComment:"Lägg till kommentar...",addReply:"Lägg till svar...",showAllAnnotations:"Visa alla anteckningar",closeAllAnnotations:"Stäng alla anteckningar",save:"Spara",cancel:"Avbryt",edit:"Redigera",delete:"Radera",showMore:"mer",showLess:"mindre",emptyState:"Lägg till annoteringar för att kunna kommentera dem."},blendMode:{normal:"Normal",multiply:"Multiplicera",screen:"Skärm",overlay:"Täck över",darken:"Mörkare",lighten:"Ljusare",colorDodge:"Färgskugga",colorBurn:"Efterbelys färg",hardLight:"Skarpt ljus",softLight:"Mjukt ljus",difference:"Differens",exclusion:"Uteslutning",hue:"Nyans",saturation:"Mättnad",color:"Färg",luminosity:"Luminiscens"},print:{title:"Utskriftsinställningar",loading:"Förbereder dokument...",pages:"Sidor att skriva ut",all:"Alla sidor",current:"Aktuell sida ({currentPage})",specify:"Välj sidor",specifyEG:"t.ex. 1-3, 5, 8-10",total:"Totalt antal sidor i dokumentet: {totalPages}",annotation:"Inkludera annoteringar",printing:"Skriver ut...",print:"Skriv ut",cancel:"Avbryt"},protect:{title:"Skydda dokumentet",cancel:"Avbryt",apply:"Tillämpa skydd",applying:"Tillämpar...",applyFailed:"Misslyckades med att tillämpa skydd. Var god försök igen.",removeFailed:"Misslyckades med att ta bort skydd. Var god försök igen.",passwordMismatch:"Lösenorden stämmer inte överens",noProtectionSelected:"Välj minst ett alternativ att tillämpa.",bothPasswordsNote:"Användare som öppnar dokumentet med lösenordet kommer ha begränsade behörigheter. Använd ägarlösenordet för att låsa upp alla behörigheter.",openPassword:{title:"Kräv lösenord för att öppna fil",description:"Användare måste skriva in ett lösenord för att öppna dokumentet.",label:"Dokumentlösenord",placeholder:"Skriv in lösenord",confirm:"Bekräfta lösenord",confirmPlaceholder:"Bekräfta lösenord"},ownerPassword:{label:"Ägarlösenord",placeholder:"Skriv in ägarlösenord",confirm:"Bekräfta ägarlösenord",confirmPlaceholder:"Bekräfta ägarlösenord"},permissions:{title:"Begränsa behörigheter",description:"Begränsa vad användaren kan göra med dokumentet.",allowedActions:"Tillåtna handlingar",print:"Skriv ut",printHighQuality:"Skriv ut i hög kvalitet",copy:"Kopiera innehåll",accessibility:"Extrahera för tillgänglighet",modify:"Ändra innehåll",annotations:"Lägga till/ändra annoteringar & kommentarer",fillForms:"Fylla i formulär & signera",assemble:"Ordna sidor"},encrypted:{title:"Dokumentet är skyddat",description:"Det här dokumentet skyddas av ägaren. Skriv in ägarlösenordet för att ändra säkerhetsinställningarna.",enterOwnerPassword:"Skriv in ägarlösenordet för att redigera",unlockAndEdit:"Lås upp & redigera"},modifyProtection:{title:"Ändra skydd",description:"Välj hur du vill ändra dokumentskyddet.",changeOption:"Ändra lösenord eller behörigheter",changeDescription:"Ändra dokumentets lösenord eller behörigheter.",removeOption:"Ta bort alla skydd",removeDescription:"Ta bort lösenordsskydd från dokumentet."},removeProtection:{title:"Ta bort skydd",warning:"Är du säker på att du vill ta bort skydd?",description:"Det här kommer ta bort allt lösenordsskydd från dokumentet. Vem som helst kommer kunna öppna och ändra det.",confirm:"Ta bort skydd"}},security:{protected:{title:"Det här dokumentet är skyddat",description:"Den här filen är skyddad och vissa funktioner kan vara inaktiverade. Gå till Säkerhet i filmenyn för att visa eller låsa upp behörigheter.",viewPermissions:"Visa behörigheter"},viewPermissions:{title:"Filbehörigheter",description:"Den här filen är skyddad av ägaren och kräver ett lösenord för vissa handlingar.",restrictedActions:"Begränsade handlingar"},unlock:{label:"Skriv in ägarlösenordet för att låsa upp filen",placeholder:"Skriv in ägarlösenordet",button:"Lås upp filen",invalidPassword:"Ogiltigt lösenord. Var vänlig försök igen.",failed:"Misslyckades med att låsa upp. Var vänlig försök igen.",success:"Ägarbehörighet upplåst! Du har nu full åtkomst."}},common:{close:"Stäng",back:"Tillbaka",cancel:"Avbryt"},link:{title:"Lägg till länk",url:"URL",page:"Sida",enterUrl:"Skriv in URL",enterPage:"Skriv in sidnummer",pageRange:"Sida 1 till {totalPages}",link:"Länk"}}}],paramResolvers:Ob},ui:{schema:{id:"pdf-viewer-ui",version:"1.0.0",toolbars:{"main-toolbar":{id:"main-toolbar",position:{placement:"top",slot:"main",order:0},permanent:!0,responsive:{localeOverrides:{groups:[{id:"cjk-languages",locales:["zh-CN","ja"],breakpoints:{sm:{replaceHide:["zoom-toolbar","mode-select-button","overflow-tabs-button"],replaceShow:["view-mode","annotate-mode","shapes-mode","redact-mode","pan-button","pointer-button","divider-3"]},md:{replaceShow:["view-mode","annotate-mode","shapes-mode","redact-mode","zoom-toolbar","pan-button","pointer-button","divider-3"],replaceHide:["zoom-menu-button","mode-select-button","overflow-tabs-button"]}}},{id:"germanic-languages",locales:["de","nl"],breakpoints:{md:{replaceShow:["view-mode","annotate-mode","zoom-toolbar","pan-button","pointer-button","divider-3","overflow-tabs-button"]}}}]},breakpoints:{xxxs:{maxWidth:400,hide:["annotate-mode","view-mode","shapes-mode","redact-mode","zoom-toolbar","pan-button","pointer-button","divider-3","page-settings-button","zoom-menu-button","divider-2","overflow-tabs-button"],show:["mode-select-button"]},xxs:{minWidth:400,show:["page-settings-button","zoom-menu-button","divider-2"],hide:["overflow-left-action-menu-button"]},xs:{minWidth:500,maxWidth:640,show:["pan-button","pointer-button","divider-3"]},sm:{minWidth:640,maxWidth:768,hide:["shapes-mode","redact-mode","zoom-toolbar","mode-select-button"],show:["view-mode","annotate-mode","overflow-tabs-button","pan-button","pointer-button","divider-3"]},md:{minWidth:768,show:["view-mode","annotate-mode","shapes-mode","zoom-toolbar","pan-button","pointer-button","divider-3","overflow-tabs-button"],hide:["zoom-menu-button","mode-select-button"]},lg:{minWidth:1024,show:["shapes-mode","redact-mode"],hide:["overflow-tabs-button"]}}},items:[{type:"group",id:"left-group",alignment:"start",gap:2,items:[{type:"command-button",id:"document-menu-button",commandId:"document:menu",variant:"icon",categories:["document","document-menu"]},{type:"divider",id:"divider-1",orientation:"vertical"},{type:"command-button",id:"sidebar-button",commandId:"panel:toggle-sidebar",variant:"icon",categories:["panel","panel-sidebar"]},{type:"command-button",id:"overflow-left-action-menu-button",commandId:"left-action-menu:overflow-menu",variant:"icon",categories:["ui","ui-menu"]},{type:"command-button",id:"page-settings-button",commandId:"page:settings",variant:"icon",categories:["page","page-settings"]}]},{type:"divider",id:"divider-2",orientation:"vertical"},{type:"group",id:"center-group",alignment:"center",gap:2,items:[{type:"command-button",id:"zoom-menu-button",commandId:"zoom:toggle-menu-mobile",variant:"icon",categories:["zoom","zoom-menu"]},{type:"custom",id:"zoom-toolbar",componentId:"zoom-toolbar",categories:["zoom"]},{type:"divider",id:"divider-3",orientation:"vertical",visibilityDependsOn:{itemIds:["zoom-toolbar","zoom-menu-button"]}},{type:"command-button",id:"pan-button",commandId:"pan:toggle",variant:"icon",categories:["tools","pan"]},{type:"command-button",id:"pointer-button",commandId:"pointer:toggle",variant:"icon",categories:["tools","pointer"]}]},{type:"spacer",id:"spacer-1",flex:!0},{type:"custom",id:"mode-select-button",componentId:"mode-select-button",categories:["mode"],visibilityDependsOn:{itemIds:["mode:annotate","mode:shapes","mode:redact"]}},{type:"tab-group",id:"mode-tabs",tabs:[{id:"view-mode",commandId:"mode:view",variant:"text",categories:["mode","mode-view"],visibilityDependsOn:{itemIds:["annotate-mode","shapes-mode","redact-mode"]}},{id:"annotate-mode",commandId:"mode:annotate",variant:"text",categories:["mode","mode-annotate","annotation"]},{id:"shapes-mode",commandId:"mode:shapes",variant:"text",categories:["mode","mode-shapes","annotation"]},{id:"redact-mode",commandId:"mode:redact",variant:"text",categories:["mode","mode-redact","redaction"]},{id:"overflow-tabs-button",commandId:"tabs:overflow-menu",variant:"icon",categories:["ui","ui-menu"],visibilityDependsOn:{menuId:"mode-tabs-overflow-menu"}}]},{type:"spacer",id:"spacer-2",flex:!0},{type:"group",id:"right-group",alignment:"end",gap:2,items:[{type:"command-button",id:"search-button",commandId:"panel:toggle-search",variant:"icon",categories:["panel","panel-search"]},{type:"command-button",id:"comment-button",commandId:"panel:toggle-comment",variant:"icon",categories:["panel","panel-comment"]}]}]},"annotation-toolbar":{id:"annotation-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-text","add-stamp","add-ink","add-insert-text","add-replace-text","add-comment"],show:["overflow-annotation-tools"]},md:{minWidth:640,hide:["overflow-annotation-tools"],show:["add-text","add-stamp","add-ink","add-insert-text","add-replace-text","add-comment"]}}},permanent:!1,categories:["annotation"],items:[{type:"spacer",id:"spacer-3",flex:!0},{type:"group",id:"annotation-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-highlight",commandId:"annotation:add-highlight",variant:"icon",categories:["annotation","annotation-markup","annotation-highlight"]},{type:"command-button",id:"add-strikeout",commandId:"annotation:add-strikeout",variant:"icon",categories:["annotation","annotation-markup","annotation-strikeout"]},{type:"command-button",id:"add-underline",commandId:"annotation:add-underline",variant:"icon",categories:["annotation","annotation-markup","annotation-underline"]},{type:"command-button",id:"add-squiggly",commandId:"annotation:add-squiggly",variant:"icon",categories:["annotation","annotation-markup","annotation-squiggly"]},{type:"command-button",id:"add-ink",commandId:"annotation:add-ink",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-text",commandId:"annotation:add-text",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"add-insert-text",commandId:"annotation:add-insert-text",variant:"icon",categories:["annotation","annotation-markup","annotation-insert-text"]},{type:"command-button",id:"add-replace-text",commandId:"annotation:add-replace-text",variant:"icon",categories:["annotation","annotation-markup","annotation-replace-text"]},{type:"command-button",id:"add-comment",commandId:"annotation:add-comment",variant:"icon",categories:["annotation","annotation-comment-tool"]},{type:"command-button",id:"add-stamp",commandId:"annotation:add-stamp",variant:"icon",categories:["annotation","annotation-stamp"]},{type:"command-button",id:"overflow-annotation-tools",commandId:"annotation:overflow-tools",variant:"icon",categories:["annotation","annotation-overflow"]},{type:"divider",id:"annotation-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"annotation-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-4",flex:!0}]},"shapes-toolbar":{id:"shapes-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-polygon","add-polyline"],show:["overflow-shapes-tools"]},md:{minWidth:640,hide:["overflow-shapes-tools"],show:["add-polygon","add-polyline"]}}},permanent:!1,categories:["annotation","annotation-shape"],items:[{type:"spacer",id:"spacer-5",flex:!0},{type:"group",id:"shapes-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rectangle",commandId:"annotation:add-rectangle",variant:"icon",categories:["annotation","annotation-shape","annotation-rectangle"]},{type:"command-button",id:"add-circle",commandId:"annotation:add-circle",variant:"icon",categories:["annotation","annotation-shape","annotation-circle"]},{type:"command-button",id:"add-line",commandId:"annotation:add-line",variant:"icon",categories:["annotation","annotation-shape","annotation-line"]},{type:"command-button",id:"add-arrow",commandId:"annotation:add-arrow",variant:"icon",categories:["annotation","annotation-shape","annotation-arrow"]},{type:"command-button",id:"add-polygon",commandId:"annotation:add-polygon",variant:"icon",categories:["annotation","annotation-shape","annotation-polygon"]},{type:"command-button",id:"add-polyline",commandId:"annotation:add-polyline",variant:"icon",categories:["annotation","annotation-shape","annotation-polyline"]},{type:"command-button",id:"overflow-shapes-tools",commandId:"annotation:overflow-shapes",variant:"icon",categories:["annotation","annotation-shape","annotation-overflow"]},{type:"divider",id:"shapes-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"shapes-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-6",flex:!0}]},"redaction-toolbar":{id:"redaction-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["redaction"],items:[{type:"spacer",id:"spacer-7",flex:!0},{type:"group",id:"redaction-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"redact",commandId:"redaction:redact",variant:"icon",categories:["redaction","redaction-combined"]},{type:"divider",id:"redaction-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-redaction-panel",commandId:"panel:toggle-redaction",variant:"icon",categories:["panel","panel-redaction"]},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"redaction-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-8",flex:!0}]}},menus:{"left-action-menu":{id:"left-action-menu",categories:["ui"],items:[{type:"submenu",id:"page-settings-submenu",labelKey:"menu.viewControls",label:"View Controls",icon:"viewSettings",menuId:"page-settings-menu",categories:["page"]},{type:"submenu",id:"zoom-submenu",labelKey:"menu.zoomControls",label:"Zoom Controls",icon:"zoomIn",menuId:"zoom-menu",categories:["zoom"]},{type:"divider",id:"divider-15"},{type:"command",id:"pan-button-menu",commandId:"pan:toggle",categories:["tools","pan"]},{type:"command",id:"pointer-button-menu",commandId:"pointer:toggle",categories:["tools","pointer"]}]},"mode-tabs-overflow-menu":{id:"mode-tabs-overflow-menu",items:[{type:"command",id:"mode:view",commandId:"mode:view",categories:["mode","mode-view"]},{type:"command",id:"mode:annotate",commandId:"mode:annotate",categories:["mode","mode-annotate","annotation"]},{type:"command",id:"mode:shapes",commandId:"mode:shapes",categories:["mode","mode-shapes","annotation"]},{type:"command",id:"mode:redact",commandId:"mode:redact",categories:["mode","mode-redact","redaction"]}],responsive:{breakpoints:{xs:{maxWidth:640,show:["mode:view","mode:annotate","mode:shapes","mode:redact"]},sm:{minWidth:640,maxWidth:768,hide:["mode:view","mode:annotate"]},md:{minWidth:768,hide:["mode:view","mode:annotate","mode:shapes"]}},localeOverrides:{groups:[{id:"germanic-languages",locales:["de","nl"],breakpoints:{md:{replaceHide:["mode:view","mode:annotate"]}}}]}}},"zoom-levels-menu":{id:"zoom-levels-menu",categories:["zoom","zoom-level"],items:[{type:"command",id:"zoom-levels-menu:25",commandId:"zoom:25",categories:["zoom","zoom-level","zoom-level-25"]},{type:"command",id:"zoom-levels-menu:50",commandId:"zoom:50",categories:["zoom","zoom-level","zoom-level-50"]},{type:"command",id:"zoom-levels-menu:100",commandId:"zoom:100",categories:["zoom","zoom-level","zoom-level-100"]},{type:"command",id:"zoom-levels-menu:125",commandId:"zoom:125",categories:["zoom","zoom-level","zoom-level-125"]},{type:"command",id:"zoom-levels-menu:150",commandId:"zoom:150",categories:["zoom","zoom-level","zoom-level-150"]},{type:"command",id:"zoom-levels-menu:200",commandId:"zoom:200",categories:["zoom","zoom-level","zoom-level-200"]},{type:"command",id:"zoom-levels-menu:400",commandId:"zoom:400",categories:["zoom","zoom-level","zoom-level-400"]},{type:"command",id:"zoom-levels-menu:800",commandId:"zoom:800",categories:["zoom","zoom-level","zoom-level-800"]},{type:"command",id:"zoom-levels-menu:1600",commandId:"zoom:1600",categories:["zoom","zoom-level","zoom-level-1600"]}]},"zoom-menu":{id:"zoom-menu",categories:["zoom"],items:[{type:"command",id:"zoom-menu:25",commandId:"zoom:25",categories:["zoom","zoom-level","zoom-level-25"]},{type:"command",id:"zoom-menu:50",commandId:"zoom:50",categories:["zoom","zoom-level","zoom-level-50"]},{type:"command",id:"zoom-menu:100",commandId:"zoom:100",categories:["zoom","zoom-level","zoom-level-100"]},{type:"command",id:"zoom-menu:125",commandId:"zoom:125",categories:["zoom","zoom-level","zoom-level-125"]},{type:"command",id:"zoom-menu:150",commandId:"zoom:150",categories:["zoom","zoom-level","zoom-level-150"]},{type:"command",id:"zoom-menu:200",commandId:"zoom:200",categories:["zoom","zoom-level","zoom-level-200"]},{type:"command",id:"zoom-menu:400",commandId:"zoom:400",categories:["zoom","zoom-level","zoom-level-400"]},{type:"command",id:"zoom-menu:800",commandId:"zoom:800",categories:["zoom","zoom-level","zoom-level-800"]},{type:"command",id:"zoom-menu:1600",commandId:"zoom:1600",categories:["zoom","zoom-level","zoom-level-1600"]},{type:"submenu",id:"zoom-levels-submenu",labelKey:"zoom.level",label:"Zoom Levels",menuId:"zoom-levels-menu",categories:["zoom","zoom-level"]},{type:"divider",id:"divider-zoom-in-out"},{type:"command",id:"zoom-menu:in",commandId:"zoom:in",categories:["zoom","zoom-in"]},{type:"command",id:"zoom-menu:out",commandId:"zoom:out",categories:["zoom","zoom-out"]},{type:"divider",id:"divider-8"},{type:"command",id:"zoom:fit-page",commandId:"zoom:fit-page",categories:["zoom","zoom-fit-page"]},{type:"command",id:"zoom:fit-width",commandId:"zoom:fit-width",categories:["zoom","zoom-fit-width"]},{type:"divider",id:"divider-9"},{type:"command",id:"zoom:marquee",commandId:"zoom:marquee",categories:["zoom","zoom-marquee"]}],responsive:{breakpoints:{xs:{maxWidth:640,show:["zoom-levels-submenu","divider-zoom-in-out"],hide:["zoom-menu:25","zoom-menu:50","zoom-menu:100","zoom-menu:125","zoom-menu:150","zoom-menu:200","zoom-menu:400","zoom-menu:800","zoom-menu:1600"]},md:{minWidth:768,show:["zoom-menu:25","zoom-menu:50","zoom-menu:100","zoom-menu:125","zoom-menu:150","zoom-menu:200","zoom-menu:400","zoom-menu:800","zoom-menu:1600"],hide:["zoom-levels-submenu","divider-zoom-in-out","zoom-menu:in","zoom-menu:out"]}}}},"document-menu":{id:"document-menu",categories:["document"],items:[{type:"command",id:"document:open",commandId:"document:open",categories:["document","document-open"]},{type:"command",id:"document:close",commandId:"document:close",categories:["document","document-close"]},{type:"divider",id:"divider-10",visibilityDependsOn:{itemIds:["document:open","document:close"]}},{type:"command",id:"document:print",commandId:"document:print",categories:["document","document-print"]},{type:"command",id:"document:protect",commandId:"document:protect",categories:["document","document-protect"]},{type:"command",id:"document:capture",commandId:"document:capture",categories:["document","document-capture"]},{type:"command",id:"document:export",commandId:"document:export",categories:["document","document-export"]},{type:"divider",id:"divider-11",visibilityDependsOn:{itemIds:["document:export","document:print","document:capture","document:protect"]}},{type:"command",id:"document:fullscreen",commandId:"document:fullscreen",categories:["document","document-fullscreen"]}]},"annotation-tools-menu":{id:"annotation-tools-menu",categories:["annotation"],items:[{type:"command",id:"annotation:add-ink",commandId:"annotation:add-ink",categories:["annotation","annotation-ink"]},{type:"command",id:"annotation:add-text",commandId:"annotation:add-text",categories:["annotation","annotation-text"]},{type:"command",id:"annotation:add-insert-text",commandId:"annotation:add-insert-text",categories:["annotation","annotation-markup","annotation-insert-text"]},{type:"command",id:"annotation:add-replace-text",commandId:"annotation:add-replace-text",categories:["annotation","annotation-markup","annotation-replace-text"]},{type:"command",id:"annotation:add-comment",commandId:"annotation:add-comment",categories:["annotation","annotation-comment-tool"]},{type:"command",id:"annotation:add-stamp",commandId:"annotation:add-stamp",categories:["annotation","annotation-stamp"]}]},"shapes-tools-menu":{id:"shapes-tools-menu",categories:["annotation","annotation-shape"],items:[{type:"command",id:"annotation:add-polygon",commandId:"annotation:add-polygon",categories:["annotation","annotation-shape","annotation-polygon"]},{type:"command",id:"annotation:add-polyline",commandId:"annotation:add-polyline",categories:["annotation","annotation-shape","annotation-polyline"]}]},"page-settings-menu":{id:"page-settings-menu",categories:["page"],items:[{type:"section",id:"spread-mode-section",labelKey:"page.spreadMode",label:"Spread Mode",categories:["page","spread"],items:[{type:"command",id:"spread:none",commandId:"spread:none",categories:["page","spread","spread-none"]},{type:"command",id:"spread:odd",commandId:"spread:odd",categories:["page","spread","spread-odd"]},{type:"command",id:"spread:even",commandId:"spread:even",categories:["page","spread","spread-even"]}]},{type:"divider",id:"divider-13"},{type:"section",id:"scroll-layout-section",labelKey:"page.scrollLayout",label:"Scroll Layout",categories:["page","scroll"],items:[{type:"command",id:"scroll:vertical",commandId:"scroll:vertical",categories:["page","scroll","scroll-vertical"]},{type:"command",id:"scroll:horizontal",commandId:"scroll:horizontal",categories:["page","scroll","scroll-horizontal"]}]},{type:"divider",id:"divider-14"},{type:"section",id:"page-rotation-section",labelKey:"page.rotation",label:"Page Rotation",categories:["page","rotate"],items:[{type:"command",id:"rotate:clockwise",commandId:"rotate:clockwise",categories:["page","rotate","rotate-clockwise"]},{type:"command",id:"rotate:counter-clockwise",commandId:"rotate:counter-clockwise",categories:["page","rotate","rotate-counter-clockwise"]}]},{type:"divider",id:"divider-15"},{type:"command",id:"document:fullscreen",commandId:"document:fullscreen",categories:["document","document-fullscreen"]}]}},sidebars:{"sidebar-panel":{id:"sidebar-panel",position:{placement:"left",slot:"main",order:0},content:{type:"tabs",tabs:[{id:"thumbnails",labelKey:"panel.thumbnails",label:"Thumbnails",icon:"squares",componentId:"thumbnails-sidebar"},{id:"outline",labelKey:"panel.outline",label:"Outline",icon:"listTree",componentId:"outline-sidebar"}]},width:"250px",collapsible:!0,defaultOpen:!1},"annotation-panel":{id:"annotation-panel",position:{placement:"left",slot:"main",order:0},content:{type:"component",componentId:"annotation-sidebar"},width:"250px",collapsible:!0,defaultOpen:!1},"search-panel":{id:"search-panel",position:{placement:"right",slot:"main",order:0},content:{type:"component",componentId:"search-sidebar"},width:"250px",collapsible:!0,defaultOpen:!1},"comment-panel":{id:"comment-panel",position:{placement:"right",slot:"main",order:0},content:{type:"component",componentId:"comment-sidebar"},width:"250px",collapsible:!0,defaultOpen:!1},"redaction-panel":{id:"redaction-panel",position:{placement:"right",slot:"main",order:0},content:{type:"component",componentId:"redaction-sidebar"},width:"250px",collapsible:!0,defaultOpen:!1,categories:["redaction"]}},modals:{"print-modal":{id:"print-modal",content:{type:"component",componentId:"print-modal"},maxWidth:"28rem",closeOnClickOutside:!0,closeOnEscape:!0},"protect-modal":{id:"protect-modal",content:{type:"component",componentId:"protect-modal"},maxWidth:"28rem",closeOnClickOutside:!0,closeOnEscape:!0},"view-permissions-modal":{id:"view-permissions-modal",content:{type:"component",componentId:"view-permissions-modal"},maxWidth:"28rem",closeOnClickOutside:!0,closeOnEscape:!0},"link-modal":{id:"link-modal",content:{type:"component",componentId:"link-modal"},maxWidth:"28rem",closeOnClickOutside:!0,closeOnEscape:!0}},overlays:{"page-controls":{id:"page-controls",position:{anchor:"bottom-center",offset:{bottom:"1.5rem"}},content:{type:"component",componentId:"page-controls"},defaultEnabled:!0},"unlock-owner-overlay":{id:"unlock-owner-overlay",position:{anchor:"bottom-right",offset:{bottom:"1.5rem",right:"1.5rem"}},content:{type:"component",componentId:"unlock-owner-overlay"},defaultEnabled:!0}},selectionMenus:{annotation:{id:"annotation",categories:["annotation"],items:[{type:"command-button",id:"comment-button",commandId:"annotation:toggle-comment",variant:"icon",categories:["annotation","annotation-comment"]},{type:"command-button",id:"toggle-link",commandId:"annotation:toggle-link",variant:"icon",categories:["annotation","annotation-link"]},{type:"command-button",id:"toggle-annotation-style",commandId:"annotation:toggle-annotation-style",variant:"icon",categories:["annotation","annotation-style"]},{type:"command-button",id:"apply-redaction",commandId:"annotation:apply-redaction",variant:"icon",categories:["annotation","annotation-redaction"]},{type:"command-button",id:"delete-annotation",commandId:"annotation:delete-selected",variant:"icon",categories:["annotation","annotation-delete"]},{type:"command-button",id:"goto-link",commandId:"annotation:goto-link",variant:"icon-text",categories:["annotation","annotation-link"]}]},groupAnnotation:{id:"groupAnnotation",categories:["annotation","annotation-group"],items:[{type:"command-button",id:"comment-button",commandId:"annotation:toggle-comment",variant:"icon",categories:["annotation","annotation-comment"]},{type:"command-button",id:"toggle-group-annotations",commandId:"annotation:toggle-group",variant:"icon",categories:["annotation","annotation-group"]},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"command-button",id:"delete-all-annotations",commandId:"annotation:delete-all-selected",variant:"icon",categories:["annotation","annotation-delete","annotation-group"]}]},redaction:{id:"redaction",categories:["redaction"],items:[{type:"command-button",id:"delete-redaction",commandId:"redaction:delete-selected",variant:"icon",categories:["redaction","redaction-delete"]},{type:"command-button",id:"commit-redaction",commandId:"redaction:commit-selected",variant:"icon",categories:["redaction","redaction-commit"]}]},selection:{id:"selection",visibilityDependsOn:{itemIds:["copy-selection","add-highlight","add-strikeout","add-underline","add-squiggly","add-link","redact-text"]},items:[{type:"command-button",id:"copy-selection",commandId:"selection:copy",variant:"icon",categories:["selection","selection-copy"]},{type:"command-button",id:"add-highlight",commandId:"annotation:add-highlight",variant:"icon",categories:["annotation","annotation-markup","annotation-highlight"]},{type:"command-button",id:"add-strikeout",commandId:"annotation:add-strikeout",variant:"icon",categories:["annotation","annotation-markup","annotation-strikeout"]},{type:"command-button",id:"add-underline",commandId:"annotation:add-underline",variant:"icon",categories:["annotation","annotation-markup","annotation-underline"]},{type:"command-button",id:"add-squiggly",commandId:"annotation:add-squiggly",variant:"icon",categories:["annotation","annotation-markup","annotation-squiggly"]},{type:"command-button",id:"add-link",commandId:"annotation:add-link",variant:"icon",categories:["annotation","annotation-link"]},{type:"command-button",id:"redact-text",commandId:"redaction:redact-text",variant:"icon",categories:["redaction","redaction-text"]}]}}}},viewport:{viewportGap:10},scroll:{defaultStrategy:pi.Vertical},zoom:{defaultZoomLevel:Wa.FitPage},spread:{defaultSpreadMode:Ti.None},rotation:{defaultRotation:We.Degree0},pan:{},render:{defaultImageType:"image/png"},tiling:{tileSize:768,overlapPx:2.5,extraRings:0},thumbnails:{width:150,gap:10,buffer:3,labelHeight:30},annotations:{},search:{},selection:{},bookmarks:{},attachments:{},capture:{scale:2,imageType:"image/png"},redaction:{drawBlackBoxes:!0,useAnnotationMode:!0},print:{},export:{defaultFileName:"document.pdf"},fullscreen:{},history:{},interactionManager:{}};function nw(e){var t=e.documentId,n=e.tabBarVisibility,o=void 0===n?"multiple":n,i=function(e){const t=ua(),{provides:n}=Qr(),o=null==n?void 0:n.getSchema(),i=Jr(e);return{renderToolbar:(r,a)=>{const s=`${r}-${a}`;if(!o||!n||!i)return null;const l=i.activeToolbars[s],c=l?o.toolbars[l.toolbarId]:null;l&&!c&&console.warn(`Toolbar "${l.toolbarId}" not found in schema`);const d=c&&!c.permanent?()=>n.forDocument(e).closeToolbarSlot(r,a):void 0,u=t.toolbar;return He(H,{children:l&&c&&He(u,{schema:c,documentId:e,isOpen:l.isOpen,onClose:d})},`toolbar-slot-${s}`)},renderSidebar:(r,a)=>{var s;const l=`${r}-${a}`;if(!o||!n||!i)return null;const c=i.activeSidebars[l],d=c?null==(s=o.sidebars)?void 0:s[c.sidebarId]:null;c&&!d&&console.warn(`Sidebar "${c.sidebarId}" not found in schema`);const u=t.sidebar;return He(H,{children:c&&d&&He(u,{schema:d,documentId:e,isOpen:c.isOpen,onClose:()=>{n.forDocument(e).closeSidebarSlot(r,a)}})},`sidebar-slot-${l}`)},renderModal:()=>{var r;if(!o||!n||!i)return null;const a=t.modal;if(!a)return null;const s=i.activeModal,l=s?null==(r=o.modals)?void 0:r[s.modalId]:null;return s&&!l&&console.warn(`Modal "${s.modalId}" not found in schema`),He(H,{children:s&&l&&He(a,{schema:l,documentId:e,isOpen:s.isOpen,onClose:()=>{n.forDocument(e).closeModal()},onExited:()=>{n.forDocument(e).clearModal()},modalProps:s.props})},"modal-slot")},getActiveToolbars:()=>i?Object.entries(i.activeToolbars).map(([e,t])=>{const[n,o]=e.split("-");return{placement:n,slot:o,toolbarId:t.toolbarId,isOpen:t.isOpen}}):[],getActiveSidebars:()=>i?Object.entries(i.activeSidebars).map(([e,t])=>{const[n,o]=e.split("-");return{placement:n,slot:o,sidebarId:t.sidebarId,isOpen:t.isOpen}}):[],renderOverlays:()=>{if(!o||!n||!i)return null;const r=t.overlay;return r?He(H,{children:(o.overlays?Object.values(o.overlays):[]).filter(e=>!1!==i.enabledOverlays[e.id]).map(t=>He(r,{schema:t,documentId:e},t.id))},"overlays-slot"):null}}}(t),r=i.renderToolbar,a=i.renderSidebar,s=i.renderModal,l=i.renderOverlays,c=Ha(t).translate,d=ha("selection",t),u=ha("annotation",t),h=ha("groupAnnotation",t),m=ha("redaction",t),g=(e=>{const t=$o();return Re(()=>t?t.documentOrder.map(e=>t.documents[e]).filter(e=>null!=e):[],[t,e])})(),p=(()=>{const e=$o();return Re(()=>{if(!e)return{activeDocumentId:null,activeDocument:null};const t=e.activeDocumentId;return{activeDocumentId:t,activeDocument:t?e.documents[t]??null:null}},[e])})();return F(H,null,F(qb,{documentStates:g,activeDocumentId:p.activeDocumentId,visibility:o}),r("top","main"),r("top","secondary"),F("div",{id:"document-content",className:"bg-bg-surface flex flex-1 overflow-hidden"},a("left","main"),F("div",{className:"flex-1 overflow-hidden"},F(ba,{documentId:t},function(e){var n=e.documentState,o=e.isLoading,i=e.isError,r=e.isLoaded;return F(H,null,o&&F("div",{className:"flex h-full items-center justify-center"},F(vy,{size:"lg",text:c("document.loading")})),i&&F(Vb,{documentState:n}),r&&F("div",{className:"relative h-full w-full"},F(ph,{documentId:t},F(gi,{className:"bg-bg-app",documentId:t},F(rs,{documentId:t},F(zi,{documentId:t,renderPage:function(e){var n=e.pageIndex;return F(xs,{documentId:t,pageIndex:n,style:{backgroundColor:"#fff"}},F(fh,{documentId:t,pageIndex:n},F(us,{documentId:t,pageIndex:n,scale:.5,style:{pointerEvents:"none"}}),F(lc,{documentId:t,pageIndex:n,style:{pointerEvents:"none"}}),F(Ws,{documentId:t,pageIndex:n}),F(as,{documentId:t,pageIndex:n}),F(jm,{documentId:t,pageIndex:n}),F(ql,{documentId:t,pageIndex:n,selectionMenu:d}),F(zg,{documentId:t,pageIndex:n,selectionMenu:m}),F(Yh,{documentId:t,pageIndex:n,selectionMenu:u,groupSelectionMenu:h})))}})))),l()))})),a("right","main")),s())}var ow=new yt([new pt,new vt]);function iw(e){var t,o=e.config,i=e.onRegistryReady,r=function(e){const{wasmUrl:t=qo,worker:n=!0,logger:o,encoderPoolSize:i,fontFallback:r}=e??{},[a,s]=Se(null),[l,c]=Se(!0),[d,u]=Se(null),h=De(null);return Me(()=>{let e=!1;return(async()=>{try{const{createPdfiumEngine:e}=n?await import("./worker-engine-CW9-K7eD.js"):await import("./direct-engine-Bd0KtghI.js"),a=await e(t,{logger:o,encoderPoolSize:i,fontFallback:r});h.current=a,s(a),c(!1)}catch(t){e||(u(t),c(!1))}})(),()=>{var t,n;e=!0,null==(n=null==(t=h.current)?void 0:t.closeAllDocuments)||n.call(t).wait(()=>{var e,t;null==(t=null==(e=h.current)?void 0:e.destroy)||t.call(e),h.current=null},Ln)}},[t,n,o,r]),{engine:a,isLoading:l,error:d}}(h(h(h({},o.wasmUrl&&{wasmUrl:o.wasmUrl}),o.fontFallback&&{fontFallback:o.fontFallback}),{},{worker:o.worker,logger:o.log?ow:void 0})),a=r.engine,s=r.isLoading,l=Re(function(){return{"thumbnails-sidebar":uy,"annotation-sidebar":kb,"zoom-toolbar":Ly,"search-sidebar":py,"outline-sidebar":fy,"comment-sidebar":Ny,"print-modal":Tb,"link-modal":Eb,"protect-modal":Qb,"unlock-owner-overlay":Jb,"page-controls":_b,"mode-select-button":Kb,"view-permissions-modal":ew,"redaction-sidebar":Ab}},[]),c=Re(function(){return{toolbar:Bv,sidebar:ey,modal:dy,overlay:Rb,menu:oy,selectionMenu:Mb}},[]);return F(H,null,F("style",null,Fe),!a||s?F("div",{className:"flex h-full w-full items-center justify-center"},F(vy,{size:"lg",text:"Initializing PDF engine..."})):F(No,{config:{logger:o.log?ow:void 0,permissions:o.permissions},onInitialized:(t=n(g().m(function e(t){return g().w(function(e){for(;;)switch(e.n){case 0:i&&t&&i(t);case 1:return e.a(2)}},e)})),function(e){return t.apply(this,arguments)}),engine:a,plugins:[vo(xa,h(h(h({},tw.documentManager),o.src&&{initialDocuments:[{url:o.src}]}),o.documentManager)),vo(za,h(h(h({},tw.commands),o.disabledCategories&&{disabledCategories:o.disabledCategories}),o.commands)),vo(Ua,h(h({},tw.i18n),o.i18n)),vo(Xr,h(h(h({},tw.ui),o.disabledCategories&&{disabledCategories:o.disabledCategories}),o.ui)),vo(di,h(h({},tw.viewport),o.viewport)),vo(Pi,h(h({},tw.scroll),o.scroll)),vo(ts,h(h({},tw.zoom),o.zoom)),vo(Wi,h(h({},tw.spread),o.spread)),vo(ws,h(h({},tw.rotation),o.rotation)),vo(Mm,h(h({},tw.pan),o.pan)),vo(ds,h(h({},tw.render),o.render)),vo(rc,h(h({},tw.tiling),o.tiling)),vo(wc,h(h({},tw.thumbnails),o.thumbnails)),vo(Xh,h(h({},tw.annotations),o.annotations)),vo(Us,h(h({},tw.search),o.search)),vo(Gl,h(h({},tw.selection),o.selection)),vo(fm,h(h({},tw.bookmarks),o.bookmarks)),vo(Lg,h(h({},tw.attachments),o.attachments)),vo(Om,h(h({},tw.capture),o.capture)),vo(Tg,h(h({},tw.redaction),o.redaction)),vo(om,h(h({},tw.print),o.print)),vo(wm,h(h({},tw.export),o.export)),vo(um,h(h({},tw.fullscreen),o.fullscreen)),vo(Zm,h(h({},tw.history),o.history)),vo(lh,h(h({},tw.interactionManager),o.interactionManager))]},function(e){var t=e.pluginsReady,n=e.activeDocumentId;return F(H,null,t?F(H,null,n?F(pa,{documentId:n,components:l,renderers:c,className:"relative flex h-full w-full select-none flex-col"},F(nw,{documentId:n,tabBarVisibility:o.tabBar}),F(Zb,{documentId:n}),F(wy,{documentId:n})):F(Gb,null)):F("div",{className:"flex h-full items-center justify-center"},F(vy,{size:"lg",text:"Initializing plugins..."})))}))}var rw="undefined"!=typeof HTMLElement?HTMLElement:r(function e(){i(this,e)}),aw=function(){function e(){var t;return i(this,e),s(t=o(this,e),"_resolveRegistry",null),s(t,"themeStyleEl",null),s(t,"systemPreferenceCleanup",null),s(t,"handleRegistryReady",function(e){t._resolveRegistry&&(t._resolveRegistry(e),t._resolveRegistry=null)}),t.root=t.attachShadow({mode:"open"}),t._registryPromise=new Promise(function(e){t._resolveRegistry=e}),t}return c(e,rw),r(e,[{key:"connectedCallback",value:function(){this._config||(this._config={src:this.getAttribute("src")||"/demo.pdf",worker:"false"!==this.getAttribute("worker"),theme:this.parseThemeAttribute()}),this.setupTheme(),this.renderViewer()}},{key:"disconnectedCallback",value:function(){var e;null===(e=this.systemPreferenceCleanup)||void 0===e||e.call(this),this.systemPreferenceCleanup=null,ce(null,this.root)}},{key:"parseThemeAttribute",value:function(){var e=this.getAttribute("theme");if(e)return["light","dark","system"].includes(e)?{preference:e}:void 0}},{key:"config",get:function(){return this._config},set:function(e){this._config=e,e.icons&&hf(e.icons),this.isConnected&&(this.setupTheme(),this.renderViewer())}},{key:"registry",get:function(){return this._registryPromise}},{key:"themePreference",get:function(){var e;return(null===(e=this._config)||void 0===e||null===(e=e.theme)||void 0===e?void 0:e.preference)||"system"}},{key:"activeColorScheme",get:function(){return Hb(this.themePreference)}},{key:"activeTheme",get:function(){return this.resolveActiveTheme()}},{key:"resolveActiveTheme",value:function(){var e,t,n,o=null===(e=this._config)||void 0===e?void 0:e.theme,i=Hb((null==o?void 0:o.preference)||"system"),r="dark"===i?jb:$b,a=null==o?void 0:o[i];return n=r,(t=a)?Ub(n,t):n}},{key:"setupTheme",value:function(){var e,t,n=this;null===(e=this.systemPreferenceCleanup)||void 0===e||e.call(this),this.systemPreferenceCleanup=null,"system"===((null===(t=this._config)||void 0===t||null===(t=t.theme)||void 0===t?void 0:t.preference)||"system")&&(this.systemPreferenceCleanup=function(e){if("undefined"==typeof window)return function(){};var t=window.matchMedia("(prefers-color-scheme: dark)"),n=function(t){return e(t.matches?"dark":"light")};return t.addEventListener("change",n),function(){return t.removeEventListener("change",n)}}(function(e){n.injectTheme(),n.dispatchEvent(new CustomEvent("themechange",{detail:{preference:"system",colorScheme:e,theme:n.activeTheme},bubbles:!0}))})),this.injectTheme()}},{key:"injectTheme",value:function(){var e=Bb(this.resolveActiveTheme()),t=this.root.querySelector("style[data-embedpdf-theme]");t||((t=document.createElement("style")).setAttribute("data-embedpdf-theme",""),this.root.appendChild(t)),this.themeStyleEl=t,this.themeStyleEl.textContent=e,this.setAttribute("data-color-scheme",this.activeColorScheme)}},{key:"setTheme",value:function(e){this._config&&(this._config.theme="string"==typeof e?h(h({},this._config.theme),{},{preference:e}):h(h({},this._config.theme),e),this.setupTheme(),this.dispatchEvent(new CustomEvent("themechange",{detail:{preference:this.themePreference,colorScheme:this.activeColorScheme,theme:this.activeTheme},bubbles:!0})))}},{key:"registerIcon",value:function(e,t){uf(e,t)}},{key:"registerIcons",value:function(e){hf(e)}},{key:"renderViewer",value:function(){this._config&&(ce(F(iw,{config:this._config,onRegistryReady:this.handleRegistryReady}),this.root),this.injectTheme())}}])}(),sw=["type","target"],lw="2.8.0";"undefined"==typeof customElements||customElements.get("embedpdf-container")||customElements.define("embedpdf-container",aw);var cw={version:lw,init:function(e){if("container"===e.type)return function(e){e.type,e.target;var t=m(e,sw),n=document.createElement("embedpdf-container");return n.config=t,e.target.appendChild(n),n}(e)}};export{rh as $,$t as A,Ge as B,ot as C,mt as D,_t as E,Nt as F,Lt as G,At as H,Et as I,sn as J,Yt as K,Nn as L,su as M,gt as N,_g as O,tn as P,pm as Q,We as R,Lm as S,Ct as T,Ma as U,va as V,aw as W,ym as X,lm as Y,Gm as Z,ja as _,nn as a,Sm as a0,tm as a1,Ym as a2,bg as a3,ls as a4,ys as a5,Ai as a6,pi as a7,js as a8,Ml as a9,Ti as aa,ji as ab,bc as ac,ic as ad,Br as ae,ci as af,Wa as ag,es as ah,Ub as ai,jb as aj,cw as ak,Ln as al,$b as am,uf as an,hf as ao,lw as ap,Ot as b,en as c,St as d,jt as e,Wt as f,Bt as g,Ft as h,En as i,Pt as j,Tt as k,Mt as l,on as m,an as n,Ut as o,ln as p,cn as q,Ze as r,zn as s,Ye as t,_n as u,qt as v,rn as w,Kt as x,Zt as y,Ht as z}; diff --git a/src/components/BootstrapBlazor.EmbedPDF/wwwroot/embedpdf.js b/src/components/BootstrapBlazor.EmbedPDF/wwwroot/embedpdf.js index 5f9f82bd..07f7eaaa 100644 --- a/src/components/BootstrapBlazor.EmbedPDF/wwwroot/embedpdf.js +++ b/src/components/BootstrapBlazor.EmbedPDF/wwwroot/embedpdf.js @@ -1 +1 @@ -export{J as AnnotationPlugin,K as AttachmentPlugin,L as BookmarkPlugin,M as CapturePlugin,O as CommandsPlugin,Q as DocumentManagerPlugin,S as EmbedPdfContainer,U as ExportPlugin,V as FullscreenPlugin,W as HistoryPlugin,X as I18nPlugin,Y as InteractionManagerPlugin,Z as PanPlugin,_ as PrintPlugin,$ as RedactionMode,a0 as RedactionPlugin,a1 as RenderPlugin,a2 as RotatePlugin,R as Rotation,a3 as ScrollPlugin,a4 as ScrollStrategy,a5 as SearchPlugin,a6 as SelectionPlugin,a7 as SpreadMode,a8 as SpreadPlugin,a9 as ThumbnailPlugin,aa as TilingPlugin,ab as UIPlugin,ac as ViewportPlugin,ad as ZoomMode,ae as ZoomPlugin,af as createTheme,ag as darkTheme,ah as default,ai as ignore,aj as lightTheme,ak as registerIcon,al as registerIcons,am as version}from"./embedpdf-DX_zb2Zx.js"; +export{M as AnnotationPlugin,O as AttachmentPlugin,Q as BookmarkPlugin,S as CapturePlugin,U as CommandsPlugin,V as DocumentManagerPlugin,W as EmbedPdfContainer,X as ExportPlugin,Y as FullscreenPlugin,Z as HistoryPlugin,_ as I18nPlugin,$ as InteractionManagerPlugin,a0 as PanPlugin,a1 as PrintPlugin,a2 as RedactionMode,a3 as RedactionPlugin,a4 as RenderPlugin,a5 as RotatePlugin,R as Rotation,a6 as ScrollPlugin,a7 as ScrollStrategy,a8 as SearchPlugin,a9 as SelectionPlugin,aa as SpreadMode,ab as SpreadPlugin,ac as ThumbnailPlugin,ad as TilingPlugin,ae as UIPlugin,af as ViewportPlugin,ag as ZoomMode,ah as ZoomPlugin,ai as createTheme,aj as darkTheme,ak as default,al as ignore,am as lightTheme,an as registerIcon,ao as registerIcons,ap as version}from"./embedpdf-xgzA9lZs.js"; diff --git a/src/components/BootstrapBlazor.EmbedPDF/wwwroot/pdfium.wasm b/src/components/BootstrapBlazor.EmbedPDF/wwwroot/pdfium.wasm index 5a82765f..1f5bba3c 100644 Binary files a/src/components/BootstrapBlazor.EmbedPDF/wwwroot/pdfium.wasm and b/src/components/BootstrapBlazor.EmbedPDF/wwwroot/pdfium.wasm differ diff --git a/src/components/BootstrapBlazor.EmbedPDF/wwwroot/worker-engine-CW9-K7eD.js b/src/components/BootstrapBlazor.EmbedPDF/wwwroot/worker-engine-CW9-K7eD.js new file mode 100644 index 00000000..fc335830 --- /dev/null +++ b/src/components/BootstrapBlazor.EmbedPDF/wwwroot/worker-engine-CW9-K7eD.js @@ -0,0 +1 @@ +import{P as n,c as e}from"./browser-BISJ9naB-D71PyCCt.js";import{P as t,N as r,T as o,s as a}from"./embedpdf-xgzA9lZs.js";const i="RemoteExecutor",s="Worker",d=class n{constructor(e,d){this.worker=e,this.pendingRequests=new Map,this.requestCounter=0,this.handleMessage=n=>{const e=n.data;if("ready"===e.type)return this.logger.debug(i,s,"Worker is ready"),void this.readyTask.resolve(!0);const r=this.pendingRequests.get(e.id);if(r)switch(e.type){case"result":this.logger.debug(i,s,`Received result for ${e.id}`),r.resolve(e.data),this.pendingRequests.delete(e.id);break;case"error":this.logger.debug(i,s,`Received error for ${e.id}:`,e.error),e.error?r.fail(e.error):r.reject({code:t.Unknown,message:"Unknown error"}),this.pendingRequests.delete(e.id);break;case"progress":this.logger.debug(i,s,`Received progress for ${e.id}`),r.progress(e.progress)}else this.logger.warn(i,s,`Received response for unknown request: ${e.id}`)},this.logger=d.logger??new r,this.worker.addEventListener("message",this.handleMessage),this.readyTask=new o,this.pendingRequests.set(n.READY_TASK_ID,this.readyTask),this.worker.postMessage({id:n.READY_TASK_ID,type:"wasmInit",wasmUrl:d.wasmUrl,logger:d.logger?a(d.logger):void 0,fontFallback:d.fontFallback}),this.logger.debug(i,s,"RemoteExecutor created")}generateId(){return`req-${Date.now()}-${this.requestCounter++}`}send(n,e){const r=this.generateId(),a=new o,d={id:r,type:"execute",method:n,args:e};return this.readyTask.wait(()=>{this.pendingRequests.set(r,a),this.logger.debug(i,s,`Sending ${n} request:`,r),this.worker.postMessage(d)},e=>{this.logger.error(i,s,`Worker init failed, rejecting ${n}:`,e),a.reject({code:t.Initialization,message:"Worker initialization failed"})}),a}destroy(){this.worker.removeEventListener("message",this.handleMessage),this.pendingRequests.forEach((e,t)=>{t!==n.READY_TASK_ID&&(e.abort("Worker destroyed"),this.logger.debug(i,s,`Aborted pending request: ${t}`))}),this.pendingRequests.clear(),this.worker.terminate(),this.logger.debug(i,s,"RemoteExecutor destroyed")}openDocumentBuffer(n,e){return this.send("openDocumentBuffer",[n,e])}getMetadata(n){return this.send("getMetadata",[n])}setMetadata(n,e){return this.send("setMetadata",[n,e])}getDocPermissions(n){return this.send("getDocPermissions",[n])}getDocUserPermissions(n){return this.send("getDocUserPermissions",[n])}getSignatures(n){return this.send("getSignatures",[n])}getBookmarks(n){return this.send("getBookmarks",[n])}setBookmarks(n,e){return this.send("setBookmarks",[n,e])}deleteBookmarks(n){return this.send("deleteBookmarks",[n])}renderPageRaw(n,e,t){return this.send("renderPageRaw",[n,e,t])}renderPageRect(n,e,t,r){return this.send("renderPageRect",[n,e,t,r])}renderThumbnailRaw(n,e,t){return this.send("renderThumbnailRaw",[n,e,t])}renderPageAnnotationRaw(n,e,t,r){return this.send("renderPageAnnotationRaw",[n,e,t,r])}renderPageAnnotationsRaw(n,e,t){return this.send("renderPageAnnotationsRaw",[n,e,t])}getPageAnnotationsRaw(n,e){return this.send("getPageAnnotationsRaw",[n,e])}getPageAnnotations(n,e){return this.send("getPageAnnotations",[n,e])}createPageAnnotation(n,e,t,r){return this.send("createPageAnnotation",[n,e,t,r])}updatePageAnnotation(n,e,t,r){return this.send("updatePageAnnotation",[n,e,t,r])}removePageAnnotation(n,e,t){return this.send("removePageAnnotation",[n,e,t])}getPageTextRects(n,e){return this.send("getPageTextRects",[n,e])}searchInPage(n,e,t,r){return this.send("searchInPage",[n,e,t,r])}getAnnotationsBatch(n,e){return this.send("getAnnotationsBatch",[n,e])}searchBatch(n,e,t,r){return this.send("searchBatch",[n,e,t,r])}getAttachments(n){return this.send("getAttachments",[n])}addAttachment(n,e){return this.send("addAttachment",[n,e])}removeAttachment(n,e){return this.send("removeAttachment",[n,e])}readAttachmentContent(n,e){return this.send("readAttachmentContent",[n,e])}setFormFieldValue(n,e,t,r){return this.send("setFormFieldValue",[n,e,t,r])}flattenPage(n,e,t){return this.send("flattenPage",[n,e,t])}extractPages(n,e){return this.send("extractPages",[n,e])}extractText(n,e){return this.send("extractText",[n,e])}redactTextInRects(n,e,t,r){return this.send("redactTextInRects",[n,e,t,r])}applyRedaction(n,e,t){return this.send("applyRedaction",[n,e,t])}applyAllRedactions(n,e){return this.send("applyAllRedactions",[n,e])}flattenAnnotation(n,e,t){return this.send("flattenAnnotation",[n,e,t])}getTextSlices(n,e){return this.send("getTextSlices",[n,e])}getPageGlyphs(n,e){return this.send("getPageGlyphs",[n,e])}getPageGeometry(n,e){return this.send("getPageGeometry",[n,e])}getPageTextRuns(n,e){return this.send("getPageTextRuns",[n,e])}merge(n){return this.send("merge",[n])}mergePages(n){return this.send("mergePages",[n])}preparePrintDocument(n,e){return this.send("preparePrintDocument",[n,e])}saveAsCopy(n){return this.send("saveAsCopy",[n])}closeDocument(n){return this.send("closeDocument",[n])}closeAllDocuments(){return this.send("closeAllDocuments",[])}setDocumentEncryption(n,e,t,r){return this.send("setDocumentEncryption",[n,e,t,r])}removeEncryption(n){return this.send("removeEncryption",[n])}unlockOwnerPermissions(n,e){return this.send("unlockOwnerPermissions",[n,e])}isEncrypted(n){return this.send("isEncrypted",[n])}isOwnerUnlocked(n){return this.send("isOwnerUnlocked",[n])}};d.READY_TASK_ID="0";let l=d;const u="ImageEncoderPool",c="Encoder";class p{constructor(n=2,e,t){this.poolSize=n,this.workerUrl=e,this.workers=[],this.pendingTasks=new Map,this.nextWorkerId=0,this.requestCounter=0,this.logger=t??new r,this.initialize()}initialize(){this.logger.debug(u,c,`Creating worker pool with ${this.poolSize} workers`);for(let n=0;n{const a=this.getNextWorker();if(!a)return void o(new Error("No workers available in the pool"));const i=`encode-${Date.now()}-${this.requestCounter++}`;this.pendingTasks.set(i,{resolve:r,reject:o});const s={id:i,type:"encode",data:{imageData:{data:n.data,width:n.width,height:n.height},imageType:e,quality:t}};this.logger.debug(u,c,`Sending encoding request ${i} (${n.width}x${n.height})`),a.postMessage(s,[n.data.buffer])})}destroy(){this.logger.debug(u,c,"Destroying worker pool"),this.pendingTasks.forEach((n,e)=>{n.reject(new Error("Worker pool destroyed")),this.logger.debug(u,c,`Rejected pending task: ${e}`)}),this.pendingTasks.clear(),this.workers.forEach((n,e)=>{n.terminate(),this.logger.debug(u,c,`Worker ${e} terminated`)}),this.workers=[]}get activeWorkers(){return this.workers.length}get pendingTasksCount(){return this.pendingTasks.size}}function m(t,r){const o=r instanceof Object&&"debug"in r?{logger:r}:r||{},{logger:a,encoderPoolSize:i,fontFallback:s}=o,d=new Worker(URL.createObjectURL(new Blob(['var Rotation = /* @__PURE__ */ ((Rotation2) => {\n Rotation2[Rotation2["Degree0"] = 0] = "Degree0";\n Rotation2[Rotation2["Degree90"] = 1] = "Degree90";\n Rotation2[Rotation2["Degree180"] = 2] = "Degree180";\n Rotation2[Rotation2["Degree270"] = 3] = "Degree270";\n return Rotation2;\n})(Rotation || {});\nfunction toIntPos(p) {\n return { x: Math.floor(p.x), y: Math.floor(p.y) };\n}\nfunction toIntSize(s) {\n return { width: Math.ceil(s.width), height: Math.ceil(s.height) };\n}\nfunction toIntRect(r) {\n return {\n origin: toIntPos(r.origin),\n size: toIntSize(r.size)\n };\n}\nfunction swap(size) {\n const { width, height } = size;\n return {\n width: height,\n height: width\n };\n}\nfunction quadToRect(q) {\n const xs = [q.p1.x, q.p2.x, q.p3.x, q.p4.x];\n const ys = [q.p1.y, q.p2.y, q.p3.y, q.p4.y];\n return {\n origin: { x: Math.min(...xs), y: Math.min(...ys) },\n size: {\n width: Math.max(...xs) - Math.min(...xs),\n height: Math.max(...ys) - Math.min(...ys)\n }\n };\n}\nfunction rectToQuad(r) {\n return {\n p1: { x: r.origin.x, y: r.origin.y },\n p2: { x: r.origin.x + r.size.width, y: r.origin.y },\n p3: { x: r.origin.x + r.size.width, y: r.origin.y + r.size.height },\n p4: { x: r.origin.x, y: r.origin.y + r.size.height }\n };\n}\nfunction rotateRect(containerSize, rect, rotation) {\n let x = rect.origin.x;\n let y = rect.origin.y;\n let size = rect.size;\n switch (rotation) {\n case 0:\n break;\n case 1:\n x = containerSize.height - rect.origin.y - rect.size.height;\n y = rect.origin.x;\n size = swap(rect.size);\n break;\n case 2:\n x = containerSize.width - rect.origin.x - rect.size.width;\n y = containerSize.height - rect.origin.y - rect.size.height;\n break;\n case 3:\n x = rect.origin.y;\n y = containerSize.width - rect.origin.x - rect.size.width;\n size = swap(rect.size);\n break;\n }\n return {\n origin: {\n x,\n y\n },\n size: {\n width: size.width,\n height: size.height\n }\n };\n}\nfunction scaleRect(rect, scaleFactor) {\n return {\n origin: {\n x: rect.origin.x * scaleFactor,\n y: rect.origin.y * scaleFactor\n },\n size: {\n width: rect.size.width * scaleFactor,\n height: rect.size.height * scaleFactor\n }\n };\n}\nfunction transformRect(containerSize, rect, rotation, scaleFactor) {\n return scaleRect(rotateRect(containerSize, rect, rotation), scaleFactor);\n}\nfunction buildUserToDeviceMatrix(rect, rotation, outW, outH) {\n const L = rect.origin.x;\n const B = rect.origin.y;\n const W = rect.size.width;\n const H = rect.size.height;\n const sx0 = outW / W;\n const sy0 = outH / H;\n const sx90 = outW / H;\n const sy90 = outH / W;\n switch (rotation) {\n case 0:\n return { a: sx0, b: 0, c: 0, d: sy0, e: -sx0 * L, f: -sy0 * B };\n case 3:\n return { a: 0, b: -sy90, c: sx90, d: 0, e: -sx90 * B, f: sy90 * (L + W) };\n case 2:\n return { a: -sx0, b: 0, c: 0, d: -sy0, e: sx0 * (L + W), f: sy0 * (B + H) };\n case 1:\n return { a: 0, b: sy90, c: -sx90, d: 0, e: sx90 * (B + H), f: -sy90 * L };\n }\n}\nclass NoopLogger {\n /** {@inheritDoc Logger.isEnabled} */\n isEnabled() {\n return false;\n }\n /** {@inheritDoc Logger.debug} */\n debug() {\n }\n /** {@inheritDoc Logger.info} */\n info() {\n }\n /** {@inheritDoc Logger.warn} */\n warn() {\n }\n /** {@inheritDoc Logger.error} */\n error() {\n }\n /** {@inheritDoc Logger.perf} */\n perf() {\n }\n}\nclass ConsoleLogger {\n /** {@inheritDoc Logger.isEnabled} */\n isEnabled() {\n return true;\n }\n /** {@inheritDoc Logger.debug} */\n debug(source, category, ...args) {\n console.debug(`${source}.${category}`, ...args);\n }\n /** {@inheritDoc Logger.info} */\n info(source, category, ...args) {\n console.info(`${source}.${category}`, ...args);\n }\n /** {@inheritDoc Logger.warn} */\n warn(source, category, ...args) {\n console.warn(`${source}.${category}`, ...args);\n }\n /** {@inheritDoc Logger.error} */\n error(source, category, ...args) {\n console.error(`${source}.${category}`, ...args);\n }\n /** {@inheritDoc Logger.perf} */\n perf(source, category, event, phase, ...args) {\n console.info(`${source}.${category}.${event}.${phase}`, ...args);\n }\n}\nclass LevelLogger {\n /**\n * create new LevelLogger\n * @param logger - the original logger\n * @param level - log level that used for filtering, all logs lower than this level will be filtered out\n */\n constructor(logger, level) {\n this.logger = logger;\n this.level = level;\n }\n /** {@inheritDoc Logger.isEnabled} */\n isEnabled(level) {\n const levelMap = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3\n /* Error */\n };\n return this.level <= levelMap[level];\n }\n /** {@inheritDoc Logger.debug} */\n debug(source, category, ...args) {\n if (this.level <= 0) {\n this.logger.debug(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.info} */\n info(source, category, ...args) {\n if (this.level <= 1) {\n this.logger.info(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.warn} */\n warn(source, category, ...args) {\n if (this.level <= 2) {\n this.logger.warn(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.error} */\n error(source, category, ...args) {\n if (this.level <= 3) {\n this.logger.error(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.perf} */\n perf(source, category, event, phase, ...args) {\n this.logger.perf(source, category, event, phase, ...args);\n }\n}\nclass PerfLogger {\n /**\n * create new PerfLogger\n */\n constructor() {\n this.marks = /* @__PURE__ */ new Map();\n }\n /** {@inheritDoc Logger.isEnabled} */\n isEnabled() {\n return false;\n }\n /** {@inheritDoc Logger.debug} */\n debug(source, category, ...args) {\n }\n /** {@inheritDoc Logger.info} */\n info(source, category, ...args) {\n }\n /** {@inheritDoc Logger.warn} */\n warn(source, category, ...args) {\n }\n /** {@inheritDoc Logger.error} */\n error(source, category, ...args) {\n }\n /** {@inheritDoc Logger.perf} */\n perf(source, category, event, phase, identifier, ...args) {\n const markName = `${source}.${category}.${event}.${phase}.${identifier}`;\n switch (phase) {\n case "Begin":\n globalThis.performance.mark(markName, { detail: args });\n this.marks.set(`${source}.${category}.${event}.${identifier}`, Date.now());\n break;\n case "End":\n globalThis.performance.mark(markName, { detail: args });\n const measureName = `${source}.${category}.${event}.Measure.${identifier}`;\n const beginMark = `${source}.${category}.${event}.Begin.${identifier}`;\n globalThis.performance.measure(measureName, beginMark, markName);\n const startTime = this.marks.get(`${source}.${category}.${event}.${identifier}`);\n if (startTime) {\n const duration = Date.now() - startTime;\n console.info(`⏱️ ${source}.${category}.${event}.${identifier}: ${duration}ms`);\n this.marks.delete(`${source}.${category}.${event}.${identifier}`);\n }\n break;\n }\n }\n}\nclass AllLogger {\n /**\n * create new PerfLogger\n */\n constructor(loggers) {\n this.loggers = loggers;\n }\n /** {@inheritDoc Logger.isEnabled} */\n isEnabled(level) {\n return this.loggers.some((logger) => logger.isEnabled(level));\n }\n /** {@inheritDoc Logger.debug} */\n debug(source, category, ...args) {\n for (const logger of this.loggers) {\n logger.debug(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.info} */\n info(source, category, ...args) {\n for (const logger of this.loggers) {\n logger.info(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.warn} */\n warn(source, category, ...args) {\n for (const logger of this.loggers) {\n logger.warn(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.error} */\n error(source, category, ...args) {\n for (const logger of this.loggers) {\n logger.error(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.perf} */\n perf(source, category, event, phase, ...args) {\n for (const logger of this.loggers) {\n logger.perf(source, category, event, phase, ...args);\n }\n }\n}\nclass TaskAbortedError extends Error {\n constructor(reason) {\n super(`Task aborted: ${JSON.stringify(reason)}`);\n this.name = "TaskAbortedError";\n this.reason = reason;\n }\n}\nclass TaskRejectedError extends Error {\n constructor(reason) {\n super(`Task rejected: ${JSON.stringify(reason)}`);\n this.name = "TaskRejectedError";\n this.reason = reason;\n }\n}\nclass Task {\n constructor() {\n this.state = {\n stage: 0\n /* Pending */\n };\n this.resolvedCallbacks = [];\n this.rejectedCallbacks = [];\n this._promise = null;\n this.progressCbs = [];\n }\n /**\n * Convert task to promise\n * @returns promise that will be resolved when task is settled\n */\n toPromise() {\n if (!this._promise) {\n this._promise = new Promise((resolve, reject) => {\n this.wait(\n (result) => resolve(result),\n (error) => {\n if (error.type === "abort") {\n reject(new TaskAbortedError(error.reason));\n } else {\n reject(new TaskRejectedError(error.reason));\n }\n }\n );\n });\n }\n return this._promise;\n }\n /**\n * wait for task to be settled\n * @param resolvedCallback - callback for resolved value\n * @param rejectedCallback - callback for rejected value\n */\n wait(resolvedCallback, rejectedCallback) {\n switch (this.state.stage) {\n case 0:\n this.resolvedCallbacks.push(resolvedCallback);\n this.rejectedCallbacks.push(rejectedCallback);\n break;\n case 1:\n resolvedCallback(this.state.result);\n break;\n case 2:\n rejectedCallback({\n type: "reject",\n reason: this.state.reason\n });\n break;\n case 3:\n rejectedCallback({\n type: "abort",\n reason: this.state.reason\n });\n break;\n }\n }\n /**\n * resolve task with specific result\n * @param result - result value\n */\n resolve(result) {\n if (this.state.stage === 0) {\n this.state = {\n stage: 1,\n result\n };\n for (const resolvedCallback of this.resolvedCallbacks) {\n try {\n resolvedCallback(result);\n } catch (e) {\n }\n }\n this.resolvedCallbacks = [];\n this.rejectedCallbacks = [];\n }\n }\n /**\n * reject task with specific reason\n * @param reason - abort reason\n *\n */\n reject(reason) {\n if (this.state.stage === 0) {\n this.state = {\n stage: 2,\n reason\n };\n for (const rejectedCallback of this.rejectedCallbacks) {\n try {\n rejectedCallback({\n type: "reject",\n reason\n });\n } catch (e) {\n }\n }\n this.resolvedCallbacks = [];\n this.rejectedCallbacks = [];\n }\n }\n /**\n * abort task with specific reason\n * @param reason - abort reason\n */\n abort(reason) {\n if (this.state.stage === 0) {\n this.state = {\n stage: 3,\n reason\n };\n for (const rejectedCallback of this.rejectedCallbacks) {\n try {\n rejectedCallback({\n type: "abort",\n reason\n });\n } catch (e) {\n }\n }\n this.resolvedCallbacks = [];\n this.rejectedCallbacks = [];\n }\n }\n /**\n * fail task with a TaskError from another task\n * This is a convenience method for error propagation between tasks\n * @param error - TaskError from another task\n */\n fail(error) {\n if (error.type === "abort") {\n this.abort(error.reason);\n } else {\n this.reject(error.reason);\n }\n }\n /**\n * add a progress callback\n * @param cb - progress callback\n */\n onProgress(cb) {\n this.progressCbs.push(cb);\n }\n /**\n * call progress callback\n * @param p - progress value\n */\n progress(p) {\n for (const cb of this.progressCbs) cb(p);\n }\n /**\n * Static method to wait for all tasks to resolve\n * Returns a new task that resolves with an array of all results\n * Rejects immediately if any task fails\n *\n * @param tasks - array of tasks to wait for\n * @returns new task that resolves when all input tasks resolve\n * @public\n */\n static all(tasks) {\n const combinedTask = new Task();\n if (tasks.length === 0) {\n combinedTask.resolve([]);\n return combinedTask;\n }\n const results = new Array(tasks.length);\n let resolvedCount = 0;\n let isSettled = false;\n tasks.forEach((task, index) => {\n task.wait(\n (result) => {\n if (isSettled) return;\n results[index] = result;\n resolvedCount++;\n if (resolvedCount === tasks.length) {\n isSettled = true;\n combinedTask.resolve(results);\n }\n },\n (error) => {\n if (isSettled) return;\n isSettled = true;\n if (error.type === "abort") {\n combinedTask.abort(error.reason);\n } else {\n combinedTask.reject(error.reason);\n }\n }\n );\n });\n return combinedTask;\n }\n /**\n * Static method to wait for all tasks to settle (resolve, reject, or abort)\n * Always resolves with an array of settlement results\n *\n * @param tasks - array of tasks to wait for\n * @returns new task that resolves when all input tasks settle\n * @public\n */\n static allSettled(tasks) {\n const combinedTask = new Task();\n if (tasks.length === 0) {\n combinedTask.resolve([]);\n return combinedTask;\n }\n const results = new Array(tasks.length);\n let settledCount = 0;\n tasks.forEach((task, index) => {\n task.wait(\n (result) => {\n results[index] = { status: "resolved", value: result };\n settledCount++;\n if (settledCount === tasks.length) {\n combinedTask.resolve(results);\n }\n },\n (error) => {\n results[index] = {\n status: error.type === "abort" ? "aborted" : "rejected",\n reason: error.reason\n };\n settledCount++;\n if (settledCount === tasks.length) {\n combinedTask.resolve(results);\n }\n }\n );\n });\n return combinedTask;\n }\n /**\n * Static method that resolves/rejects with the first task that settles\n *\n * @param tasks - array of tasks to race\n * @returns new task that settles with the first input task that settles\n * @public\n */\n static race(tasks) {\n const combinedTask = new Task();\n if (tasks.length === 0) {\n combinedTask.reject("No tasks provided");\n return combinedTask;\n }\n let isSettled = false;\n tasks.forEach((task) => {\n task.wait(\n (result) => {\n if (isSettled) return;\n isSettled = true;\n combinedTask.resolve(result);\n },\n (error) => {\n if (isSettled) return;\n isSettled = true;\n if (error.type === "abort") {\n combinedTask.abort(error.reason);\n } else {\n combinedTask.reject(error.reason);\n }\n }\n );\n });\n return combinedTask;\n }\n /**\n * Utility to track progress of multiple tasks\n *\n * @param tasks - array of tasks to track\n * @param onProgress - callback called when any task completes\n * @returns new task that resolves when all input tasks resolve\n * @public\n */\n static withProgress(tasks, onProgress) {\n const combinedTask = Task.all(tasks);\n if (onProgress) {\n let completedCount = 0;\n tasks.forEach((task) => {\n task.wait(\n () => {\n completedCount++;\n onProgress(completedCount, tasks.length);\n },\n () => {\n completedCount++;\n onProgress(completedCount, tasks.length);\n }\n );\n });\n }\n return combinedTask;\n }\n}\nconst PdfSoftHyphenMarker = "­";\nconst PdfZeroWidthSpace = "​";\nconst PdfWordJoiner = "⁠";\nconst PdfBomOrZwnbsp = "\\uFEFF";\nconst PdfNonCharacterFFFE = "￾";\nconst PdfNonCharacterFFFF = "￿";\nconst PdfUnwantedTextMarkers = Object.freeze([\n PdfSoftHyphenMarker,\n PdfZeroWidthSpace,\n PdfWordJoiner,\n PdfBomOrZwnbsp,\n PdfNonCharacterFFFE,\n PdfNonCharacterFFFF\n]);\nconst PdfUnwantedTextRegex = new RegExp(`[${PdfUnwantedTextMarkers.join("")}]`, "g");\nfunction stripPdfUnwantedMarkers(text) {\n return text.replace(PdfUnwantedTextRegex, "");\n}\nvar PdfZoomMode = /* @__PURE__ */ ((PdfZoomMode2) => {\n PdfZoomMode2[PdfZoomMode2["Unknown"] = 0] = "Unknown";\n PdfZoomMode2[PdfZoomMode2["XYZ"] = 1] = "XYZ";\n PdfZoomMode2[PdfZoomMode2["FitPage"] = 2] = "FitPage";\n PdfZoomMode2[PdfZoomMode2["FitHorizontal"] = 3] = "FitHorizontal";\n PdfZoomMode2[PdfZoomMode2["FitVertical"] = 4] = "FitVertical";\n PdfZoomMode2[PdfZoomMode2["FitRectangle"] = 5] = "FitRectangle";\n PdfZoomMode2[PdfZoomMode2["FitBoundingBox"] = 6] = "FitBoundingBox";\n PdfZoomMode2[PdfZoomMode2["FitBoundingBoxHorizontal"] = 7] = "FitBoundingBoxHorizontal";\n PdfZoomMode2[PdfZoomMode2["FitBoundingBoxVertical"] = 8] = "FitBoundingBoxVertical";\n return PdfZoomMode2;\n})(PdfZoomMode || {});\nvar PdfTrappedStatus = /* @__PURE__ */ ((PdfTrappedStatus2) => {\n PdfTrappedStatus2[PdfTrappedStatus2["NotSet"] = 0] = "NotSet";\n PdfTrappedStatus2[PdfTrappedStatus2["True"] = 1] = "True";\n PdfTrappedStatus2[PdfTrappedStatus2["False"] = 2] = "False";\n PdfTrappedStatus2[PdfTrappedStatus2["Unknown"] = 3] = "Unknown";\n return PdfTrappedStatus2;\n})(PdfTrappedStatus || {});\nvar PdfStandardFont = /* @__PURE__ */ ((PdfStandardFont2) => {\n PdfStandardFont2[PdfStandardFont2["Unknown"] = -1] = "Unknown";\n PdfStandardFont2[PdfStandardFont2["Courier"] = 0] = "Courier";\n PdfStandardFont2[PdfStandardFont2["Courier_Bold"] = 1] = "Courier_Bold";\n PdfStandardFont2[PdfStandardFont2["Courier_BoldOblique"] = 2] = "Courier_BoldOblique";\n PdfStandardFont2[PdfStandardFont2["Courier_Oblique"] = 3] = "Courier_Oblique";\n PdfStandardFont2[PdfStandardFont2["Helvetica"] = 4] = "Helvetica";\n PdfStandardFont2[PdfStandardFont2["Helvetica_Bold"] = 5] = "Helvetica_Bold";\n PdfStandardFont2[PdfStandardFont2["Helvetica_BoldOblique"] = 6] = "Helvetica_BoldOblique";\n PdfStandardFont2[PdfStandardFont2["Helvetica_Oblique"] = 7] = "Helvetica_Oblique";\n PdfStandardFont2[PdfStandardFont2["Times_Roman"] = 8] = "Times_Roman";\n PdfStandardFont2[PdfStandardFont2["Times_Bold"] = 9] = "Times_Bold";\n PdfStandardFont2[PdfStandardFont2["Times_BoldItalic"] = 10] = "Times_BoldItalic";\n PdfStandardFont2[PdfStandardFont2["Times_Italic"] = 11] = "Times_Italic";\n PdfStandardFont2[PdfStandardFont2["Symbol"] = 12] = "Symbol";\n PdfStandardFont2[PdfStandardFont2["ZapfDingbats"] = 13] = "ZapfDingbats";\n return PdfStandardFont2;\n})(PdfStandardFont || {});\nvar PdfTextAlignment = /* @__PURE__ */ ((PdfTextAlignment2) => {\n PdfTextAlignment2[PdfTextAlignment2["Left"] = 0] = "Left";\n PdfTextAlignment2[PdfTextAlignment2["Center"] = 1] = "Center";\n PdfTextAlignment2[PdfTextAlignment2["Right"] = 2] = "Right";\n return PdfTextAlignment2;\n})(PdfTextAlignment || {});\nvar PdfBlendMode = /* @__PURE__ */ ((PdfBlendMode2) => {\n PdfBlendMode2[PdfBlendMode2["Normal"] = 0] = "Normal";\n PdfBlendMode2[PdfBlendMode2["Multiply"] = 1] = "Multiply";\n PdfBlendMode2[PdfBlendMode2["Screen"] = 2] = "Screen";\n PdfBlendMode2[PdfBlendMode2["Overlay"] = 3] = "Overlay";\n PdfBlendMode2[PdfBlendMode2["Darken"] = 4] = "Darken";\n PdfBlendMode2[PdfBlendMode2["Lighten"] = 5] = "Lighten";\n PdfBlendMode2[PdfBlendMode2["ColorDodge"] = 6] = "ColorDodge";\n PdfBlendMode2[PdfBlendMode2["ColorBurn"] = 7] = "ColorBurn";\n PdfBlendMode2[PdfBlendMode2["HardLight"] = 8] = "HardLight";\n PdfBlendMode2[PdfBlendMode2["SoftLight"] = 9] = "SoftLight";\n PdfBlendMode2[PdfBlendMode2["Difference"] = 10] = "Difference";\n PdfBlendMode2[PdfBlendMode2["Exclusion"] = 11] = "Exclusion";\n PdfBlendMode2[PdfBlendMode2["Hue"] = 12] = "Hue";\n PdfBlendMode2[PdfBlendMode2["Saturation"] = 13] = "Saturation";\n PdfBlendMode2[PdfBlendMode2["Color"] = 14] = "Color";\n PdfBlendMode2[PdfBlendMode2["Luminosity"] = 15] = "Luminosity";\n return PdfBlendMode2;\n})(PdfBlendMode || {});\nvar PdfStampFit = /* @__PURE__ */ ((PdfStampFit2) => {\n PdfStampFit2[PdfStampFit2["Contain"] = 0] = "Contain";\n PdfStampFit2[PdfStampFit2["Cover"] = 1] = "Cover";\n PdfStampFit2[PdfStampFit2["Stretch"] = 2] = "Stretch";\n return PdfStampFit2;\n})(PdfStampFit || {});\nvar PdfActionType = /* @__PURE__ */ ((PdfActionType2) => {\n PdfActionType2[PdfActionType2["Unsupported"] = 0] = "Unsupported";\n PdfActionType2[PdfActionType2["Goto"] = 1] = "Goto";\n PdfActionType2[PdfActionType2["RemoteGoto"] = 2] = "RemoteGoto";\n PdfActionType2[PdfActionType2["URI"] = 3] = "URI";\n PdfActionType2[PdfActionType2["LaunchAppOrOpenFile"] = 4] = "LaunchAppOrOpenFile";\n return PdfActionType2;\n})(PdfActionType || {});\nconst AP_MODE_NORMAL = 1;\nconst AP_MODE_ROLLOVER = 2;\nconst AP_MODE_DOWN = 4;\nvar PdfAnnotationSubtype = /* @__PURE__ */ ((PdfAnnotationSubtype2) => {\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["UNKNOWN"] = 0] = "UNKNOWN";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["TEXT"] = 1] = "TEXT";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["LINK"] = 2] = "LINK";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["FREETEXT"] = 3] = "FREETEXT";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["LINE"] = 4] = "LINE";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["SQUARE"] = 5] = "SQUARE";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["CIRCLE"] = 6] = "CIRCLE";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["POLYGON"] = 7] = "POLYGON";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["POLYLINE"] = 8] = "POLYLINE";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["HIGHLIGHT"] = 9] = "HIGHLIGHT";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["UNDERLINE"] = 10] = "UNDERLINE";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["SQUIGGLY"] = 11] = "SQUIGGLY";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["STRIKEOUT"] = 12] = "STRIKEOUT";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["STAMP"] = 13] = "STAMP";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["CARET"] = 14] = "CARET";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["INK"] = 15] = "INK";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["POPUP"] = 16] = "POPUP";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["FILEATTACHMENT"] = 17] = "FILEATTACHMENT";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["SOUND"] = 18] = "SOUND";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["MOVIE"] = 19] = "MOVIE";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["WIDGET"] = 20] = "WIDGET";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["SCREEN"] = 21] = "SCREEN";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["PRINTERMARK"] = 22] = "PRINTERMARK";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["TRAPNET"] = 23] = "TRAPNET";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["WATERMARK"] = 24] = "WATERMARK";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["THREED"] = 25] = "THREED";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["RICHMEDIA"] = 26] = "RICHMEDIA";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["XFAWIDGET"] = 27] = "XFAWIDGET";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["REDACT"] = 28] = "REDACT";\n return PdfAnnotationSubtype2;\n})(PdfAnnotationSubtype || {});\nvar AppearanceMode = /* @__PURE__ */ ((AppearanceMode2) => {\n AppearanceMode2[AppearanceMode2["Normal"] = 0] = "Normal";\n AppearanceMode2[AppearanceMode2["Rollover"] = 1] = "Rollover";\n AppearanceMode2[AppearanceMode2["Down"] = 2] = "Down";\n return AppearanceMode2;\n})(AppearanceMode || {});\nvar PdfAnnotationIcon = /* @__PURE__ */ ((PdfAnnotationIcon2) => {\n PdfAnnotationIcon2[PdfAnnotationIcon2["Unknown"] = -1] = "Unknown";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Comment"] = 0] = "Comment";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Key"] = 1] = "Key";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Note"] = 2] = "Note";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Help"] = 3] = "Help";\n PdfAnnotationIcon2[PdfAnnotationIcon2["NewParagraph"] = 4] = "NewParagraph";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Paragraph"] = 5] = "Paragraph";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Insert"] = 6] = "Insert";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Graph"] = 7] = "Graph";\n PdfAnnotationIcon2[PdfAnnotationIcon2["PushPin"] = 8] = "PushPin";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Paperclip"] = 9] = "Paperclip";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Tag"] = 10] = "Tag";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Speaker"] = 11] = "Speaker";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Mic"] = 12] = "Mic";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Approved"] = 13] = "Approved";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Experimental"] = 14] = "Experimental";\n PdfAnnotationIcon2[PdfAnnotationIcon2["NotApproved"] = 15] = "NotApproved";\n PdfAnnotationIcon2[PdfAnnotationIcon2["AsIs"] = 16] = "AsIs";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Expired"] = 17] = "Expired";\n PdfAnnotationIcon2[PdfAnnotationIcon2["NotForPublicRelease"] = 18] = "NotForPublicRelease";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Confidential"] = 19] = "Confidential";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Final"] = 20] = "Final";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Sold"] = 21] = "Sold";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Departmental"] = 22] = "Departmental";\n PdfAnnotationIcon2[PdfAnnotationIcon2["ForComment"] = 23] = "ForComment";\n PdfAnnotationIcon2[PdfAnnotationIcon2["TopSecret"] = 24] = "TopSecret";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Draft"] = 25] = "Draft";\n PdfAnnotationIcon2[PdfAnnotationIcon2["ForPublicRelease"] = 26] = "ForPublicRelease";\n return PdfAnnotationIcon2;\n})(PdfAnnotationIcon || {});\nvar PdfAnnotationLineEnding = /* @__PURE__ */ ((PdfAnnotationLineEnding2) => {\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["None"] = 0] = "None";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["Square"] = 1] = "Square";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["Circle"] = 2] = "Circle";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["Diamond"] = 3] = "Diamond";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["OpenArrow"] = 4] = "OpenArrow";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["ClosedArrow"] = 5] = "ClosedArrow";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["Butt"] = 6] = "Butt";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["ROpenArrow"] = 7] = "ROpenArrow";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["RClosedArrow"] = 8] = "RClosedArrow";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["Slash"] = 9] = "Slash";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["Unknown"] = 10] = "Unknown";\n return PdfAnnotationLineEnding2;\n})(PdfAnnotationLineEnding || {});\nvar PdfAnnotationReplyType = /* @__PURE__ */ ((PdfAnnotationReplyType2) => {\n PdfAnnotationReplyType2[PdfAnnotationReplyType2["Unknown"] = 0] = "Unknown";\n PdfAnnotationReplyType2[PdfAnnotationReplyType2["Reply"] = 1] = "Reply";\n PdfAnnotationReplyType2[PdfAnnotationReplyType2["Group"] = 2] = "Group";\n return PdfAnnotationReplyType2;\n})(PdfAnnotationReplyType || {});\nvar PDF_FORM_FIELD_TYPE = /* @__PURE__ */ ((PDF_FORM_FIELD_TYPE2) => {\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["UNKNOWN"] = 0] = "UNKNOWN";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["PUSHBUTTON"] = 1] = "PUSHBUTTON";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["CHECKBOX"] = 2] = "CHECKBOX";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["RADIOBUTTON"] = 3] = "RADIOBUTTON";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["COMBOBOX"] = 4] = "COMBOBOX";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["LISTBOX"] = 5] = "LISTBOX";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["TEXTFIELD"] = 6] = "TEXTFIELD";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["SIGNATURE"] = 7] = "SIGNATURE";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA"] = 8] = "XFA";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA_CHECKBOX"] = 9] = "XFA_CHECKBOX";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA_COMBOBOX"] = 10] = "XFA_COMBOBOX";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA_IMAGEFIELD"] = 11] = "XFA_IMAGEFIELD";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA_LISTBOX"] = 12] = "XFA_LISTBOX";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA_PUSHBUTTON"] = 13] = "XFA_PUSHBUTTON";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA_SIGNATURE"] = 14] = "XFA_SIGNATURE";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA_TEXTFIELD"] = 15] = "XFA_TEXTFIELD";\n return PDF_FORM_FIELD_TYPE2;\n})(PDF_FORM_FIELD_TYPE || {});\nvar PdfAnnotationColorType = /* @__PURE__ */ ((PdfAnnotationColorType2) => {\n PdfAnnotationColorType2[PdfAnnotationColorType2["Color"] = 0] = "Color";\n PdfAnnotationColorType2[PdfAnnotationColorType2["InteriorColor"] = 1] = "InteriorColor";\n PdfAnnotationColorType2[PdfAnnotationColorType2["OverlayColor"] = 2] = "OverlayColor";\n return PdfAnnotationColorType2;\n})(PdfAnnotationColorType || {});\nvar PdfAnnotationBorderStyle = /* @__PURE__ */ ((PdfAnnotationBorderStyle2) => {\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["UNKNOWN"] = 0] = "UNKNOWN";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["SOLID"] = 1] = "SOLID";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["DASHED"] = 2] = "DASHED";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["BEVELED"] = 3] = "BEVELED";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["INSET"] = 4] = "INSET";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["UNDERLINE"] = 5] = "UNDERLINE";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["CLOUDY"] = 6] = "CLOUDY";\n return PdfAnnotationBorderStyle2;\n})(PdfAnnotationBorderStyle || {});\nvar PdfPageObjectType = /* @__PURE__ */ ((PdfPageObjectType2) => {\n PdfPageObjectType2[PdfPageObjectType2["UNKNOWN"] = 0] = "UNKNOWN";\n PdfPageObjectType2[PdfPageObjectType2["TEXT"] = 1] = "TEXT";\n PdfPageObjectType2[PdfPageObjectType2["PATH"] = 2] = "PATH";\n PdfPageObjectType2[PdfPageObjectType2["IMAGE"] = 3] = "IMAGE";\n PdfPageObjectType2[PdfPageObjectType2["SHADING"] = 4] = "SHADING";\n PdfPageObjectType2[PdfPageObjectType2["FORM"] = 5] = "FORM";\n return PdfPageObjectType2;\n})(PdfPageObjectType || {});\nconst PdfAnnotationFlagName = Object.freeze({\n [\n 1\n /* INVISIBLE */\n ]: "invisible",\n [\n 2\n /* HIDDEN */\n ]: "hidden",\n [\n 4\n /* PRINT */\n ]: "print",\n [\n 8\n /* NO_ZOOM */\n ]: "noZoom",\n [\n 16\n /* NO_ROTATE */\n ]: "noRotate",\n [\n 32\n /* NO_VIEW */\n ]: "noView",\n [\n 64\n /* READ_ONLY */\n ]: "readOnly",\n [\n 128\n /* LOCKED */\n ]: "locked",\n [\n 256\n /* TOGGLE_NOVIEW */\n ]: "toggleNoView"\n});\nconst PdfAnnotationFlagValue = Object.entries(\n PdfAnnotationFlagName\n).reduce(\n (acc, [bit, name]) => {\n acc[name] = Number(bit);\n return acc;\n },\n {}\n);\nfunction flagsToNames(raw) {\n return Object.keys(PdfAnnotationFlagName).filter((flag) => (raw & flag) !== 0).map((flag) => PdfAnnotationFlagName[flag]);\n}\nfunction namesToFlags(names) {\n return names.reduce(\n (mask, name) => mask | PdfAnnotationFlagValue[name],\n 0\n /* NONE */\n );\n}\nvar FontCharset = /* @__PURE__ */ ((FontCharset2) => {\n FontCharset2[FontCharset2["ANSI"] = 0] = "ANSI";\n FontCharset2[FontCharset2["DEFAULT"] = 1] = "DEFAULT";\n FontCharset2[FontCharset2["SYMBOL"] = 2] = "SYMBOL";\n FontCharset2[FontCharset2["SHIFTJIS"] = 128] = "SHIFTJIS";\n FontCharset2[FontCharset2["HANGEUL"] = 129] = "HANGEUL";\n FontCharset2[FontCharset2["GB2312"] = 134] = "GB2312";\n FontCharset2[FontCharset2["CHINESEBIG5"] = 136] = "CHINESEBIG5";\n FontCharset2[FontCharset2["GREEK"] = 161] = "GREEK";\n FontCharset2[FontCharset2["VIETNAMESE"] = 163] = "VIETNAMESE";\n FontCharset2[FontCharset2["HEBREW"] = 177] = "HEBREW";\n FontCharset2[FontCharset2["ARABIC"] = 178] = "ARABIC";\n FontCharset2[FontCharset2["CYRILLIC"] = 204] = "CYRILLIC";\n FontCharset2[FontCharset2["THAI"] = 222] = "THAI";\n FontCharset2[FontCharset2["EASTERNEUROPEAN"] = 238] = "EASTERNEUROPEAN";\n return FontCharset2;\n})(FontCharset || {});\nvar PdfPageFlattenFlag = /* @__PURE__ */ ((PdfPageFlattenFlag2) => {\n PdfPageFlattenFlag2[PdfPageFlattenFlag2["Display"] = 0] = "Display";\n PdfPageFlattenFlag2[PdfPageFlattenFlag2["Print"] = 1] = "Print";\n return PdfPageFlattenFlag2;\n})(PdfPageFlattenFlag || {});\nvar PdfErrorCode = /* @__PURE__ */ ((PdfErrorCode2) => {\n PdfErrorCode2[PdfErrorCode2["Ok"] = 0] = "Ok";\n PdfErrorCode2[PdfErrorCode2["Unknown"] = 1] = "Unknown";\n PdfErrorCode2[PdfErrorCode2["NotFound"] = 2] = "NotFound";\n PdfErrorCode2[PdfErrorCode2["WrongFormat"] = 3] = "WrongFormat";\n PdfErrorCode2[PdfErrorCode2["Password"] = 4] = "Password";\n PdfErrorCode2[PdfErrorCode2["Security"] = 5] = "Security";\n PdfErrorCode2[PdfErrorCode2["PageError"] = 6] = "PageError";\n PdfErrorCode2[PdfErrorCode2["XFALoad"] = 7] = "XFALoad";\n PdfErrorCode2[PdfErrorCode2["XFALayout"] = 8] = "XFALayout";\n PdfErrorCode2[PdfErrorCode2["Cancelled"] = 9] = "Cancelled";\n PdfErrorCode2[PdfErrorCode2["Initialization"] = 10] = "Initialization";\n PdfErrorCode2[PdfErrorCode2["NotReady"] = 11] = "NotReady";\n PdfErrorCode2[PdfErrorCode2["NotSupport"] = 12] = "NotSupport";\n PdfErrorCode2[PdfErrorCode2["LoadDoc"] = 13] = "LoadDoc";\n PdfErrorCode2[PdfErrorCode2["DocNotOpen"] = 14] = "DocNotOpen";\n PdfErrorCode2[PdfErrorCode2["CantCloseDoc"] = 15] = "CantCloseDoc";\n PdfErrorCode2[PdfErrorCode2["CantCreateNewDoc"] = 16] = "CantCreateNewDoc";\n PdfErrorCode2[PdfErrorCode2["CantImportPages"] = 17] = "CantImportPages";\n PdfErrorCode2[PdfErrorCode2["CantCreateAnnot"] = 18] = "CantCreateAnnot";\n PdfErrorCode2[PdfErrorCode2["CantSetAnnotRect"] = 19] = "CantSetAnnotRect";\n PdfErrorCode2[PdfErrorCode2["CantSetAnnotContent"] = 20] = "CantSetAnnotContent";\n PdfErrorCode2[PdfErrorCode2["CantRemoveInkList"] = 21] = "CantRemoveInkList";\n PdfErrorCode2[PdfErrorCode2["CantAddInkStoke"] = 22] = "CantAddInkStoke";\n PdfErrorCode2[PdfErrorCode2["CantReadAttachmentSize"] = 23] = "CantReadAttachmentSize";\n PdfErrorCode2[PdfErrorCode2["CantReadAttachmentContent"] = 24] = "CantReadAttachmentContent";\n PdfErrorCode2[PdfErrorCode2["CantFocusAnnot"] = 25] = "CantFocusAnnot";\n PdfErrorCode2[PdfErrorCode2["CantSelectText"] = 26] = "CantSelectText";\n PdfErrorCode2[PdfErrorCode2["CantSelectOption"] = 27] = "CantSelectOption";\n PdfErrorCode2[PdfErrorCode2["CantCheckField"] = 28] = "CantCheckField";\n PdfErrorCode2[PdfErrorCode2["CantSetAnnotString"] = 29] = "CantSetAnnotString";\n return PdfErrorCode2;\n})(PdfErrorCode || {});\nclass PdfTaskHelper {\n /**\n * Create a task\n * @returns new task\n */\n static create() {\n return new Task();\n }\n /**\n * Create a task that has been resolved with value\n * @param result - resolved value\n * @returns resolved task\n */\n static resolve(result) {\n const task = new Task();\n task.resolve(result);\n return task;\n }\n /**\n * Create a task that has been rejected with error\n * @param reason - rejected error\n * @returns rejected task\n */\n static reject(reason) {\n const task = new Task();\n task.reject(reason);\n return task;\n }\n /**\n * Create a task that has been aborted with error\n * @param reason - aborted error\n * @returns aborted task\n */\n static abort(reason) {\n const task = new Task();\n task.reject(reason);\n return task;\n }\n}\nfunction pdfColorToWebColor(c) {\n const clamp = (n) => Math.max(0, Math.min(255, n));\n const toHex = (n) => clamp(n).toString(16).padStart(2, "0");\n return `#${toHex(c.red)}${toHex(c.green)}${toHex(c.blue)}`;\n}\nfunction webColorToPdfColor(color) {\n if (/^#?[0-9a-f]{3}$/i.test(color)) {\n color = color.replace(/^#?([0-9a-f])([0-9a-f])([0-9a-f])$/i, "#$1$1$2$2$3$3").toLowerCase();\n }\n const [, r, g, b] = /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(color) ?? (() => {\n throw new Error(`Invalid hex colour: "${color}"`);\n })();\n return {\n red: parseInt(r, 16),\n green: parseInt(g, 16),\n blue: parseInt(b, 16)\n };\n}\nfunction pdfAlphaToWebOpacity(alpha) {\n const clamp = (n) => Math.max(0, Math.min(255, n));\n return clamp(alpha) / 255;\n}\nfunction webOpacityToPdfAlpha(opacity) {\n const clamp = (n, hi = 255) => Math.max(0, Math.min(hi, n));\n return clamp(Math.round(opacity * 255));\n}\nfunction pdfDateToDate(pdf) {\n if (!(pdf == null ? void 0 : pdf.startsWith("D:")) || pdf.length < 16) return;\n const y = +pdf.slice(2, 6);\n const mo = +pdf.slice(6, 8) - 1;\n const d = +pdf.slice(8, 10);\n const H = +pdf.slice(10, 12);\n const M = +pdf.slice(12, 14);\n const S = +pdf.slice(14, 16);\n return new Date(Date.UTC(y, mo, d, H, M, S));\n}\nfunction dateToPdfDate(date = /* @__PURE__ */ new Date()) {\n const z = (n, len = 2) => n.toString().padStart(len, "0");\n const YYYY = date.getUTCFullYear();\n const MM = z(date.getUTCMonth() + 1);\n const DD = z(date.getUTCDate());\n const HH = z(date.getUTCHours());\n const mm = z(date.getUTCMinutes());\n const SS = z(date.getUTCSeconds());\n return `D:${YYYY}${MM}${DD}${HH}${mm}${SS}`;\n}\nconst TEXT_ALIGNMENT_INFOS = Object.freeze([\n { id: PdfTextAlignment.Left, label: "Left", css: "left" },\n { id: PdfTextAlignment.Center, label: "Center", css: "center" },\n { id: PdfTextAlignment.Right, label: "Right", css: "right" }\n]);\nTEXT_ALIGNMENT_INFOS.reduce(\n (m, info) => {\n m[info.id] = info;\n return m;\n },\n {}\n);\nTEXT_ALIGNMENT_INFOS.reduce(\n (m, info) => {\n m[info.css] = info.id;\n return m;\n },\n {}\n);\nTEXT_ALIGNMENT_INFOS.map((info) => ({\n value: info.id,\n label: info.label\n}));\nvar PdfStandardFontFamily = /* @__PURE__ */ ((PdfStandardFontFamily2) => {\n PdfStandardFontFamily2["Courier"] = "Courier";\n PdfStandardFontFamily2["Helvetica"] = "Helvetica";\n PdfStandardFontFamily2["Times"] = "Times";\n PdfStandardFontFamily2["Symbol"] = "Symbol";\n PdfStandardFontFamily2["ZapfDingbats"] = "ZapfDingbats";\n PdfStandardFontFamily2["Unknown"] = "Unknown";\n return PdfStandardFontFamily2;\n})(PdfStandardFontFamily || {});\nPdfStandardFont.Helvetica;\nconst HELVETICA_DESC = {\n id: PdfStandardFont.Helvetica,\n family: "Helvetica",\n bold: false,\n italic: false,\n label: "Helvetica",\n css: "Helvetica, Arial, sans-serif"\n};\nconst STANDARD_FONT_DESCRIPTORS = Object.freeze([\n {\n id: PdfStandardFont.Courier,\n family: "Courier",\n bold: false,\n italic: false,\n label: "Courier",\n css: "Courier, monospace"\n },\n {\n id: PdfStandardFont.Courier_Bold,\n family: "Courier",\n bold: true,\n italic: false,\n label: "Courier Bold",\n css: "Courier, monospace"\n },\n {\n id: PdfStandardFont.Courier_BoldOblique,\n family: "Courier",\n bold: true,\n italic: true,\n label: "Courier Bold Oblique",\n css: "Courier, monospace"\n },\n {\n id: PdfStandardFont.Courier_Oblique,\n family: "Courier",\n bold: false,\n italic: true,\n label: "Courier Oblique",\n css: "Courier, monospace"\n },\n HELVETICA_DESC,\n {\n id: PdfStandardFont.Helvetica_Bold,\n family: "Helvetica",\n bold: true,\n italic: false,\n label: "Helvetica Bold",\n css: "Helvetica, Arial, sans-serif"\n },\n {\n id: PdfStandardFont.Helvetica_BoldOblique,\n family: "Helvetica",\n bold: true,\n italic: true,\n label: "Helvetica Bold Oblique",\n css: "Helvetica, Arial, sans-serif"\n },\n {\n id: PdfStandardFont.Helvetica_Oblique,\n family: "Helvetica",\n bold: false,\n italic: true,\n label: "Helvetica Oblique",\n css: "Helvetica, Arial, sans-serif"\n },\n {\n id: PdfStandardFont.Times_Roman,\n family: "Times",\n bold: false,\n italic: false,\n label: "Times Roman",\n css: \'"Times New Roman", Times, serif\'\n },\n {\n id: PdfStandardFont.Times_Bold,\n family: "Times",\n bold: true,\n italic: false,\n label: "Times Bold",\n css: \'"Times New Roman", Times, serif\'\n },\n {\n id: PdfStandardFont.Times_BoldItalic,\n family: "Times",\n bold: true,\n italic: true,\n label: "Times Bold Italic",\n css: \'"Times New Roman", Times, serif\'\n },\n {\n id: PdfStandardFont.Times_Italic,\n family: "Times",\n bold: false,\n italic: true,\n label: "Times Italic",\n css: \'"Times New Roman", Times, serif\'\n },\n {\n id: PdfStandardFont.Symbol,\n family: "Symbol",\n bold: false,\n italic: false,\n label: "Symbol",\n css: "Symbol, serif"\n },\n {\n id: PdfStandardFont.ZapfDingbats,\n family: "ZapfDingbats",\n bold: false,\n italic: false,\n label: "Zapf Dingbats",\n css: "ZapfDingbats, serif"\n }\n]);\nSTANDARD_FONT_DESCRIPTORS.reduce((m, d) => (m[d.id] = d, m), {});\nconst familyStyleToId = /* @__PURE__ */ new Map();\nfor (const d of STANDARD_FONT_DESCRIPTORS) {\n familyStyleToId.set(`${d.family}_${d.bold}_${d.italic}`, d.id);\n}\nObject.values(PdfStandardFontFamily).filter(\n (f) => f !== "Unknown"\n /* Unknown */\n).map((family) => ({ value: family, label: family }));\n[\n ...new Set(STANDARD_FONT_DESCRIPTORS.map((d) => d.family))\n];\nconst BLEND_MODE_INFOS = Object.freeze([\n { id: PdfBlendMode.Normal, label: "Normal", css: "normal" },\n { id: PdfBlendMode.Multiply, label: "Multiply", css: "multiply" },\n { id: PdfBlendMode.Screen, label: "Screen", css: "screen" },\n { id: PdfBlendMode.Overlay, label: "Overlay", css: "overlay" },\n { id: PdfBlendMode.Darken, label: "Darken", css: "darken" },\n { id: PdfBlendMode.Lighten, label: "Lighten", css: "lighten" },\n { id: PdfBlendMode.ColorDodge, label: "Color Dodge", css: "color-dodge" },\n { id: PdfBlendMode.ColorBurn, label: "Color Burn", css: "color-burn" },\n { id: PdfBlendMode.HardLight, label: "Hard Light", css: "hard-light" },\n { id: PdfBlendMode.SoftLight, label: "Soft Light", css: "soft-light" },\n { id: PdfBlendMode.Difference, label: "Difference", css: "difference" },\n { id: PdfBlendMode.Exclusion, label: "Exclusion", css: "exclusion" },\n { id: PdfBlendMode.Hue, label: "Hue", css: "hue" },\n { id: PdfBlendMode.Saturation, label: "Saturation", css: "saturation" },\n { id: PdfBlendMode.Color, label: "Color", css: "color" },\n { id: PdfBlendMode.Luminosity, label: "Luminosity", css: "luminosity" }\n]);\nBLEND_MODE_INFOS.reduce(\n (m, info) => {\n m[info.id] = info;\n return m;\n },\n {}\n);\nBLEND_MODE_INFOS.reduce(\n (m, info) => {\n m[info.css] = info.id;\n return m;\n },\n {}\n);\nBLEND_MODE_INFOS.map((info) => ({\n value: info.id,\n label: info.label\n}));\nBLEND_MODE_INFOS.map((info) => info.id);\nfunction deserializeLogger(serialized) {\n var _a, _b, _c;\n switch (serialized.type) {\n case "noop":\n return new NoopLogger();\n case "console":\n return new ConsoleLogger();\n case "perf":\n return new PerfLogger();\n case "level":\n if (!((_a = serialized.config) == null ? void 0 : _a.logger) || ((_b = serialized.config) == null ? void 0 : _b.level) === void 0) {\n throw new Error("LevelLogger requires logger and level in config");\n }\n return new LevelLogger(deserializeLogger(serialized.config.logger), serialized.config.level);\n case "all":\n if (!((_c = serialized.config) == null ? void 0 : _c.loggers)) {\n throw new Error("AllLogger requires loggers array in config");\n }\n return new AllLogger(serialized.config.loggers.map(deserializeLogger));\n default:\n return new NoopLogger();\n }\n}\nconst V4_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\nfunction isUuidV4(str) {\n return V4_REGEX.test(str);\n}\nfunction getRandomBytes(len) {\n var _a;\n if (typeof ((_a = globalThis.crypto) == null ? void 0 : _a.getRandomValues) === "function") {\n return globalThis.crypto.getRandomValues(new Uint8Array(len));\n }\n if (typeof require === "function") {\n try {\n const { randomBytes } = require("crypto");\n return randomBytes(len);\n } catch {\n }\n }\n const bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) bytes[i] = Math.floor(Math.random() * 256);\n return bytes;\n}\nfunction uuidV4() {\n var _a;\n if (typeof ((_a = globalThis.crypto) == null ? void 0 : _a.randomUUID) === "function") {\n return globalThis.crypto.randomUUID();\n }\n const bytes = getRandomBytes(16);\n bytes[6] = bytes[6] & 15 | 64;\n bytes[8] = bytes[8] & 63 | 128;\n const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\nvar createPdfium = (() => {\n var _scriptName = import.meta.url;\n return async function(moduleArg = {}) {\n var moduleRtn;\n var Module = moduleArg;\n var readyPromiseResolve, readyPromiseReject;\n var readyPromise = new Promise((resolve, reject) => {\n readyPromiseResolve = resolve;\n readyPromiseReject = reject;\n });\n [\n "_EPDF_GetMetaKeyCount",\n "_EPDF_GetMetaKeyName",\n "_EPDF_GetMetaTrapped",\n "_EPDF_GetPageRotationByIndex",\n "_EPDF_GetPageSizeByIndexNormalized",\n "_EPDF_HasMetaText",\n "_EPDF_IsEncrypted",\n "_EPDF_IsOwnerUnlocked",\n "_EPDF_LoadPageNormalized",\n "_EPDF_PNG_EncodeRGBA",\n "_EPDF_RemoveEncryption",\n "_EPDF_RenderAnnotBitmap",\n "_EPDF_RenderAnnotBitmapUnrotated",\n "_EPDF_SetEncryption",\n "_EPDF_SetMetaText",\n "_EPDF_SetMetaTrapped",\n "_EPDF_UnlockOwnerPermissions",\n "_EPDFAction_CreateGoTo",\n "_EPDFAction_CreateGoToNamed",\n "_EPDFAction_CreateLaunch",\n "_EPDFAction_CreateRemoteGoToByName",\n "_EPDFAction_CreateRemoteGoToDest",\n "_EPDFAction_CreateURI",\n "_EPDFAnnot_ApplyRedaction",\n "_EPDFAnnot_ClearColor",\n "_EPDFAnnot_ClearRectangleDifferences",\n "_EPDFAnnot_Flatten",\n "_EPDFAnnot_GenerateAppearance",\n "_EPDFAnnot_GenerateAppearanceWithBlend",\n "_EPDFAnnot_GetAPMatrix",\n "_EPDFAnnot_GetAvailableAppearanceModes",\n "_EPDFAnnot_GetBlendMode",\n "_EPDFAnnot_GetBorderDashPattern",\n "_EPDFAnnot_GetBorderDashPatternCount",\n "_EPDFAnnot_GetBorderEffect",\n "_EPDFAnnot_GetBorderStyle",\n "_EPDFAnnot_GetColor",\n "_EPDFAnnot_GetDefaultAppearance",\n "_EPDFAnnot_GetExtendedRotation",\n "_EPDFAnnot_GetIcon",\n "_EPDFAnnot_GetIntent",\n "_EPDFAnnot_GetLineEndings",\n "_EPDFAnnot_GetOpacity",\n "_EPDFAnnot_GetOverlayText",\n "_EPDFAnnot_GetOverlayTextRepeat",\n "_EPDFAnnot_GetRect",\n "_EPDFAnnot_GetRectangleDifferences",\n "_EPDFAnnot_GetReplyType",\n "_EPDFAnnot_GetRichContent",\n "_EPDFAnnot_GetRotate",\n "_EPDFAnnot_GetTextAlignment",\n "_EPDFAnnot_GetUnrotatedRect",\n "_EPDFAnnot_GetVerticalAlignment",\n "_EPDFAnnot_HasAppearanceStream",\n "_EPDFAnnot_SetAction",\n "_EPDFAnnot_SetAPMatrix",\n "_EPDFAnnot_SetBorderDashPattern",\n "_EPDFAnnot_SetBorderStyle",\n "_EPDFAnnot_SetColor",\n "_EPDFAnnot_SetDefaultAppearance",\n "_EPDFAnnot_SetExtendedRotation",\n "_EPDFAnnot_SetIcon",\n "_EPDFAnnot_SetIntent",\n "_EPDFAnnot_SetLine",\n "_EPDFAnnot_SetLineEndings",\n "_EPDFAnnot_SetLinkedAnnot",\n "_EPDFAnnot_SetOpacity",\n "_EPDFAnnot_SetOverlayText",\n "_EPDFAnnot_SetOverlayTextRepeat",\n "_EPDFAnnot_SetRectangleDifferences",\n "_EPDFAnnot_SetReplyType",\n "_EPDFAnnot_SetRotate",\n "_EPDFAnnot_SetTextAlignment",\n "_EPDFAnnot_SetUnrotatedRect",\n "_EPDFAnnot_SetVerticalAlignment",\n "_EPDFAnnot_SetVertices",\n "_EPDFAnnot_UpdateAppearanceToRect",\n "_EPDFAttachment_GetDescription",\n "_EPDFAttachment_GetIntegerValue",\n "_EPDFAttachment_SetDescription",\n "_EPDFAttachment_SetSubtype",\n "_EPDFBookmark_AppendChild",\n "_EPDFBookmark_Clear",\n "_EPDFBookmark_ClearTarget",\n "_EPDFBookmark_Create",\n "_EPDFBookmark_Delete",\n "_EPDFBookmark_InsertAfter",\n "_EPDFBookmark_SetAction",\n "_EPDFBookmark_SetDest",\n "_EPDFBookmark_SetTitle",\n "_EPDFCatalog_GetLanguage",\n "_EPDFDest_CreateRemoteView",\n "_EPDFDest_CreateRemoteXYZ",\n "_EPDFDest_CreateView",\n "_EPDFDest_CreateXYZ",\n "_EPDFNamedDest_Remove",\n "_EPDFNamedDest_SetDest",\n "_EPDFPage_ApplyRedactions",\n "_EPDFPage_CreateAnnot",\n "_EPDFPage_GetAnnotByName",\n "_EPDFPage_GetAnnotCountRaw",\n "_EPDFPage_GetAnnotRaw",\n "_EPDFPage_RemoveAnnotByName",\n "_EPDFPage_RemoveAnnotRaw",\n "_EPDFText_RedactInQuads",\n "_EPDFText_RedactInRect",\n "_FORM_CanRedo",\n "_FORM_CanUndo",\n "_FORM_DoDocumentAAction",\n "_FORM_DoDocumentJSAction",\n "_FORM_DoDocumentOpenAction",\n "_FORM_DoPageAAction",\n "_FORM_ForceToKillFocus",\n "_FORM_GetFocusedAnnot",\n "_FORM_GetFocusedText",\n "_FORM_GetSelectedText",\n "_FORM_IsIndexSelected",\n "_FORM_OnAfterLoadPage",\n "_FORM_OnBeforeClosePage",\n "_FORM_OnChar",\n "_FORM_OnFocus",\n "_FORM_OnKeyDown",\n "_FORM_OnKeyUp",\n "_FORM_OnLButtonDoubleClick",\n "_FORM_OnLButtonDown",\n "_FORM_OnLButtonUp",\n "_FORM_OnMouseMove",\n "_FORM_OnMouseWheel",\n "_FORM_OnRButtonDown",\n "_FORM_OnRButtonUp",\n "_FORM_Redo",\n "_FORM_ReplaceAndKeepSelection",\n "_FORM_ReplaceSelection",\n "_FORM_SelectAllText",\n "_FORM_SetFocusedAnnot",\n "_FORM_SetIndexSelected",\n "_FORM_Undo",\n "_FPDF_AddInstalledFont",\n "_FPDF_CloseDocument",\n "_FPDF_ClosePage",\n "_FPDF_CloseXObject",\n "_FPDF_CopyViewerPreferences",\n "_FPDF_CountNamedDests",\n "_FPDF_CreateClipPath",\n "_FPDF_CreateNewDocument",\n "_FPDF_DestroyClipPath",\n "_FPDF_DestroyLibrary",\n "_FPDF_DeviceToPage",\n "_FPDF_DocumentHasValidCrossReferenceTable",\n "_FPDF_FFLDraw",\n "_FPDF_FreeDefaultSystemFontInfo",\n "_FPDF_GetDefaultSystemFontInfo",\n "_FPDF_GetDefaultTTFMap",\n "_FPDF_GetDefaultTTFMapCount",\n "_FPDF_GetDefaultTTFMapEntry",\n "_FPDF_GetDocPermissions",\n "_FPDF_GetDocUserPermissions",\n "_FPDF_GetFileIdentifier",\n "_FPDF_GetFileVersion",\n "_FPDF_GetFormType",\n "_FPDF_GetLastError",\n "_FPDF_GetMetaText",\n "_FPDF_GetNamedDest",\n "_FPDF_GetNamedDestByName",\n "_FPDF_GetPageAAction",\n "_FPDF_GetPageBoundingBox",\n "_FPDF_GetPageCount",\n "_FPDF_GetPageHeight",\n "_FPDF_GetPageHeightF",\n "_FPDF_GetPageLabel",\n "_FPDF_GetPageSizeByIndex",\n "_FPDF_GetPageSizeByIndexF",\n "_FPDF_GetPageWidth",\n "_FPDF_GetPageWidthF",\n "_FPDF_GetSecurityHandlerRevision",\n "_FPDF_GetSignatureCount",\n "_FPDF_GetSignatureObject",\n "_FPDF_GetTrailerEnds",\n "_FPDF_GetXFAPacketContent",\n "_FPDF_GetXFAPacketCount",\n "_FPDF_GetXFAPacketName",\n "_FPDF_ImportNPagesToOne",\n "_FPDF_ImportPages",\n "_FPDF_ImportPagesByIndex",\n "_FPDF_InitLibrary",\n "_FPDF_InitLibraryWithConfig",\n "_FPDF_LoadCustomDocument",\n "_FPDF_LoadDocument",\n "_FPDF_LoadMemDocument",\n "_FPDF_LoadMemDocument64",\n "_FPDF_LoadPage",\n "_FPDF_LoadXFA",\n "_FPDF_MovePages",\n "_FPDF_NewFormObjectFromXObject",\n "_FPDF_NewXObjectFromPage",\n "_FPDF_PageToDevice",\n "_FPDF_RemoveFormFieldHighlight",\n "_FPDF_RenderPage_Close",\n "_FPDF_RenderPage_Continue",\n "_FPDF_RenderPageBitmap",\n "_FPDF_RenderPageBitmap_Start",\n "_FPDF_RenderPageBitmapWithColorScheme_Start",\n "_FPDF_RenderPageBitmapWithMatrix",\n "_FPDF_SaveAsCopy",\n "_FPDF_SaveWithVersion",\n "_FPDF_SetFormFieldHighlightAlpha",\n "_FPDF_SetFormFieldHighlightColor",\n "_FPDF_SetSandBoxPolicy",\n "_FPDF_SetSystemFontInfo",\n "_FPDF_StructElement_Attr_CountChildren",\n "_FPDF_StructElement_Attr_GetBlobValue",\n "_FPDF_StructElement_Attr_GetBooleanValue",\n "_FPDF_StructElement_Attr_GetChildAtIndex",\n "_FPDF_StructElement_Attr_GetCount",\n "_FPDF_StructElement_Attr_GetName",\n "_FPDF_StructElement_Attr_GetNumberValue",\n "_FPDF_StructElement_Attr_GetStringValue",\n "_FPDF_StructElement_Attr_GetType",\n "_FPDF_StructElement_Attr_GetValue",\n "_FPDF_StructElement_CountChildren",\n "_FPDF_StructElement_GetActualText",\n "_FPDF_StructElement_GetAltText",\n "_FPDF_StructElement_GetAttributeAtIndex",\n "_FPDF_StructElement_GetAttributeCount",\n "_FPDF_StructElement_GetChildAtIndex",\n "_FPDF_StructElement_GetChildMarkedContentID",\n "_FPDF_StructElement_GetID",\n "_FPDF_StructElement_GetLang",\n "_FPDF_StructElement_GetMarkedContentID",\n "_FPDF_StructElement_GetMarkedContentIdAtIndex",\n "_FPDF_StructElement_GetMarkedContentIdCount",\n "_FPDF_StructElement_GetObjType",\n "_FPDF_StructElement_GetParent",\n "_FPDF_StructElement_GetStringAttribute",\n "_FPDF_StructElement_GetTitle",\n "_FPDF_StructElement_GetType",\n "_FPDF_StructTree_Close",\n "_FPDF_StructTree_CountChildren",\n "_FPDF_StructTree_GetChildAtIndex",\n "_FPDF_StructTree_GetForPage",\n "_FPDF_VIEWERREF_GetDuplex",\n "_FPDF_VIEWERREF_GetName",\n "_FPDF_VIEWERREF_GetNumCopies",\n "_FPDF_VIEWERREF_GetPrintPageRange",\n "_FPDF_VIEWERREF_GetPrintPageRangeCount",\n "_FPDF_VIEWERREF_GetPrintPageRangeElement",\n "_FPDF_VIEWERREF_GetPrintScaling",\n "_FPDFAction_GetDest",\n "_FPDFAction_GetFilePath",\n "_FPDFAction_GetType",\n "_FPDFAction_GetURIPath",\n "_FPDFAnnot_AddFileAttachment",\n "_FPDFAnnot_AddInkStroke",\n "_FPDFAnnot_AppendAttachmentPoints",\n "_FPDFAnnot_AppendObject",\n "_FPDFAnnot_CountAttachmentPoints",\n "_FPDFAnnot_GetAP",\n "_FPDFAnnot_GetAttachmentPoints",\n "_FPDFAnnot_GetBorder",\n "_FPDFAnnot_GetColor",\n "_FPDFAnnot_GetFileAttachment",\n "_FPDFAnnot_GetFlags",\n "_FPDFAnnot_GetFocusableSubtypes",\n "_FPDFAnnot_GetFocusableSubtypesCount",\n "_FPDFAnnot_GetFontColor",\n "_FPDFAnnot_GetFontSize",\n "_FPDFAnnot_GetFormAdditionalActionJavaScript",\n "_FPDFAnnot_GetFormControlCount",\n "_FPDFAnnot_GetFormControlIndex",\n "_FPDFAnnot_GetFormFieldAlternateName",\n "_FPDFAnnot_GetFormFieldAtPoint",\n "_FPDFAnnot_GetFormFieldExportValue",\n "_FPDFAnnot_GetFormFieldFlags",\n "_FPDFAnnot_GetFormFieldName",\n "_FPDFAnnot_GetFormFieldType",\n "_FPDFAnnot_GetFormFieldValue",\n "_FPDFAnnot_GetInkListCount",\n "_FPDFAnnot_GetInkListPath",\n "_FPDFAnnot_GetLine",\n "_FPDFAnnot_GetLink",\n "_FPDFAnnot_GetLinkedAnnot",\n "_FPDFAnnot_GetNumberValue",\n "_FPDFAnnot_GetObject",\n "_FPDFAnnot_GetObjectCount",\n "_FPDFAnnot_GetOptionCount",\n "_FPDFAnnot_GetOptionLabel",\n "_FPDFAnnot_GetRect",\n "_FPDFAnnot_GetStringValue",\n "_FPDFAnnot_GetSubtype",\n "_FPDFAnnot_GetValueType",\n "_FPDFAnnot_GetVertices",\n "_FPDFAnnot_HasAttachmentPoints",\n "_FPDFAnnot_HasKey",\n "_FPDFAnnot_IsChecked",\n "_FPDFAnnot_IsObjectSupportedSubtype",\n "_FPDFAnnot_IsOptionSelected",\n "_FPDFAnnot_IsSupportedSubtype",\n "_FPDFAnnot_RemoveInkList",\n "_FPDFAnnot_RemoveObject",\n "_FPDFAnnot_SetAP",\n "_FPDFAnnot_SetAttachmentPoints",\n "_FPDFAnnot_SetBorder",\n "_FPDFAnnot_SetColor",\n "_FPDFAnnot_SetFlags",\n "_FPDFAnnot_SetFocusableSubtypes",\n "_FPDFAnnot_SetFontColor",\n "_FPDFAnnot_SetFormFieldFlags",\n "_FPDFAnnot_SetRect",\n "_FPDFAnnot_SetStringValue",\n "_FPDFAnnot_SetURI",\n "_FPDFAnnot_UpdateObject",\n "_FPDFAttachment_GetFile",\n "_FPDFAttachment_GetName",\n "_FPDFAttachment_GetStringValue",\n "_FPDFAttachment_GetSubtype",\n "_FPDFAttachment_GetValueType",\n "_FPDFAttachment_HasKey",\n "_FPDFAttachment_SetFile",\n "_FPDFAttachment_SetStringValue",\n "_FPDFAvail_Create",\n "_FPDFAvail_Destroy",\n "_FPDFAvail_GetDocument",\n "_FPDFAvail_GetFirstPageNum",\n "_FPDFAvail_IsDocAvail",\n "_FPDFAvail_IsFormAvail",\n "_FPDFAvail_IsLinearized",\n "_FPDFAvail_IsPageAvail",\n "_FPDFBitmap_Create",\n "_FPDFBitmap_CreateEx",\n "_FPDFBitmap_Destroy",\n "_FPDFBitmap_FillRect",\n "_FPDFBitmap_GetBuffer",\n "_FPDFBitmap_GetFormat",\n "_FPDFBitmap_GetHeight",\n "_FPDFBitmap_GetStride",\n "_FPDFBitmap_GetWidth",\n "_FPDFBookmark_Find",\n "_FPDFBookmark_GetAction",\n "_FPDFBookmark_GetCount",\n "_FPDFBookmark_GetDest",\n "_FPDFBookmark_GetFirstChild",\n "_FPDFBookmark_GetNextSibling",\n "_FPDFBookmark_GetTitle",\n "_FPDFCatalog_GetLanguage",\n "_FPDFCatalog_IsTagged",\n "_FPDFCatalog_SetLanguage",\n "_FPDFClipPath_CountPaths",\n "_FPDFClipPath_CountPathSegments",\n "_FPDFClipPath_GetPathSegment",\n "_FPDFDest_GetDestPageIndex",\n "_FPDFDest_GetLocationInPage",\n "_FPDFDest_GetView",\n "_FPDFDoc_AddAttachment",\n "_FPDFDoc_CloseJavaScriptAction",\n "_FPDFDoc_DeleteAttachment",\n "_FPDFDOC_ExitFormFillEnvironment",\n "_FPDFDoc_GetAttachment",\n "_FPDFDoc_GetAttachmentCount",\n "_FPDFDoc_GetJavaScriptAction",\n "_FPDFDoc_GetJavaScriptActionCount",\n "_FPDFDoc_GetPageMode",\n "_FPDFDOC_InitFormFillEnvironment",\n "_FPDFFont_Close",\n "_FPDFFont_GetAscent",\n "_FPDFFont_GetBaseFontName",\n "_FPDFFont_GetDescent",\n "_FPDFFont_GetFamilyName",\n "_FPDFFont_GetFlags",\n "_FPDFFont_GetFontData",\n "_FPDFFont_GetGlyphPath",\n "_FPDFFont_GetGlyphWidth",\n "_FPDFFont_GetIsEmbedded",\n "_FPDFFont_GetItalicAngle",\n "_FPDFFont_GetWeight",\n "_FPDFFormObj_CountObjects",\n "_FPDFFormObj_GetObject",\n "_FPDFFormObj_RemoveObject",\n "_FPDFGlyphPath_CountGlyphSegments",\n "_FPDFGlyphPath_GetGlyphPathSegment",\n "_FPDFImageObj_GetBitmap",\n "_FPDFImageObj_GetIccProfileDataDecoded",\n "_FPDFImageObj_GetImageDataDecoded",\n "_FPDFImageObj_GetImageDataRaw",\n "_FPDFImageObj_GetImageFilter",\n "_FPDFImageObj_GetImageFilterCount",\n "_FPDFImageObj_GetImageMetadata",\n "_FPDFImageObj_GetImagePixelSize",\n "_FPDFImageObj_GetRenderedBitmap",\n "_FPDFImageObj_LoadJpegFile",\n "_FPDFImageObj_LoadJpegFileInline",\n "_FPDFImageObj_SetBitmap",\n "_FPDFImageObj_SetMatrix",\n "_FPDFJavaScriptAction_GetName",\n "_FPDFJavaScriptAction_GetScript",\n "_FPDFLink_CloseWebLinks",\n "_FPDFLink_CountQuadPoints",\n "_FPDFLink_CountRects",\n "_FPDFLink_CountWebLinks",\n "_FPDFLink_Enumerate",\n "_FPDFLink_GetAction",\n "_FPDFLink_GetAnnot",\n "_FPDFLink_GetAnnotRect",\n "_FPDFLink_GetDest",\n "_FPDFLink_GetLinkAtPoint",\n "_FPDFLink_GetLinkZOrderAtPoint",\n "_FPDFLink_GetQuadPoints",\n "_FPDFLink_GetRect",\n "_FPDFLink_GetTextRange",\n "_FPDFLink_GetURL",\n "_FPDFLink_LoadWebLinks",\n "_FPDFPage_CloseAnnot",\n "_FPDFPage_CountObjects",\n "_FPDFPage_CreateAnnot",\n "_FPDFPage_Delete",\n "_FPDFPage_Flatten",\n "_FPDFPage_FormFieldZOrderAtPoint",\n "_FPDFPage_GenerateContent",\n "_FPDFPage_GetAnnot",\n "_FPDFPage_GetAnnotCount",\n "_FPDFPage_GetAnnotIndex",\n "_FPDFPage_GetArtBox",\n "_FPDFPage_GetBleedBox",\n "_FPDFPage_GetCropBox",\n "_FPDFPage_GetDecodedThumbnailData",\n "_FPDFPage_GetMediaBox",\n "_FPDFPage_GetObject",\n "_FPDFPage_GetRawThumbnailData",\n "_FPDFPage_GetRotation",\n "_FPDFPage_GetThumbnailAsBitmap",\n "_FPDFPage_GetTrimBox",\n "_FPDFPage_HasFormFieldAtPoint",\n "_FPDFPage_HasTransparency",\n "_FPDFPage_InsertClipPath",\n "_FPDFPage_InsertObject",\n "_FPDFPage_InsertObjectAtIndex",\n "_FPDFPage_New",\n "_FPDFPage_RemoveAnnot",\n "_FPDFPage_RemoveObject",\n "_FPDFPage_SetArtBox",\n "_FPDFPage_SetBleedBox",\n "_FPDFPage_SetCropBox",\n "_FPDFPage_SetMediaBox",\n "_FPDFPage_SetRotation",\n "_FPDFPage_SetTrimBox",\n "_FPDFPage_TransformAnnots",\n "_FPDFPage_TransFormWithClip",\n "_FPDFPageObj_AddMark",\n "_FPDFPageObj_CountMarks",\n "_FPDFPageObj_CreateNewPath",\n "_FPDFPageObj_CreateNewRect",\n "_FPDFPageObj_CreateTextObj",\n "_FPDFPageObj_Destroy",\n "_FPDFPageObj_GetBounds",\n "_FPDFPageObj_GetClipPath",\n "_FPDFPageObj_GetDashArray",\n "_FPDFPageObj_GetDashCount",\n "_FPDFPageObj_GetDashPhase",\n "_FPDFPageObj_GetFillColor",\n "_FPDFPageObj_GetIsActive",\n "_FPDFPageObj_GetLineCap",\n "_FPDFPageObj_GetLineJoin",\n "_FPDFPageObj_GetMark",\n "_FPDFPageObj_GetMarkedContentID",\n "_FPDFPageObj_GetMatrix",\n "_FPDFPageObj_GetRotatedBounds",\n "_FPDFPageObj_GetStrokeColor",\n "_FPDFPageObj_GetStrokeWidth",\n "_FPDFPageObj_GetType",\n "_FPDFPageObj_HasTransparency",\n "_FPDFPageObj_NewImageObj",\n "_FPDFPageObj_NewTextObj",\n "_FPDFPageObj_RemoveMark",\n "_FPDFPageObj_SetBlendMode",\n "_FPDFPageObj_SetDashArray",\n "_FPDFPageObj_SetDashPhase",\n "_FPDFPageObj_SetFillColor",\n "_FPDFPageObj_SetIsActive",\n "_FPDFPageObj_SetLineCap",\n "_FPDFPageObj_SetLineJoin",\n "_FPDFPageObj_SetMatrix",\n "_FPDFPageObj_SetStrokeColor",\n "_FPDFPageObj_SetStrokeWidth",\n "_FPDFPageObj_Transform",\n "_FPDFPageObj_TransformClipPath",\n "_FPDFPageObj_TransformF",\n "_FPDFPageObjMark_CountParams",\n "_FPDFPageObjMark_GetName",\n "_FPDFPageObjMark_GetParamBlobValue",\n "_FPDFPageObjMark_GetParamFloatValue",\n "_FPDFPageObjMark_GetParamIntValue",\n "_FPDFPageObjMark_GetParamKey",\n "_FPDFPageObjMark_GetParamStringValue",\n "_FPDFPageObjMark_GetParamValueType",\n "_FPDFPageObjMark_RemoveParam",\n "_FPDFPageObjMark_SetBlobParam",\n "_FPDFPageObjMark_SetFloatParam",\n "_FPDFPageObjMark_SetIntParam",\n "_FPDFPageObjMark_SetStringParam",\n "_FPDFPath_BezierTo",\n "_FPDFPath_Close",\n "_FPDFPath_CountSegments",\n "_FPDFPath_GetDrawMode",\n "_FPDFPath_GetPathSegment",\n "_FPDFPath_LineTo",\n "_FPDFPath_MoveTo",\n "_FPDFPath_SetDrawMode",\n "_FPDFPathSegment_GetClose",\n "_FPDFPathSegment_GetPoint",\n "_FPDFPathSegment_GetType",\n "_FPDFSignatureObj_GetByteRange",\n "_FPDFSignatureObj_GetContents",\n "_FPDFSignatureObj_GetDocMDPPermission",\n "_FPDFSignatureObj_GetReason",\n "_FPDFSignatureObj_GetSubFilter",\n "_FPDFSignatureObj_GetTime",\n "_FPDFText_ClosePage",\n "_FPDFText_CountChars",\n "_FPDFText_CountRects",\n "_FPDFText_FindClose",\n "_FPDFText_FindNext",\n "_FPDFText_FindPrev",\n "_FPDFText_FindStart",\n "_FPDFText_GetBoundedText",\n "_FPDFText_GetCharAngle",\n "_FPDFText_GetCharBox",\n "_FPDFText_GetCharIndexAtPos",\n "_FPDFText_GetCharIndexFromTextIndex",\n "_FPDFText_GetCharOrigin",\n "_FPDFText_GetFillColor",\n "_FPDFText_GetFontInfo",\n "_FPDFText_GetFontSize",\n "_FPDFText_GetFontWeight",\n "_FPDFText_GetLooseCharBox",\n "_FPDFText_GetMatrix",\n "_FPDFText_GetRect",\n "_FPDFText_GetSchCount",\n "_FPDFText_GetSchResultIndex",\n "_FPDFText_GetStrokeColor",\n "_FPDFText_GetText",\n "_FPDFText_GetTextIndexFromCharIndex",\n "_FPDFText_GetTextObject",\n "_FPDFText_GetUnicode",\n "_FPDFText_HasUnicodeMapError",\n "_FPDFText_IsGenerated",\n "_FPDFText_IsHyphen",\n "_FPDFText_LoadCidType2Font",\n "_FPDFText_LoadFont",\n "_FPDFText_LoadPage",\n "_FPDFText_LoadStandardFont",\n "_FPDFText_SetCharcodes",\n "_FPDFText_SetText",\n "_FPDFTextObj_GetFont",\n "_FPDFTextObj_GetFontSize",\n "_FPDFTextObj_GetRenderedBitmap",\n "_FPDFTextObj_GetText",\n "_FPDFTextObj_GetTextRenderMode",\n "_FPDFTextObj_SetTextRenderMode",\n "_PDFiumExt_CloseFileWriter",\n "_PDFiumExt_CloseFormFillInfo",\n "_PDFiumExt_ExitFormFillEnvironment",\n "_PDFiumExt_GetFileWriterData",\n "_PDFiumExt_GetFileWriterSize",\n "_PDFiumExt_Init",\n "_PDFiumExt_InitFormFillEnvironment",\n "_PDFiumExt_OpenFileWriter",\n "_PDFiumExt_OpenFormFillInfo",\n "_PDFiumExt_SaveAsCopy",\n "_malloc",\n "_free",\n "_memory",\n "___indirect_function_table",\n "onRuntimeInitialized"\n ].forEach((prop) => {\n if (!Object.getOwnPropertyDescriptor(readyPromise, prop)) {\n Object.defineProperty(readyPromise, prop, {\n get: () => abort(\n "You are getting " + prop + " on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js"\n ),\n set: () => abort(\n "You are setting " + prop + " on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js"\n )\n });\n }\n });\n var ENVIRONMENT_IS_WEB = typeof window == "object";\n var ENVIRONMENT_IS_WORKER = typeof importScripts == "function";\n typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string" && process.type != "renderer";\n var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && true && !ENVIRONMENT_IS_WORKER;\n var moduleOverrides = Object.assign({}, Module);\n var thisProgram = "./this.program";\n var scriptDirectory = "";\n function locateFile(path) {\n if (Module["locateFile"]) {\n return Module["locateFile"](path, scriptDirectory);\n }\n return scriptDirectory + path;\n }\n var readAsync, readBinary;\n if (ENVIRONMENT_IS_SHELL) {\n if (typeof window == "object" || typeof importScripts == "function")\n throw new Error(\n "not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)"\n );\n readBinary = (f) => {\n if (typeof readbuffer == "function") {\n return new Uint8Array(readbuffer(f));\n }\n let data = read(f, "binary");\n assert(typeof data == "object");\n return data;\n };\n readAsync = (f) => {\n return new Promise((resolve, reject) => {\n setTimeout(() => resolve(readBinary(f)));\n });\n };\n globalThis.clearTimeout ?? (globalThis.clearTimeout = (id) => {\n });\n globalThis.setTimeout ?? (globalThis.setTimeout = (f) => typeof f == "function" ? f() : abort());\n if (typeof print != "undefined") {\n globalThis.console ?? (globalThis.console = /** @type{!Console} */\n {});\n console.log = /** @type{!function(this:Console, ...*): undefined} */\n print;\n console.warn = console.error = /** @type{!function(this:Console, ...*): undefined} */\n globalThis.printErr ?? print;\n }\n } else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {\n if (ENVIRONMENT_IS_WORKER) {\n scriptDirectory = self.location.href;\n } else if (typeof document != "undefined" && document.currentScript) {\n scriptDirectory = document.currentScript.src;\n }\n if (_scriptName) {\n scriptDirectory = _scriptName;\n }\n if (scriptDirectory.startsWith("blob:")) {\n scriptDirectory = "";\n } else {\n scriptDirectory = scriptDirectory.substr(\n 0,\n scriptDirectory.replace(/[?#].*/, "").lastIndexOf("/") + 1\n );\n }\n if (!(typeof window == "object" || typeof importScripts == "function"))\n throw new Error(\n "not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)"\n );\n {\n if (ENVIRONMENT_IS_WORKER) {\n readBinary = (url) => {\n var xhr = new XMLHttpRequest();\n xhr.open("GET", url, false);\n xhr.responseType = "arraybuffer";\n xhr.send(null);\n return new Uint8Array(\n /** @type{!ArrayBuffer} */\n xhr.response\n );\n };\n }\n readAsync = (url) => {\n assert(!isFileURI(url), "readAsync does not work with file:// URLs");\n return fetch(url, { credentials: "same-origin" }).then((response) => {\n if (response.ok) {\n return response.arrayBuffer();\n }\n return Promise.reject(new Error(response.status + " : " + response.url));\n });\n };\n }\n } else {\n throw new Error("environment detection error");\n }\n var out = Module["print"] || console.log.bind(console);\n var err = Module["printErr"] || console.error.bind(console);\n Object.assign(Module, moduleOverrides);\n moduleOverrides = null;\n checkIncomingModuleAPI();\n if (Module["arguments"]) Module["arguments"];\n legacyModuleProp("arguments", "arguments_");\n if (Module["thisProgram"]) thisProgram = Module["thisProgram"];\n legacyModuleProp("thisProgram", "thisProgram");\n assert(\n typeof Module["memoryInitializerPrefixURL"] == "undefined",\n "Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead"\n );\n assert(\n typeof Module["pthreadMainPrefixURL"] == "undefined",\n "Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead"\n );\n assert(\n typeof Module["cdInitializerPrefixURL"] == "undefined",\n "Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead"\n );\n assert(\n typeof Module["filePackagePrefixURL"] == "undefined",\n "Module.filePackagePrefixURL option was removed, use Module.locateFile instead"\n );\n assert(typeof Module["read"] == "undefined", "Module.read option was removed");\n assert(\n typeof Module["readAsync"] == "undefined",\n "Module.readAsync option was removed (modify readAsync in JS)"\n );\n assert(\n typeof Module["readBinary"] == "undefined",\n "Module.readBinary option was removed (modify readBinary in JS)"\n );\n assert(\n typeof Module["setWindowTitle"] == "undefined",\n "Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)"\n );\n assert(\n typeof Module["TOTAL_MEMORY"] == "undefined",\n "Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY"\n );\n legacyModuleProp("asm", "wasmExports");\n legacyModuleProp("readAsync", "readAsync");\n legacyModuleProp("readBinary", "readBinary");\n legacyModuleProp("setWindowTitle", "setWindowTitle");\n var wasmBinary = Module["wasmBinary"];\n legacyModuleProp("wasmBinary", "wasmBinary");\n if (typeof WebAssembly != "object") {\n err("no native wasm support detected");\n }\n var wasmMemory;\n var ABORT = false;\n function assert(condition, text) {\n if (!condition) {\n abort("Assertion failed" + (text ? ": " + text : ""));\n }\n }\n var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64;\n function updateMemoryViews() {\n var b = wasmMemory.buffer;\n Module["HEAP8"] = HEAP8 = new Int8Array(b);\n Module["HEAP16"] = HEAP16 = new Int16Array(b);\n Module["HEAPU8"] = HEAPU8 = new Uint8Array(b);\n Module["HEAPU16"] = HEAPU16 = new Uint16Array(b);\n Module["HEAP32"] = HEAP32 = new Int32Array(b);\n Module["HEAPU32"] = HEAPU32 = new Uint32Array(b);\n Module["HEAPF32"] = HEAPF32 = new Float32Array(b);\n Module["HEAPF64"] = HEAPF64 = new Float64Array(b);\n }\n assert(\n !Module["STACK_SIZE"],\n "STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time"\n );\n assert(\n typeof Int32Array != "undefined" && typeof Float64Array !== "undefined" && Int32Array.prototype.subarray != void 0 && Int32Array.prototype.set != void 0,\n "JS engine does not provide full typed array support"\n );\n assert(\n !Module["wasmMemory"],\n "Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally"\n );\n assert(\n !Module["INITIAL_MEMORY"],\n "Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically"\n );\n function writeStackCookie() {\n var max = _emscripten_stack_get_end();\n assert((max & 3) == 0);\n if (max == 0) {\n max += 4;\n }\n HEAPU32[max >> 2] = 34821223;\n HEAPU32[max + 4 >> 2] = 2310721022;\n HEAPU32[0 >> 2] = 1668509029;\n }\n function checkStackCookie() {\n if (ABORT) return;\n var max = _emscripten_stack_get_end();\n if (max == 0) {\n max += 4;\n }\n var cookie1 = HEAPU32[max >> 2];\n var cookie2 = HEAPU32[max + 4 >> 2];\n if (cookie1 != 34821223 || cookie2 != 2310721022) {\n abort(\n `Stack overflow! Stack cookie has been overwritten at ${ptrToString(max)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${ptrToString(cookie2)} ${ptrToString(cookie1)}`\n );\n }\n if (HEAPU32[0 >> 2] != 1668509029) {\n abort("Runtime error: The application has corrupted its heap memory area (address zero)!");\n }\n }\n var __ATPRERUN__ = [];\n var __ATINIT__ = [];\n var __ATPOSTRUN__ = [];\n var runtimeInitialized = false;\n function preRun() {\n var preRuns = Module["preRun"];\n if (preRuns) {\n if (typeof preRuns == "function") preRuns = [preRuns];\n preRuns.forEach(addOnPreRun);\n }\n callRuntimeCallbacks(__ATPRERUN__);\n }\n function initRuntime() {\n assert(!runtimeInitialized);\n runtimeInitialized = true;\n checkStackCookie();\n if (!Module["noFSInit"] && !FS.initialized) FS.init();\n FS.ignorePermissions = false;\n callRuntimeCallbacks(__ATINIT__);\n }\n function postRun() {\n checkStackCookie();\n var postRuns = Module["postRun"];\n if (postRuns) {\n if (typeof postRuns == "function") postRuns = [postRuns];\n postRuns.forEach(addOnPostRun);\n }\n callRuntimeCallbacks(__ATPOSTRUN__);\n }\n function addOnPreRun(cb) {\n __ATPRERUN__.unshift(cb);\n }\n function addOnInit(cb) {\n __ATINIT__.unshift(cb);\n }\n function addOnPostRun(cb) {\n __ATPOSTRUN__.unshift(cb);\n }\n assert(\n Math.imul,\n "This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"\n );\n assert(\n Math.fround,\n "This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"\n );\n assert(\n Math.clz32,\n "This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"\n );\n assert(\n Math.trunc,\n "This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"\n );\n var runDependencies = 0;\n var runDependencyWatcher = null;\n var dependenciesFulfilled = null;\n var runDependencyTracking = {};\n function getUniqueRunDependency(id) {\n var orig = id;\n while (1) {\n if (!runDependencyTracking[id]) return id;\n id = orig + Math.random();\n }\n }\n function addRunDependency(id) {\n var _a;\n runDependencies++;\n (_a = Module["monitorRunDependencies"]) == null ? void 0 : _a.call(Module, runDependencies);\n if (id) {\n assert(!runDependencyTracking[id]);\n runDependencyTracking[id] = 1;\n if (runDependencyWatcher === null && typeof setInterval != "undefined") {\n runDependencyWatcher = setInterval(() => {\n if (ABORT) {\n clearInterval(runDependencyWatcher);\n runDependencyWatcher = null;\n return;\n }\n var shown = false;\n for (var dep in runDependencyTracking) {\n if (!shown) {\n shown = true;\n err("still waiting on run dependencies:");\n }\n err(`dependency: ${dep}`);\n }\n if (shown) {\n err("(end of list)");\n }\n }, 1e4);\n }\n } else {\n err("warning: run dependency added without ID");\n }\n }\n function removeRunDependency(id) {\n var _a;\n runDependencies--;\n (_a = Module["monitorRunDependencies"]) == null ? void 0 : _a.call(Module, runDependencies);\n if (id) {\n assert(runDependencyTracking[id]);\n delete runDependencyTracking[id];\n } else {\n err("warning: run dependency removed without ID");\n }\n if (runDependencies == 0) {\n if (runDependencyWatcher !== null) {\n clearInterval(runDependencyWatcher);\n runDependencyWatcher = null;\n }\n if (dependenciesFulfilled) {\n var callback = dependenciesFulfilled;\n dependenciesFulfilled = null;\n callback();\n }\n }\n }\n function abort(what) {\n var _a;\n (_a = Module["onAbort"]) == null ? void 0 : _a.call(Module, what);\n what = "Aborted(" + what + ")";\n err(what);\n ABORT = true;\n var e = new WebAssembly.RuntimeError(what);\n readyPromiseReject(e);\n throw e;\n }\n var dataURIPrefix = "data:application/octet-stream;base64,";\n var isDataURI = (filename) => filename.startsWith(dataURIPrefix);\n var isFileURI = (filename) => filename.startsWith("file://");\n function createExportWrapper(name, nargs) {\n return (...args) => {\n assert(\n runtimeInitialized,\n `native function \\`${name}\\` called before runtime initialization`\n );\n var f = wasmExports[name];\n assert(f, `exported native function \\`${name}\\` not found`);\n assert(\n args.length <= nargs,\n `native function \\`${name}\\` called with ${args.length} args but expects ${nargs}`\n );\n return f(...args);\n };\n }\n function findWasmBinary() {\n if (Module["locateFile"]) {\n var f = "pdfium.wasm";\n if (!isDataURI(f)) {\n return locateFile(f);\n }\n return f;\n }\n if (ENVIRONMENT_IS_SHELL) return "pdfium.wasm";\n return "pdfium.wasm";\n }\n var wasmBinaryFile;\n function getBinarySync(file) {\n if (file == wasmBinaryFile && wasmBinary) {\n return new Uint8Array(wasmBinary);\n }\n if (readBinary) {\n return readBinary(file);\n }\n throw "both async and sync fetching of the wasm failed";\n }\n function getBinaryPromise(binaryFile) {\n if (!wasmBinary) {\n return readAsync(binaryFile).then(\n (response) => new Uint8Array(\n /** @type{!ArrayBuffer} */\n response\n ),\n // Fall back to getBinarySync if readAsync fails\n () => getBinarySync(binaryFile)\n );\n }\n return Promise.resolve().then(() => getBinarySync(binaryFile));\n }\n function instantiateArrayBuffer(binaryFile, imports, receiver) {\n return getBinaryPromise(binaryFile).then((binary) => {\n return WebAssembly.instantiate(binary, imports);\n }).then(receiver, (reason) => {\n err(`failed to asynchronously prepare wasm: ${reason}`);\n if (isFileURI(wasmBinaryFile)) {\n err(\n `warning: Loading from a file URI (${wasmBinaryFile}) is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing`\n );\n }\n abort(reason);\n });\n }\n function instantiateAsync(binary, binaryFile, imports, callback) {\n if (!binary && typeof WebAssembly.instantiateStreaming == "function" && !isDataURI(binaryFile) && // Avoid instantiateStreaming() on Node.js environment for now, as while\n // Node.js v18.1.0 implements it, it does not have a full fetch()\n // implementation yet.\n //\n // Reference:\n // https://github.com/emscripten-core/emscripten/pull/16917\n true && typeof fetch == "function") {\n return fetch(binaryFile, { credentials: "same-origin" }).then((response) => {\n var result = WebAssembly.instantiateStreaming(response, imports);\n return result.then(callback, function(reason) {\n err(`wasm streaming compile failed: ${reason}`);\n err("falling back to ArrayBuffer instantiation");\n return instantiateArrayBuffer(binaryFile, imports, callback);\n });\n });\n }\n return instantiateArrayBuffer(binaryFile, imports, callback);\n }\n function getWasmImports() {\n return {\n env: wasmImports,\n wasi_snapshot_preview1: wasmImports\n };\n }\n function createWasm() {\n var info = getWasmImports();\n function receiveInstance(instance, module) {\n wasmExports = instance.exports;\n Module["wasmExports"] = wasmExports;\n wasmMemory = wasmExports["memory"];\n assert(wasmMemory, "memory not found in wasm exports");\n updateMemoryViews();\n wasmTable = wasmExports["__indirect_function_table"];\n assert(wasmTable, "table not found in wasm exports");\n addOnInit(wasmExports["__wasm_call_ctors"]);\n removeRunDependency("wasm-instantiate");\n return wasmExports;\n }\n addRunDependency("wasm-instantiate");\n var trueModule = Module;\n function receiveInstantiationResult(result) {\n assert(\n Module === trueModule,\n "the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?"\n );\n trueModule = null;\n receiveInstance(result["instance"]);\n }\n if (Module["instantiateWasm"]) {\n try {\n return Module["instantiateWasm"](info, receiveInstance);\n } catch (e) {\n err(`Module.instantiateWasm callback failed with error: ${e}`);\n readyPromiseReject(e);\n }\n }\n wasmBinaryFile ?? (wasmBinaryFile = findWasmBinary());\n instantiateAsync(wasmBinary, wasmBinaryFile, info, receiveInstantiationResult).catch(\n readyPromiseReject\n );\n return {};\n }\n var tempDouble;\n var tempI64;\n (() => {\n var h16 = new Int16Array(1);\n var h8 = new Int8Array(h16.buffer);\n h16[0] = 25459;\n if (h8[0] !== 115 || h8[1] !== 99)\n throw "Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)";\n })();\n if (Module["ENVIRONMENT"]) {\n throw new Error(\n "Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)"\n );\n }\n function legacyModuleProp(prop, newName, incoming = true) {\n if (!Object.getOwnPropertyDescriptor(Module, prop)) {\n Object.defineProperty(Module, prop, {\n configurable: true,\n get() {\n let extra = incoming ? " (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)" : "";\n abort(`\\`Module.${prop}\\` has been replaced by \\`${newName}\\`` + extra);\n }\n });\n }\n }\n function ignoredModuleProp(prop) {\n if (Object.getOwnPropertyDescriptor(Module, prop)) {\n abort(\n `\\`Module.${prop}\\` was supplied but \\`${prop}\\` not included in INCOMING_MODULE_JS_API`\n );\n }\n }\n function isExportedByForceFilesystem(name) {\n return name === "FS_createPath" || name === "FS_createDataFile" || name === "FS_createPreloadedFile" || name === "FS_unlink" || name === "addRunDependency" || // The old FS has some functionality that WasmFS lacks.\n name === "FS_createLazyFile" || name === "FS_createDevice" || name === "removeRunDependency";\n }\n function hookGlobalSymbolAccess(sym, func) {\n if (typeof globalThis != "undefined" && !Object.getOwnPropertyDescriptor(globalThis, sym)) {\n Object.defineProperty(globalThis, sym, {\n configurable: true,\n get() {\n func();\n return void 0;\n }\n });\n }\n }\n function missingGlobal(sym, msg) {\n hookGlobalSymbolAccess(sym, () => {\n warnOnce(`\\`${sym}\\` is not longer defined by emscripten. ${msg}`);\n });\n }\n missingGlobal("buffer", "Please use HEAP8.buffer or wasmMemory.buffer");\n missingGlobal("asm", "Please use wasmExports instead");\n function missingLibrarySymbol(sym) {\n hookGlobalSymbolAccess(sym, () => {\n var msg = `\\`${sym}\\` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line`;\n var librarySymbol = sym;\n if (!librarySymbol.startsWith("_")) {\n librarySymbol = "$" + sym;\n }\n msg += ` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE=\'${librarySymbol}\')`;\n if (isExportedByForceFilesystem(sym)) {\n msg += ". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you";\n }\n warnOnce(msg);\n });\n unexportedRuntimeSymbol(sym);\n }\n function unexportedRuntimeSymbol(sym) {\n if (!Object.getOwnPropertyDescriptor(Module, sym)) {\n Object.defineProperty(Module, sym, {\n configurable: true,\n get() {\n var msg = `\'${sym}\' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)`;\n if (isExportedByForceFilesystem(sym)) {\n msg += ". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you";\n }\n abort(msg);\n }\n });\n }\n }\n var callRuntimeCallbacks = (callbacks) => {\n callbacks.forEach((f) => f(Module));\n };\n function getValue(ptr, type = "i8") {\n if (type.endsWith("*")) type = "*";\n switch (type) {\n case "i1":\n return HEAP8[ptr];\n case "i8":\n return HEAP8[ptr];\n case "i16":\n return HEAP16[ptr >> 1];\n case "i32":\n return HEAP32[ptr >> 2];\n case "i64":\n abort("to do getValue(i64) use WASM_BIGINT");\n case "float":\n return HEAPF32[ptr >> 2];\n case "double":\n return HEAPF64[ptr >> 3];\n case "*":\n return HEAPU32[ptr >> 2];\n default:\n abort(`invalid type for getValue: ${type}`);\n }\n }\n Module["noExitRuntime"] || true;\n var ptrToString = (ptr) => {\n assert(typeof ptr === "number");\n ptr >>>= 0;\n return "0x" + ptr.toString(16).padStart(8, "0");\n };\n function setValue(ptr, value, type = "i8") {\n if (type.endsWith("*")) type = "*";\n switch (type) {\n case "i1":\n HEAP8[ptr] = value;\n break;\n case "i8":\n HEAP8[ptr] = value;\n break;\n case "i16":\n HEAP16[ptr >> 1] = value;\n break;\n case "i32":\n HEAP32[ptr >> 2] = value;\n break;\n case "i64":\n abort("to do setValue(i64) use WASM_BIGINT");\n case "float":\n HEAPF32[ptr >> 2] = value;\n break;\n case "double":\n HEAPF64[ptr >> 3] = value;\n break;\n case "*":\n HEAPU32[ptr >> 2] = value;\n break;\n default:\n abort(`invalid type for setValue: ${type}`);\n }\n }\n var stackRestore = (val) => __emscripten_stack_restore(val);\n var stackSave = () => _emscripten_stack_get_current();\n var warnOnce = (text) => {\n warnOnce.shown || (warnOnce.shown = {});\n if (!warnOnce.shown[text]) {\n warnOnce.shown[text] = 1;\n err(text);\n }\n };\n var UTF8Decoder = typeof TextDecoder != "undefined" ? new TextDecoder() : void 0;\n var UTF8ArrayToString = (heapOrArray, idx = 0, maxBytesToRead = NaN) => {\n var endIdx = idx + maxBytesToRead;\n var endPtr = idx;\n while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr;\n if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {\n return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));\n }\n var str = "";\n while (idx < endPtr) {\n var u0 = heapOrArray[idx++];\n if (!(u0 & 128)) {\n str += String.fromCharCode(u0);\n continue;\n }\n var u1 = heapOrArray[idx++] & 63;\n if ((u0 & 224) == 192) {\n str += String.fromCharCode((u0 & 31) << 6 | u1);\n continue;\n }\n var u2 = heapOrArray[idx++] & 63;\n if ((u0 & 240) == 224) {\n u0 = (u0 & 15) << 12 | u1 << 6 | u2;\n } else {\n if ((u0 & 248) != 240)\n warnOnce(\n "Invalid UTF-8 leading byte " + ptrToString(u0) + " encountered when deserializing a UTF-8 string in wasm memory to a JS string!"\n );\n u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heapOrArray[idx++] & 63;\n }\n if (u0 < 65536) {\n str += String.fromCharCode(u0);\n } else {\n var ch = u0 - 65536;\n str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023);\n }\n }\n return str;\n };\n var UTF8ToString = (ptr, maxBytesToRead) => {\n assert(typeof ptr == "number", `UTF8ToString expects a number (got ${typeof ptr})`);\n return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : "";\n };\n var ___assert_fail = (condition, filename, line, func) => {\n abort(\n `Assertion failed: ${UTF8ToString(condition)}, at: ` + [\n filename ? UTF8ToString(filename) : "unknown filename",\n line,\n func ? UTF8ToString(func) : "unknown function"\n ]\n );\n };\n function syscallGetVarargI() {\n assert(SYSCALLS.varargs != void 0);\n var ret = HEAP32[+SYSCALLS.varargs >> 2];\n SYSCALLS.varargs += 4;\n return ret;\n }\n var syscallGetVarargP = syscallGetVarargI;\n var PATH = {\n isAbs: (path) => path.charAt(0) === "/",\n splitPath: (filename) => {\n var splitPathRe = /^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^\\/]+?|)(\\.[^.\\/]*|))(?:[\\/]*)$/;\n return splitPathRe.exec(filename).slice(1);\n },\n normalizeArray: (parts, allowAboveRoot) => {\n var up = 0;\n for (var i = parts.length - 1; i >= 0; i--) {\n var last = parts[i];\n if (last === ".") {\n parts.splice(i, 1);\n } else if (last === "..") {\n parts.splice(i, 1);\n up++;\n } else if (up) {\n parts.splice(i, 1);\n up--;\n }\n }\n if (allowAboveRoot) {\n for (; up; up--) {\n parts.unshift("..");\n }\n }\n return parts;\n },\n normalize: (path) => {\n var isAbsolute = PATH.isAbs(path), trailingSlash = path.substr(-1) === "/";\n path = PATH.normalizeArray(\n path.split("/").filter((p) => !!p),\n !isAbsolute\n ).join("/");\n if (!path && !isAbsolute) {\n path = ".";\n }\n if (path && trailingSlash) {\n path += "/";\n }\n return (isAbsolute ? "/" : "") + path;\n },\n dirname: (path) => {\n var result = PATH.splitPath(path), root = result[0], dir = result[1];\n if (!root && !dir) {\n return ".";\n }\n if (dir) {\n dir = dir.substr(0, dir.length - 1);\n }\n return root + dir;\n },\n basename: (path) => {\n if (path === "/") return "/";\n path = PATH.normalize(path);\n path = path.replace(/\\/$/, "");\n var lastSlash = path.lastIndexOf("/");\n if (lastSlash === -1) return path;\n return path.substr(lastSlash + 1);\n },\n join: (...paths) => PATH.normalize(paths.join("/")),\n join2: (l, r) => PATH.normalize(l + "/" + r)\n };\n var initRandomFill = () => {\n if (typeof crypto == "object" && typeof crypto["getRandomValues"] == "function") {\n return (view) => crypto.getRandomValues(view);\n }\n abort(\n "no cryptographic support found for randomDevice. consider polyfilling it if you want to use something insecure like Math.random(), e.g. put this in a --pre-js: var crypto = { getRandomValues: (array) => { for (var i = 0; i < array.length; i++) array[i] = (Math.random()*256)|0 } };"\n );\n };\n var randomFill = (view) => {\n return (randomFill = initRandomFill())(view);\n };\n var PATH_FS = {\n resolve: (...args) => {\n var resolvedPath = "", resolvedAbsolute = false;\n for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n var path = i >= 0 ? args[i] : FS.cwd();\n if (typeof path != "string") {\n throw new TypeError("Arguments to path.resolve must be strings");\n } else if (!path) {\n return "";\n }\n resolvedPath = path + "/" + resolvedPath;\n resolvedAbsolute = PATH.isAbs(path);\n }\n resolvedPath = PATH.normalizeArray(\n resolvedPath.split("/").filter((p) => !!p),\n !resolvedAbsolute\n ).join("/");\n return (resolvedAbsolute ? "/" : "") + resolvedPath || ".";\n },\n relative: (from, to) => {\n from = PATH_FS.resolve(from).substr(1);\n to = PATH_FS.resolve(to).substr(1);\n function trim(arr) {\n var start = 0;\n for (; start < arr.length; start++) {\n if (arr[start] !== "") break;\n }\n var end = arr.length - 1;\n for (; end >= 0; end--) {\n if (arr[end] !== "") break;\n }\n if (start > end) return [];\n return arr.slice(start, end - start + 1);\n }\n var fromParts = trim(from.split("/"));\n var toParts = trim(to.split("/"));\n var length = Math.min(fromParts.length, toParts.length);\n var samePartsLength = length;\n for (var i = 0; i < length; i++) {\n if (fromParts[i] !== toParts[i]) {\n samePartsLength = i;\n break;\n }\n }\n var outputParts = [];\n for (var i = samePartsLength; i < fromParts.length; i++) {\n outputParts.push("..");\n }\n outputParts = outputParts.concat(toParts.slice(samePartsLength));\n return outputParts.join("/");\n }\n };\n var FS_stdin_getChar_buffer = [];\n var lengthBytesUTF8 = (str) => {\n var len = 0;\n for (var i = 0; i < str.length; ++i) {\n var c = str.charCodeAt(i);\n if (c <= 127) {\n len++;\n } else if (c <= 2047) {\n len += 2;\n } else if (c >= 55296 && c <= 57343) {\n len += 4;\n ++i;\n } else {\n len += 3;\n }\n }\n return len;\n };\n var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {\n assert(typeof str === "string", `stringToUTF8Array expects a string (got ${typeof str})`);\n if (!(maxBytesToWrite > 0)) return 0;\n var startIdx = outIdx;\n var endIdx = outIdx + maxBytesToWrite - 1;\n for (var i = 0; i < str.length; ++i) {\n var u = str.charCodeAt(i);\n if (u >= 55296 && u <= 57343) {\n var u1 = str.charCodeAt(++i);\n u = 65536 + ((u & 1023) << 10) | u1 & 1023;\n }\n if (u <= 127) {\n if (outIdx >= endIdx) break;\n heap[outIdx++] = u;\n } else if (u <= 2047) {\n if (outIdx + 1 >= endIdx) break;\n heap[outIdx++] = 192 | u >> 6;\n heap[outIdx++] = 128 | u & 63;\n } else if (u <= 65535) {\n if (outIdx + 2 >= endIdx) break;\n heap[outIdx++] = 224 | u >> 12;\n heap[outIdx++] = 128 | u >> 6 & 63;\n heap[outIdx++] = 128 | u & 63;\n } else {\n if (outIdx + 3 >= endIdx) break;\n if (u > 1114111)\n warnOnce(\n "Invalid Unicode code point " + ptrToString(u) + " encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF)."\n );\n heap[outIdx++] = 240 | u >> 18;\n heap[outIdx++] = 128 | u >> 12 & 63;\n heap[outIdx++] = 128 | u >> 6 & 63;\n heap[outIdx++] = 128 | u & 63;\n }\n }\n heap[outIdx] = 0;\n return outIdx - startIdx;\n };\n function intArrayFromString(stringy, dontAddNull, length) {\n var len = lengthBytesUTF8(stringy) + 1;\n var u8array = new Array(len);\n var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);\n u8array.length = numBytesWritten;\n return u8array;\n }\n var FS_stdin_getChar = () => {\n if (!FS_stdin_getChar_buffer.length) {\n var result = null;\n if (typeof window != "undefined" && typeof window.prompt == "function") {\n result = window.prompt("Input: ");\n if (result !== null) {\n result += "\\n";\n }\n } else if (typeof readline == "function") {\n result = readline();\n if (result) {\n result += "\\n";\n }\n } else ;\n if (!result) {\n return null;\n }\n FS_stdin_getChar_buffer = intArrayFromString(result);\n }\n return FS_stdin_getChar_buffer.shift();\n };\n var TTY = {\n ttys: [],\n init() {\n },\n shutdown() {\n },\n register(dev, ops) {\n TTY.ttys[dev] = { input: [], output: [], ops };\n FS.registerDevice(dev, TTY.stream_ops);\n },\n stream_ops: {\n open(stream) {\n var tty = TTY.ttys[stream.node.rdev];\n if (!tty) {\n throw new FS.ErrnoError(43);\n }\n stream.tty = tty;\n stream.seekable = false;\n },\n close(stream) {\n stream.tty.ops.fsync(stream.tty);\n },\n fsync(stream) {\n stream.tty.ops.fsync(stream.tty);\n },\n read(stream, buffer, offset, length, pos) {\n if (!stream.tty || !stream.tty.ops.get_char) {\n throw new FS.ErrnoError(60);\n }\n var bytesRead = 0;\n for (var i = 0; i < length; i++) {\n var result;\n try {\n result = stream.tty.ops.get_char(stream.tty);\n } catch (e) {\n throw new FS.ErrnoError(29);\n }\n if (result === void 0 && bytesRead === 0) {\n throw new FS.ErrnoError(6);\n }\n if (result === null || result === void 0) break;\n bytesRead++;\n buffer[offset + i] = result;\n }\n if (bytesRead) {\n stream.node.timestamp = Date.now();\n }\n return bytesRead;\n },\n write(stream, buffer, offset, length, pos) {\n if (!stream.tty || !stream.tty.ops.put_char) {\n throw new FS.ErrnoError(60);\n }\n try {\n for (var i = 0; i < length; i++) {\n stream.tty.ops.put_char(stream.tty, buffer[offset + i]);\n }\n } catch (e) {\n throw new FS.ErrnoError(29);\n }\n if (length) {\n stream.node.timestamp = Date.now();\n }\n return i;\n }\n },\n default_tty_ops: {\n get_char(tty) {\n return FS_stdin_getChar();\n },\n put_char(tty, val) {\n if (val === null || val === 10) {\n out(UTF8ArrayToString(tty.output));\n tty.output = [];\n } else {\n if (val != 0) tty.output.push(val);\n }\n },\n fsync(tty) {\n if (tty.output && tty.output.length > 0) {\n out(UTF8ArrayToString(tty.output));\n tty.output = [];\n }\n },\n ioctl_tcgets(tty) {\n return {\n c_iflag: 25856,\n c_oflag: 5,\n c_cflag: 191,\n c_lflag: 35387,\n c_cc: [\n 3,\n 28,\n 127,\n 21,\n 4,\n 0,\n 1,\n 0,\n 17,\n 19,\n 26,\n 0,\n 18,\n 15,\n 23,\n 22,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0\n ]\n };\n },\n ioctl_tcsets(tty, optional_actions, data) {\n return 0;\n },\n ioctl_tiocgwinsz(tty) {\n return [24, 80];\n }\n },\n default_tty1_ops: {\n put_char(tty, val) {\n if (val === null || val === 10) {\n err(UTF8ArrayToString(tty.output));\n tty.output = [];\n } else {\n if (val != 0) tty.output.push(val);\n }\n },\n fsync(tty) {\n if (tty.output && tty.output.length > 0) {\n err(UTF8ArrayToString(tty.output));\n tty.output = [];\n }\n }\n }\n };\n var zeroMemory = (address, size) => {\n HEAPU8.fill(0, address, address + size);\n };\n var alignMemory = (size, alignment) => {\n assert(alignment, "alignment argument is required");\n return Math.ceil(size / alignment) * alignment;\n };\n var mmapAlloc = (size) => {\n size = alignMemory(size, 65536);\n var ptr = _emscripten_builtin_memalign(65536, size);\n if (ptr) zeroMemory(ptr, size);\n return ptr;\n };\n var MEMFS = {\n ops_table: null,\n mount(mount) {\n return MEMFS.createNode(null, "/", 16384 | 511, 0);\n },\n createNode(parent, name, mode, dev) {\n if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {\n throw new FS.ErrnoError(63);\n }\n MEMFS.ops_table || (MEMFS.ops_table = {\n dir: {\n node: {\n getattr: MEMFS.node_ops.getattr,\n setattr: MEMFS.node_ops.setattr,\n lookup: MEMFS.node_ops.lookup,\n mknod: MEMFS.node_ops.mknod,\n rename: MEMFS.node_ops.rename,\n unlink: MEMFS.node_ops.unlink,\n rmdir: MEMFS.node_ops.rmdir,\n readdir: MEMFS.node_ops.readdir,\n symlink: MEMFS.node_ops.symlink\n },\n stream: {\n llseek: MEMFS.stream_ops.llseek\n }\n },\n file: {\n node: {\n getattr: MEMFS.node_ops.getattr,\n setattr: MEMFS.node_ops.setattr\n },\n stream: {\n llseek: MEMFS.stream_ops.llseek,\n read: MEMFS.stream_ops.read,\n write: MEMFS.stream_ops.write,\n allocate: MEMFS.stream_ops.allocate,\n mmap: MEMFS.stream_ops.mmap,\n msync: MEMFS.stream_ops.msync\n }\n },\n link: {\n node: {\n getattr: MEMFS.node_ops.getattr,\n setattr: MEMFS.node_ops.setattr,\n readlink: MEMFS.node_ops.readlink\n },\n stream: {}\n },\n chrdev: {\n node: {\n getattr: MEMFS.node_ops.getattr,\n setattr: MEMFS.node_ops.setattr\n },\n stream: FS.chrdev_stream_ops\n }\n });\n var node = FS.createNode(parent, name, mode, dev);\n if (FS.isDir(node.mode)) {\n node.node_ops = MEMFS.ops_table.dir.node;\n node.stream_ops = MEMFS.ops_table.dir.stream;\n node.contents = {};\n } else if (FS.isFile(node.mode)) {\n node.node_ops = MEMFS.ops_table.file.node;\n node.stream_ops = MEMFS.ops_table.file.stream;\n node.usedBytes = 0;\n node.contents = null;\n } else if (FS.isLink(node.mode)) {\n node.node_ops = MEMFS.ops_table.link.node;\n node.stream_ops = MEMFS.ops_table.link.stream;\n } else if (FS.isChrdev(node.mode)) {\n node.node_ops = MEMFS.ops_table.chrdev.node;\n node.stream_ops = MEMFS.ops_table.chrdev.stream;\n }\n node.timestamp = Date.now();\n if (parent) {\n parent.contents[name] = node;\n parent.timestamp = node.timestamp;\n }\n return node;\n },\n getFileDataAsTypedArray(node) {\n if (!node.contents) return new Uint8Array(0);\n if (node.contents.subarray) return node.contents.subarray(0, node.usedBytes);\n return new Uint8Array(node.contents);\n },\n expandFileStorage(node, newCapacity) {\n var prevCapacity = node.contents ? node.contents.length : 0;\n if (prevCapacity >= newCapacity) return;\n var CAPACITY_DOUBLING_MAX = 1024 * 1024;\n newCapacity = Math.max(\n newCapacity,\n prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2 : 1.125) >>> 0\n );\n if (prevCapacity != 0) newCapacity = Math.max(newCapacity, 256);\n var oldContents = node.contents;\n node.contents = new Uint8Array(newCapacity);\n if (node.usedBytes > 0) node.contents.set(oldContents.subarray(0, node.usedBytes), 0);\n },\n resizeFileStorage(node, newSize) {\n if (node.usedBytes == newSize) return;\n if (newSize == 0) {\n node.contents = null;\n node.usedBytes = 0;\n } else {\n var oldContents = node.contents;\n node.contents = new Uint8Array(newSize);\n if (oldContents) {\n node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes)));\n }\n node.usedBytes = newSize;\n }\n },\n node_ops: {\n getattr(node) {\n var attr = {};\n attr.dev = FS.isChrdev(node.mode) ? node.id : 1;\n attr.ino = node.id;\n attr.mode = node.mode;\n attr.nlink = 1;\n attr.uid = 0;\n attr.gid = 0;\n attr.rdev = node.rdev;\n if (FS.isDir(node.mode)) {\n attr.size = 4096;\n } else if (FS.isFile(node.mode)) {\n attr.size = node.usedBytes;\n } else if (FS.isLink(node.mode)) {\n attr.size = node.link.length;\n } else {\n attr.size = 0;\n }\n attr.atime = new Date(node.timestamp);\n attr.mtime = new Date(node.timestamp);\n attr.ctime = new Date(node.timestamp);\n attr.blksize = 4096;\n attr.blocks = Math.ceil(attr.size / attr.blksize);\n return attr;\n },\n setattr(node, attr) {\n if (attr.mode !== void 0) {\n node.mode = attr.mode;\n }\n if (attr.timestamp !== void 0) {\n node.timestamp = attr.timestamp;\n }\n if (attr.size !== void 0) {\n MEMFS.resizeFileStorage(node, attr.size);\n }\n },\n lookup(parent, name) {\n throw FS.genericErrors[44];\n },\n mknod(parent, name, mode, dev) {\n return MEMFS.createNode(parent, name, mode, dev);\n },\n rename(old_node, new_dir, new_name) {\n if (FS.isDir(old_node.mode)) {\n var new_node;\n try {\n new_node = FS.lookupNode(new_dir, new_name);\n } catch (e) {\n }\n if (new_node) {\n for (var i in new_node.contents) {\n throw new FS.ErrnoError(55);\n }\n }\n }\n delete old_node.parent.contents[old_node.name];\n old_node.parent.timestamp = Date.now();\n old_node.name = new_name;\n new_dir.contents[new_name] = old_node;\n new_dir.timestamp = old_node.parent.timestamp;\n },\n unlink(parent, name) {\n delete parent.contents[name];\n parent.timestamp = Date.now();\n },\n rmdir(parent, name) {\n var node = FS.lookupNode(parent, name);\n for (var i in node.contents) {\n throw new FS.ErrnoError(55);\n }\n delete parent.contents[name];\n parent.timestamp = Date.now();\n },\n readdir(node) {\n var entries = [".", ".."];\n for (var key of Object.keys(node.contents)) {\n entries.push(key);\n }\n return entries;\n },\n symlink(parent, newname, oldpath) {\n var node = MEMFS.createNode(parent, newname, 511 | 40960, 0);\n node.link = oldpath;\n return node;\n },\n readlink(node) {\n if (!FS.isLink(node.mode)) {\n throw new FS.ErrnoError(28);\n }\n return node.link;\n }\n },\n stream_ops: {\n read(stream, buffer, offset, length, position) {\n var contents = stream.node.contents;\n if (position >= stream.node.usedBytes) return 0;\n var size = Math.min(stream.node.usedBytes - position, length);\n assert(size >= 0);\n if (size > 8 && contents.subarray) {\n buffer.set(contents.subarray(position, position + size), offset);\n } else {\n for (var i = 0; i < size; i++) buffer[offset + i] = contents[position + i];\n }\n return size;\n },\n write(stream, buffer, offset, length, position, canOwn) {\n assert(!(buffer instanceof ArrayBuffer));\n if (buffer.buffer === HEAP8.buffer) {\n canOwn = false;\n }\n if (!length) return 0;\n var node = stream.node;\n node.timestamp = Date.now();\n if (buffer.subarray && (!node.contents || node.contents.subarray)) {\n if (canOwn) {\n assert(position === 0, "canOwn must imply no weird position inside the file");\n node.contents = buffer.subarray(offset, offset + length);\n node.usedBytes = length;\n return length;\n } else if (node.usedBytes === 0 && position === 0) {\n node.contents = buffer.slice(offset, offset + length);\n node.usedBytes = length;\n return length;\n } else if (position + length <= node.usedBytes) {\n node.contents.set(buffer.subarray(offset, offset + length), position);\n return length;\n }\n }\n MEMFS.expandFileStorage(node, position + length);\n if (node.contents.subarray && buffer.subarray) {\n node.contents.set(buffer.subarray(offset, offset + length), position);\n } else {\n for (var i = 0; i < length; i++) {\n node.contents[position + i] = buffer[offset + i];\n }\n }\n node.usedBytes = Math.max(node.usedBytes, position + length);\n return length;\n },\n llseek(stream, offset, whence) {\n var position = offset;\n if (whence === 1) {\n position += stream.position;\n } else if (whence === 2) {\n if (FS.isFile(stream.node.mode)) {\n position += stream.node.usedBytes;\n }\n }\n if (position < 0) {\n throw new FS.ErrnoError(28);\n }\n return position;\n },\n allocate(stream, offset, length) {\n MEMFS.expandFileStorage(stream.node, offset + length);\n stream.node.usedBytes = Math.max(stream.node.usedBytes, offset + length);\n },\n mmap(stream, length, position, prot, flags) {\n if (!FS.isFile(stream.node.mode)) {\n throw new FS.ErrnoError(43);\n }\n var ptr;\n var allocated;\n var contents = stream.node.contents;\n if (!(flags & 2) && contents && contents.buffer === HEAP8.buffer) {\n allocated = false;\n ptr = contents.byteOffset;\n } else {\n allocated = true;\n ptr = mmapAlloc(length);\n if (!ptr) {\n throw new FS.ErrnoError(48);\n }\n if (contents) {\n if (position > 0 || position + length < contents.length) {\n if (contents.subarray) {\n contents = contents.subarray(position, position + length);\n } else {\n contents = Array.prototype.slice.call(contents, position, position + length);\n }\n }\n HEAP8.set(contents, ptr);\n }\n }\n return { ptr, allocated };\n },\n msync(stream, buffer, offset, length, mmapFlags) {\n MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false);\n return 0;\n }\n }\n };\n var asyncLoad = (url, onload, onerror, noRunDep) => {\n var dep = getUniqueRunDependency(`al ${url}`);\n readAsync(url).then(\n (arrayBuffer) => {\n assert(arrayBuffer, `Loading data file "${url}" failed (no arrayBuffer).`);\n onload(new Uint8Array(arrayBuffer));\n if (dep) removeRunDependency(dep);\n },\n (err2) => {\n if (onerror) {\n onerror();\n } else {\n throw `Loading data file "${url}" failed.`;\n }\n }\n );\n if (dep) addRunDependency(dep);\n };\n var FS_createDataFile = (parent, name, fileData, canRead, canWrite, canOwn) => {\n FS.createDataFile(parent, name, fileData, canRead, canWrite, canOwn);\n };\n var preloadPlugins = Module["preloadPlugins"] || [];\n var FS_handledByPreloadPlugin = (byteArray, fullname, finish, onerror) => {\n if (typeof Browser != "undefined") Browser.init();\n var handled = false;\n preloadPlugins.forEach((plugin) => {\n if (handled) return;\n if (plugin["canHandle"](fullname)) {\n plugin["handle"](byteArray, fullname, finish, onerror);\n handled = true;\n }\n });\n return handled;\n };\n var FS_createPreloadedFile = (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) => {\n var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent;\n var dep = getUniqueRunDependency(`cp ${fullname}`);\n function processData(byteArray) {\n function finish(byteArray2) {\n preFinish == null ? void 0 : preFinish();\n if (!dontCreateFile) {\n FS_createDataFile(parent, name, byteArray2, canRead, canWrite, canOwn);\n }\n onload == null ? void 0 : onload();\n removeRunDependency(dep);\n }\n if (FS_handledByPreloadPlugin(byteArray, fullname, finish, () => {\n onerror == null ? void 0 : onerror();\n removeRunDependency(dep);\n })) {\n return;\n }\n finish(byteArray);\n }\n addRunDependency(dep);\n if (typeof url == "string") {\n asyncLoad(url, processData, onerror);\n } else {\n processData(url);\n }\n };\n var FS_modeStringToFlags = (str) => {\n var flagModes = {\n r: 0,\n "r+": 2,\n w: 512 | 64 | 1,\n "w+": 512 | 64 | 2,\n a: 1024 | 64 | 1,\n "a+": 1024 | 64 | 2\n };\n var flags = flagModes[str];\n if (typeof flags == "undefined") {\n throw new Error(`Unknown file open mode: ${str}`);\n }\n return flags;\n };\n var FS_getMode = (canRead, canWrite) => {\n var mode = 0;\n if (canRead) mode |= 292 | 73;\n if (canWrite) mode |= 146;\n return mode;\n };\n var strError = (errno) => {\n return UTF8ToString(_strerror(errno));\n };\n var ERRNO_CODES = {\n EPERM: 63,\n ENOENT: 44,\n ESRCH: 71,\n EINTR: 27,\n EIO: 29,\n ENXIO: 60,\n E2BIG: 1,\n ENOEXEC: 45,\n EBADF: 8,\n ECHILD: 12,\n EAGAIN: 6,\n EWOULDBLOCK: 6,\n ENOMEM: 48,\n EACCES: 2,\n EFAULT: 21,\n ENOTBLK: 105,\n EBUSY: 10,\n EEXIST: 20,\n EXDEV: 75,\n ENODEV: 43,\n ENOTDIR: 54,\n EISDIR: 31,\n EINVAL: 28,\n ENFILE: 41,\n EMFILE: 33,\n ENOTTY: 59,\n ETXTBSY: 74,\n EFBIG: 22,\n ENOSPC: 51,\n ESPIPE: 70,\n EROFS: 69,\n EMLINK: 34,\n EPIPE: 64,\n EDOM: 18,\n ERANGE: 68,\n ENOMSG: 49,\n EIDRM: 24,\n ECHRNG: 106,\n EL2NSYNC: 156,\n EL3HLT: 107,\n EL3RST: 108,\n ELNRNG: 109,\n EUNATCH: 110,\n ENOCSI: 111,\n EL2HLT: 112,\n EDEADLK: 16,\n ENOLCK: 46,\n EBADE: 113,\n EBADR: 114,\n EXFULL: 115,\n ENOANO: 104,\n EBADRQC: 103,\n EBADSLT: 102,\n EDEADLOCK: 16,\n EBFONT: 101,\n ENOSTR: 100,\n ENODATA: 116,\n ETIME: 117,\n ENOSR: 118,\n ENONET: 119,\n ENOPKG: 120,\n EREMOTE: 121,\n ENOLINK: 47,\n EADV: 122,\n ESRMNT: 123,\n ECOMM: 124,\n EPROTO: 65,\n EMULTIHOP: 36,\n EDOTDOT: 125,\n EBADMSG: 9,\n ENOTUNIQ: 126,\n EBADFD: 127,\n EREMCHG: 128,\n ELIBACC: 129,\n ELIBBAD: 130,\n ELIBSCN: 131,\n ELIBMAX: 132,\n ELIBEXEC: 133,\n ENOSYS: 52,\n ENOTEMPTY: 55,\n ENAMETOOLONG: 37,\n ELOOP: 32,\n EOPNOTSUPP: 138,\n EPFNOSUPPORT: 139,\n ECONNRESET: 15,\n ENOBUFS: 42,\n EAFNOSUPPORT: 5,\n EPROTOTYPE: 67,\n ENOTSOCK: 57,\n ENOPROTOOPT: 50,\n ESHUTDOWN: 140,\n ECONNREFUSED: 14,\n EADDRINUSE: 3,\n ECONNABORTED: 13,\n ENETUNREACH: 40,\n ENETDOWN: 38,\n ETIMEDOUT: 73,\n EHOSTDOWN: 142,\n EHOSTUNREACH: 23,\n EINPROGRESS: 26,\n EALREADY: 7,\n EDESTADDRREQ: 17,\n EMSGSIZE: 35,\n EPROTONOSUPPORT: 66,\n ESOCKTNOSUPPORT: 137,\n EADDRNOTAVAIL: 4,\n ENETRESET: 39,\n EISCONN: 30,\n ENOTCONN: 53,\n ETOOMANYREFS: 141,\n EUSERS: 136,\n EDQUOT: 19,\n ESTALE: 72,\n ENOTSUP: 138,\n ENOMEDIUM: 148,\n EILSEQ: 25,\n EOVERFLOW: 61,\n ECANCELED: 11,\n ENOTRECOVERABLE: 56,\n EOWNERDEAD: 62,\n ESTRPIPE: 135\n };\n var FS = {\n root: null,\n mounts: [],\n devices: {},\n streams: [],\n nextInode: 1,\n nameTable: null,\n currentPath: "/",\n initialized: false,\n ignorePermissions: true,\n ErrnoError: class extends Error {\n // We set the `name` property to be able to identify `FS.ErrnoError`\n // - the `name` is a standard ECMA-262 property of error objects. Kind of good to have it anyway.\n // - when using PROXYFS, an error can come from an underlying FS\n // as different FS objects have their own FS.ErrnoError each,\n // the test `err instanceof FS.ErrnoError` won\'t detect an error coming from another filesystem, causing bugs.\n // we\'ll use the reliable test `err.name == "ErrnoError"` instead\n constructor(errno) {\n super(runtimeInitialized ? strError(errno) : "");\n this.name = "ErrnoError";\n this.errno = errno;\n for (var key in ERRNO_CODES) {\n if (ERRNO_CODES[key] === errno) {\n this.code = key;\n break;\n }\n }\n }\n },\n genericErrors: {},\n filesystems: null,\n syncFSRequests: 0,\n readFiles: {},\n FSStream: class {\n constructor() {\n this.shared = {};\n }\n get object() {\n return this.node;\n }\n set object(val) {\n this.node = val;\n }\n get isRead() {\n return (this.flags & 2097155) !== 1;\n }\n get isWrite() {\n return (this.flags & 2097155) !== 0;\n }\n get isAppend() {\n return this.flags & 1024;\n }\n get flags() {\n return this.shared.flags;\n }\n set flags(val) {\n this.shared.flags = val;\n }\n get position() {\n return this.shared.position;\n }\n set position(val) {\n this.shared.position = val;\n }\n },\n FSNode: class {\n constructor(parent, name, mode, rdev) {\n if (!parent) {\n parent = this;\n }\n this.parent = parent;\n this.mount = parent.mount;\n this.mounted = null;\n this.id = FS.nextInode++;\n this.name = name;\n this.mode = mode;\n this.node_ops = {};\n this.stream_ops = {};\n this.rdev = rdev;\n this.readMode = 292 | 73;\n this.writeMode = 146;\n }\n get read() {\n return (this.mode & this.readMode) === this.readMode;\n }\n set read(val) {\n val ? this.mode |= this.readMode : this.mode &= ~this.readMode;\n }\n get write() {\n return (this.mode & this.writeMode) === this.writeMode;\n }\n set write(val) {\n val ? this.mode |= this.writeMode : this.mode &= ~this.writeMode;\n }\n get isFolder() {\n return FS.isDir(this.mode);\n }\n get isDevice() {\n return FS.isChrdev(this.mode);\n }\n },\n lookupPath(path, opts = {}) {\n path = PATH_FS.resolve(path);\n if (!path) return { path: "", node: null };\n var defaults = {\n follow_mount: true,\n recurse_count: 0\n };\n opts = Object.assign(defaults, opts);\n if (opts.recurse_count > 8) {\n throw new FS.ErrnoError(32);\n }\n var parts = path.split("/").filter((p) => !!p);\n var current = FS.root;\n var current_path = "/";\n for (var i = 0; i < parts.length; i++) {\n var islast = i === parts.length - 1;\n if (islast && opts.parent) {\n break;\n }\n current = FS.lookupNode(current, parts[i]);\n current_path = PATH.join2(current_path, parts[i]);\n if (FS.isMountpoint(current)) {\n if (!islast || islast && opts.follow_mount) {\n current = current.mounted.root;\n }\n }\n if (!islast || opts.follow) {\n var count = 0;\n while (FS.isLink(current.mode)) {\n var link = FS.readlink(current_path);\n current_path = PATH_FS.resolve(PATH.dirname(current_path), link);\n var lookup = FS.lookupPath(current_path, { recurse_count: opts.recurse_count + 1 });\n current = lookup.node;\n if (count++ > 40) {\n throw new FS.ErrnoError(32);\n }\n }\n }\n }\n return { path: current_path, node: current };\n },\n getPath(node) {\n var path;\n while (true) {\n if (FS.isRoot(node)) {\n var mount = node.mount.mountpoint;\n if (!path) return mount;\n return mount[mount.length - 1] !== "/" ? `${mount}/${path}` : mount + path;\n }\n path = path ? `${node.name}/${path}` : node.name;\n node = node.parent;\n }\n },\n hashName(parentid, name) {\n var hash = 0;\n for (var i = 0; i < name.length; i++) {\n hash = (hash << 5) - hash + name.charCodeAt(i) | 0;\n }\n return (parentid + hash >>> 0) % FS.nameTable.length;\n },\n hashAddNode(node) {\n var hash = FS.hashName(node.parent.id, node.name);\n node.name_next = FS.nameTable[hash];\n FS.nameTable[hash] = node;\n },\n hashRemoveNode(node) {\n var hash = FS.hashName(node.parent.id, node.name);\n if (FS.nameTable[hash] === node) {\n FS.nameTable[hash] = node.name_next;\n } else {\n var current = FS.nameTable[hash];\n while (current) {\n if (current.name_next === node) {\n current.name_next = node.name_next;\n break;\n }\n current = current.name_next;\n }\n }\n },\n lookupNode(parent, name) {\n var errCode = FS.mayLookup(parent);\n if (errCode) {\n throw new FS.ErrnoError(errCode);\n }\n var hash = FS.hashName(parent.id, name);\n for (var node = FS.nameTable[hash]; node; node = node.name_next) {\n var nodeName = node.name;\n if (node.parent.id === parent.id && nodeName === name) {\n return node;\n }\n }\n return FS.lookup(parent, name);\n },\n createNode(parent, name, mode, rdev) {\n assert(typeof parent == "object");\n var node = new FS.FSNode(parent, name, mode, rdev);\n FS.hashAddNode(node);\n return node;\n },\n destroyNode(node) {\n FS.hashRemoveNode(node);\n },\n isRoot(node) {\n return node === node.parent;\n },\n isMountpoint(node) {\n return !!node.mounted;\n },\n isFile(mode) {\n return (mode & 61440) === 32768;\n },\n isDir(mode) {\n return (mode & 61440) === 16384;\n },\n isLink(mode) {\n return (mode & 61440) === 40960;\n },\n isChrdev(mode) {\n return (mode & 61440) === 8192;\n },\n isBlkdev(mode) {\n return (mode & 61440) === 24576;\n },\n isFIFO(mode) {\n return (mode & 61440) === 4096;\n },\n isSocket(mode) {\n return (mode & 49152) === 49152;\n },\n flagsToPermissionString(flag) {\n var perms = ["r", "w", "rw"][flag & 3];\n if (flag & 512) {\n perms += "w";\n }\n return perms;\n },\n nodePermissions(node, perms) {\n if (FS.ignorePermissions) {\n return 0;\n }\n if (perms.includes("r") && !(node.mode & 292)) {\n return 2;\n } else if (perms.includes("w") && !(node.mode & 146)) {\n return 2;\n } else if (perms.includes("x") && !(node.mode & 73)) {\n return 2;\n }\n return 0;\n },\n mayLookup(dir) {\n if (!FS.isDir(dir.mode)) return 54;\n var errCode = FS.nodePermissions(dir, "x");\n if (errCode) return errCode;\n if (!dir.node_ops.lookup) return 2;\n return 0;\n },\n mayCreate(dir, name) {\n try {\n var node = FS.lookupNode(dir, name);\n return 20;\n } catch (e) {\n }\n return FS.nodePermissions(dir, "wx");\n },\n mayDelete(dir, name, isdir) {\n var node;\n try {\n node = FS.lookupNode(dir, name);\n } catch (e) {\n return e.errno;\n }\n var errCode = FS.nodePermissions(dir, "wx");\n if (errCode) {\n return errCode;\n }\n if (isdir) {\n if (!FS.isDir(node.mode)) {\n return 54;\n }\n if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {\n return 10;\n }\n } else {\n if (FS.isDir(node.mode)) {\n return 31;\n }\n }\n return 0;\n },\n mayOpen(node, flags) {\n if (!node) {\n return 44;\n }\n if (FS.isLink(node.mode)) {\n return 32;\n } else if (FS.isDir(node.mode)) {\n if (FS.flagsToPermissionString(flags) !== "r" || // opening for write\n flags & 512) {\n return 31;\n }\n }\n return FS.nodePermissions(node, FS.flagsToPermissionString(flags));\n },\n MAX_OPEN_FDS: 4096,\n nextfd() {\n for (var fd = 0; fd <= FS.MAX_OPEN_FDS; fd++) {\n if (!FS.streams[fd]) {\n return fd;\n }\n }\n throw new FS.ErrnoError(33);\n },\n getStreamChecked(fd) {\n var stream = FS.getStream(fd);\n if (!stream) {\n throw new FS.ErrnoError(8);\n }\n return stream;\n },\n getStream: (fd) => FS.streams[fd],\n createStream(stream, fd = -1) {\n assert(fd >= -1);\n stream = Object.assign(new FS.FSStream(), stream);\n if (fd == -1) {\n fd = FS.nextfd();\n }\n stream.fd = fd;\n FS.streams[fd] = stream;\n return stream;\n },\n closeStream(fd) {\n FS.streams[fd] = null;\n },\n dupStream(origStream, fd = -1) {\n var _a, _b;\n var stream = FS.createStream(origStream, fd);\n (_b = (_a = stream.stream_ops) == null ? void 0 : _a.dup) == null ? void 0 : _b.call(_a, stream);\n return stream;\n },\n chrdev_stream_ops: {\n open(stream) {\n var _a, _b;\n var device = FS.getDevice(stream.node.rdev);\n stream.stream_ops = device.stream_ops;\n (_b = (_a = stream.stream_ops).open) == null ? void 0 : _b.call(_a, stream);\n },\n llseek() {\n throw new FS.ErrnoError(70);\n }\n },\n major: (dev) => dev >> 8,\n minor: (dev) => dev & 255,\n makedev: (ma, mi) => ma << 8 | mi,\n registerDevice(dev, ops) {\n FS.devices[dev] = { stream_ops: ops };\n },\n getDevice: (dev) => FS.devices[dev],\n getMounts(mount) {\n var mounts = [];\n var check = [mount];\n while (check.length) {\n var m = check.pop();\n mounts.push(m);\n check.push(...m.mounts);\n }\n return mounts;\n },\n syncfs(populate, callback) {\n if (typeof populate == "function") {\n callback = populate;\n populate = false;\n }\n FS.syncFSRequests++;\n if (FS.syncFSRequests > 1) {\n err(\n `warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`\n );\n }\n var mounts = FS.getMounts(FS.root.mount);\n var completed = 0;\n function doCallback(errCode) {\n assert(FS.syncFSRequests > 0);\n FS.syncFSRequests--;\n return callback(errCode);\n }\n function done(errCode) {\n if (errCode) {\n if (!done.errored) {\n done.errored = true;\n return doCallback(errCode);\n }\n return;\n }\n if (++completed >= mounts.length) {\n doCallback(null);\n }\n }\n mounts.forEach((mount) => {\n if (!mount.type.syncfs) {\n return done(null);\n }\n mount.type.syncfs(mount, populate, done);\n });\n },\n mount(type, opts, mountpoint) {\n if (typeof type == "string") {\n throw type;\n }\n var root = mountpoint === "/";\n var pseudo = !mountpoint;\n var node;\n if (root && FS.root) {\n throw new FS.ErrnoError(10);\n } else if (!root && !pseudo) {\n var lookup = FS.lookupPath(mountpoint, { follow_mount: false });\n mountpoint = lookup.path;\n node = lookup.node;\n if (FS.isMountpoint(node)) {\n throw new FS.ErrnoError(10);\n }\n if (!FS.isDir(node.mode)) {\n throw new FS.ErrnoError(54);\n }\n }\n var mount = {\n type,\n opts,\n mountpoint,\n mounts: []\n };\n var mountRoot = type.mount(mount);\n mountRoot.mount = mount;\n mount.root = mountRoot;\n if (root) {\n FS.root = mountRoot;\n } else if (node) {\n node.mounted = mount;\n if (node.mount) {\n node.mount.mounts.push(mount);\n }\n }\n return mountRoot;\n },\n unmount(mountpoint) {\n var lookup = FS.lookupPath(mountpoint, { follow_mount: false });\n if (!FS.isMountpoint(lookup.node)) {\n throw new FS.ErrnoError(28);\n }\n var node = lookup.node;\n var mount = node.mounted;\n var mounts = FS.getMounts(mount);\n Object.keys(FS.nameTable).forEach((hash) => {\n var current = FS.nameTable[hash];\n while (current) {\n var next = current.name_next;\n if (mounts.includes(current.mount)) {\n FS.destroyNode(current);\n }\n current = next;\n }\n });\n node.mounted = null;\n var idx = node.mount.mounts.indexOf(mount);\n assert(idx !== -1);\n node.mount.mounts.splice(idx, 1);\n },\n lookup(parent, name) {\n return parent.node_ops.lookup(parent, name);\n },\n mknod(path, mode, dev) {\n var lookup = FS.lookupPath(path, { parent: true });\n var parent = lookup.node;\n var name = PATH.basename(path);\n if (!name || name === "." || name === "..") {\n throw new FS.ErrnoError(28);\n }\n var errCode = FS.mayCreate(parent, name);\n if (errCode) {\n throw new FS.ErrnoError(errCode);\n }\n if (!parent.node_ops.mknod) {\n throw new FS.ErrnoError(63);\n }\n return parent.node_ops.mknod(parent, name, mode, dev);\n },\n create(path, mode) {\n mode = mode !== void 0 ? mode : 438;\n mode &= 4095;\n mode |= 32768;\n return FS.mknod(path, mode, 0);\n },\n mkdir(path, mode) {\n mode = mode !== void 0 ? mode : 511;\n mode &= 511 | 512;\n mode |= 16384;\n return FS.mknod(path, mode, 0);\n },\n mkdirTree(path, mode) {\n var dirs = path.split("/");\n var d = "";\n for (var i = 0; i < dirs.length; ++i) {\n if (!dirs[i]) continue;\n d += "/" + dirs[i];\n try {\n FS.mkdir(d, mode);\n } catch (e) {\n if (e.errno != 20) throw e;\n }\n }\n },\n mkdev(path, mode, dev) {\n if (typeof dev == "undefined") {\n dev = mode;\n mode = 438;\n }\n mode |= 8192;\n return FS.mknod(path, mode, dev);\n },\n symlink(oldpath, newpath) {\n if (!PATH_FS.resolve(oldpath)) {\n throw new FS.ErrnoError(44);\n }\n var lookup = FS.lookupPath(newpath, { parent: true });\n var parent = lookup.node;\n if (!parent) {\n throw new FS.ErrnoError(44);\n }\n var newname = PATH.basename(newpath);\n var errCode = FS.mayCreate(parent, newname);\n if (errCode) {\n throw new FS.ErrnoError(errCode);\n }\n if (!parent.node_ops.symlink) {\n throw new FS.ErrnoError(63);\n }\n return parent.node_ops.symlink(parent, newname, oldpath);\n },\n rename(old_path, new_path) {\n var old_dirname = PATH.dirname(old_path);\n var new_dirname = PATH.dirname(new_path);\n var old_name = PATH.basename(old_path);\n var new_name = PATH.basename(new_path);\n var lookup, old_dir, new_dir;\n lookup = FS.lookupPath(old_path, { parent: true });\n old_dir = lookup.node;\n lookup = FS.lookupPath(new_path, { parent: true });\n new_dir = lookup.node;\n if (!old_dir || !new_dir) throw new FS.ErrnoError(44);\n if (old_dir.mount !== new_dir.mount) {\n throw new FS.ErrnoError(75);\n }\n var old_node = FS.lookupNode(old_dir, old_name);\n var relative = PATH_FS.relative(old_path, new_dirname);\n if (relative.charAt(0) !== ".") {\n throw new FS.ErrnoError(28);\n }\n relative = PATH_FS.relative(new_path, old_dirname);\n if (relative.charAt(0) !== ".") {\n throw new FS.ErrnoError(55);\n }\n var new_node;\n try {\n new_node = FS.lookupNode(new_dir, new_name);\n } catch (e) {\n }\n if (old_node === new_node) {\n return;\n }\n var isdir = FS.isDir(old_node.mode);\n var errCode = FS.mayDelete(old_dir, old_name, isdir);\n if (errCode) {\n throw new FS.ErrnoError(errCode);\n }\n errCode = new_node ? FS.mayDelete(new_dir, new_name, isdir) : FS.mayCreate(new_dir, new_name);\n if (errCode) {\n throw new FS.ErrnoError(errCode);\n }\n if (!old_dir.node_ops.rename) {\n throw new FS.ErrnoError(63);\n }\n if (FS.isMountpoint(old_node) || new_node && FS.isMountpoint(new_node)) {\n throw new FS.ErrnoError(10);\n }\n if (new_dir !== old_dir) {\n errCode = FS.nodePermissions(old_dir, "w");\n if (errCode) {\n throw new FS.ErrnoError(errCode);\n }\n }\n FS.hashRemoveNode(old_node);\n try {\n old_dir.node_ops.rename(old_node, new_dir, new_name);\n old_node.parent = new_dir;\n } catch (e) {\n throw e;\n } finally {\n FS.hashAddNode(old_node);\n }\n },\n rmdir(path) {\n var lookup = FS.lookupPath(path, { parent: true });\n var parent = lookup.node;\n var name = PATH.basename(path);\n var node = FS.lookupNode(parent, name);\n var errCode = FS.mayDelete(parent, name, true);\n if (errCode) {\n throw new FS.ErrnoError(errCode);\n }\n if (!parent.node_ops.rmdir) {\n throw new FS.ErrnoError(63);\n }\n if (FS.isMountpoint(node)) {\n throw new FS.ErrnoError(10);\n }\n parent.node_ops.rmdir(parent, name);\n FS.destroyNode(node);\n },\n readdir(path) {\n var lookup = FS.lookupPath(path, { follow: true });\n var node = lookup.node;\n if (!node.node_ops.readdir) {\n throw new FS.ErrnoError(54);\n }\n return node.node_ops.readdir(node);\n },\n unlink(path) {\n var lookup = FS.lookupPath(path, { parent: true });\n var parent = lookup.node;\n if (!parent) {\n throw new FS.ErrnoError(44);\n }\n var name = PATH.basename(path);\n var node = FS.lookupNode(parent, name);\n var errCode = FS.mayDelete(parent, name, false);\n if (errCode) {\n throw new FS.ErrnoError(errCode);\n }\n if (!parent.node_ops.unlink) {\n throw new FS.ErrnoError(63);\n }\n if (FS.isMountpoint(node)) {\n throw new FS.ErrnoError(10);\n }\n parent.node_ops.unlink(parent, name);\n FS.destroyNode(node);\n },\n readlink(path) {\n var lookup = FS.lookupPath(path);\n var link = lookup.node;\n if (!link) {\n throw new FS.ErrnoError(44);\n }\n if (!link.node_ops.readlink) {\n throw new FS.ErrnoError(28);\n }\n return PATH_FS.resolve(FS.getPath(link.parent), link.node_ops.readlink(link));\n },\n stat(path, dontFollow) {\n var lookup = FS.lookupPath(path, { follow: !dontFollow });\n var node = lookup.node;\n if (!node) {\n throw new FS.ErrnoError(44);\n }\n if (!node.node_ops.getattr) {\n throw new FS.ErrnoError(63);\n }\n return node.node_ops.getattr(node);\n },\n lstat(path) {\n return FS.stat(path, true);\n },\n chmod(path, mode, dontFollow) {\n var node;\n if (typeof path == "string") {\n var lookup = FS.lookupPath(path, { follow: !dontFollow });\n node = lookup.node;\n } else {\n node = path;\n }\n if (!node.node_ops.setattr) {\n throw new FS.ErrnoError(63);\n }\n node.node_ops.setattr(node, {\n mode: mode & 4095 | node.mode & -4096,\n timestamp: Date.now()\n });\n },\n lchmod(path, mode) {\n FS.chmod(path, mode, true);\n },\n fchmod(fd, mode) {\n var stream = FS.getStreamChecked(fd);\n FS.chmod(stream.node, mode);\n },\n chown(path, uid, gid, dontFollow) {\n var node;\n if (typeof path == "string") {\n var lookup = FS.lookupPath(path, { follow: !dontFollow });\n node = lookup.node;\n } else {\n node = path;\n }\n if (!node.node_ops.setattr) {\n throw new FS.ErrnoError(63);\n }\n node.node_ops.setattr(node, {\n timestamp: Date.now()\n // we ignore the uid / gid for now\n });\n },\n lchown(path, uid, gid) {\n FS.chown(path, uid, gid, true);\n },\n fchown(fd, uid, gid) {\n var stream = FS.getStreamChecked(fd);\n FS.chown(stream.node, uid, gid);\n },\n truncate(path, len) {\n if (len < 0) {\n throw new FS.ErrnoError(28);\n }\n var node;\n if (typeof path == "string") {\n var lookup = FS.lookupPath(path, { follow: true });\n node = lookup.node;\n } else {\n node = path;\n }\n if (!node.node_ops.setattr) {\n throw new FS.ErrnoError(63);\n }\n if (FS.isDir(node.mode)) {\n throw new FS.ErrnoError(31);\n }\n if (!FS.isFile(node.mode)) {\n throw new FS.ErrnoError(28);\n }\n var errCode = FS.nodePermissions(node, "w");\n if (errCode) {\n throw new FS.ErrnoError(errCode);\n }\n node.node_ops.setattr(node, {\n size: len,\n timestamp: Date.now()\n });\n },\n ftruncate(fd, len) {\n var stream = FS.getStreamChecked(fd);\n if ((stream.flags & 2097155) === 0) {\n throw new FS.ErrnoError(28);\n }\n FS.truncate(stream.node, len);\n },\n utime(path, atime, mtime) {\n var lookup = FS.lookupPath(path, { follow: true });\n var node = lookup.node;\n node.node_ops.setattr(node, {\n timestamp: Math.max(atime, mtime)\n });\n },\n open(path, flags, mode) {\n if (path === "") {\n throw new FS.ErrnoError(44);\n }\n flags = typeof flags == "string" ? FS_modeStringToFlags(flags) : flags;\n if (flags & 64) {\n mode = typeof mode == "undefined" ? 438 : mode;\n mode = mode & 4095 | 32768;\n } else {\n mode = 0;\n }\n var node;\n if (typeof path == "object") {\n node = path;\n } else {\n path = PATH.normalize(path);\n try {\n var lookup = FS.lookupPath(path, {\n follow: !(flags & 131072)\n });\n node = lookup.node;\n } catch (e) {\n }\n }\n var created = false;\n if (flags & 64) {\n if (node) {\n if (flags & 128) {\n throw new FS.ErrnoError(20);\n }\n } else {\n node = FS.mknod(path, mode, 0);\n created = true;\n }\n }\n if (!node) {\n throw new FS.ErrnoError(44);\n }\n if (FS.isChrdev(node.mode)) {\n flags &= -513;\n }\n if (flags & 65536 && !FS.isDir(node.mode)) {\n throw new FS.ErrnoError(54);\n }\n if (!created) {\n var errCode = FS.mayOpen(node, flags);\n if (errCode) {\n throw new FS.ErrnoError(errCode);\n }\n }\n if (flags & 512 && !created) {\n FS.truncate(node, 0);\n }\n flags &= -131713;\n var stream = FS.createStream({\n node,\n path: FS.getPath(node),\n // we want the absolute path to the node\n flags,\n seekable: true,\n position: 0,\n stream_ops: node.stream_ops,\n // used by the file family libc calls (fopen, fwrite, ferror, etc.)\n ungotten: [],\n error: false\n });\n if (stream.stream_ops.open) {\n stream.stream_ops.open(stream);\n }\n if (Module["logReadFiles"] && !(flags & 1)) {\n if (!(path in FS.readFiles)) {\n FS.readFiles[path] = 1;\n }\n }\n return stream;\n },\n close(stream) {\n if (FS.isClosed(stream)) {\n throw new FS.ErrnoError(8);\n }\n if (stream.getdents) stream.getdents = null;\n try {\n if (stream.stream_ops.close) {\n stream.stream_ops.close(stream);\n }\n } catch (e) {\n throw e;\n } finally {\n FS.closeStream(stream.fd);\n }\n stream.fd = null;\n },\n isClosed(stream) {\n return stream.fd === null;\n },\n llseek(stream, offset, whence) {\n if (FS.isClosed(stream)) {\n throw new FS.ErrnoError(8);\n }\n if (!stream.seekable || !stream.stream_ops.llseek) {\n throw new FS.ErrnoError(70);\n }\n if (whence != 0 && whence != 1 && whence != 2) {\n throw new FS.ErrnoError(28);\n }\n stream.position = stream.stream_ops.llseek(stream, offset, whence);\n stream.ungotten = [];\n return stream.position;\n },\n read(stream, buffer, offset, length, position) {\n assert(offset >= 0);\n if (length < 0 || position < 0) {\n throw new FS.ErrnoError(28);\n }\n if (FS.isClosed(stream)) {\n throw new FS.ErrnoError(8);\n }\n if ((stream.flags & 2097155) === 1) {\n throw new FS.ErrnoError(8);\n }\n if (FS.isDir(stream.node.mode)) {\n throw new FS.ErrnoError(31);\n }\n if (!stream.stream_ops.read) {\n throw new FS.ErrnoError(28);\n }\n var seeking = typeof position != "undefined";\n if (!seeking) {\n position = stream.position;\n } else if (!stream.seekable) {\n throw new FS.ErrnoError(70);\n }\n var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);\n if (!seeking) stream.position += bytesRead;\n return bytesRead;\n },\n write(stream, buffer, offset, length, position, canOwn) {\n assert(offset >= 0);\n if (length < 0 || position < 0) {\n throw new FS.ErrnoError(28);\n }\n if (FS.isClosed(stream)) {\n throw new FS.ErrnoError(8);\n }\n if ((stream.flags & 2097155) === 0) {\n throw new FS.ErrnoError(8);\n }\n if (FS.isDir(stream.node.mode)) {\n throw new FS.ErrnoError(31);\n }\n if (!stream.stream_ops.write) {\n throw new FS.ErrnoError(28);\n }\n if (stream.seekable && stream.flags & 1024) {\n FS.llseek(stream, 0, 2);\n }\n var seeking = typeof position != "undefined";\n if (!seeking) {\n position = stream.position;\n } else if (!stream.seekable) {\n throw new FS.ErrnoError(70);\n }\n var bytesWritten = stream.stream_ops.write(\n stream,\n buffer,\n offset,\n length,\n position,\n canOwn\n );\n if (!seeking) stream.position += bytesWritten;\n return bytesWritten;\n },\n allocate(stream, offset, length) {\n if (FS.isClosed(stream)) {\n throw new FS.ErrnoError(8);\n }\n if (offset < 0 || length <= 0) {\n throw new FS.ErrnoError(28);\n }\n if ((stream.flags & 2097155) === 0) {\n throw new FS.ErrnoError(8);\n }\n if (!FS.isFile(stream.node.mode) && !FS.isDir(stream.node.mode)) {\n throw new FS.ErrnoError(43);\n }\n if (!stream.stream_ops.allocate) {\n throw new FS.ErrnoError(138);\n }\n stream.stream_ops.allocate(stream, offset, length);\n },\n mmap(stream, length, position, prot, flags) {\n if ((prot & 2) !== 0 && (flags & 2) === 0 && (stream.flags & 2097155) !== 2) {\n throw new FS.ErrnoError(2);\n }\n if ((stream.flags & 2097155) === 1) {\n throw new FS.ErrnoError(2);\n }\n if (!stream.stream_ops.mmap) {\n throw new FS.ErrnoError(43);\n }\n if (!length) {\n throw new FS.ErrnoError(28);\n }\n return stream.stream_ops.mmap(stream, length, position, prot, flags);\n },\n msync(stream, buffer, offset, length, mmapFlags) {\n assert(offset >= 0);\n if (!stream.stream_ops.msync) {\n return 0;\n }\n return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags);\n },\n ioctl(stream, cmd, arg) {\n if (!stream.stream_ops.ioctl) {\n throw new FS.ErrnoError(59);\n }\n return stream.stream_ops.ioctl(stream, cmd, arg);\n },\n readFile(path, opts = {}) {\n opts.flags = opts.flags || 0;\n opts.encoding = opts.encoding || "binary";\n if (opts.encoding !== "utf8" && opts.encoding !== "binary") {\n throw new Error(`Invalid encoding type "${opts.encoding}"`);\n }\n var ret;\n var stream = FS.open(path, opts.flags);\n var stat = FS.stat(path);\n var length = stat.size;\n var buf = new Uint8Array(length);\n FS.read(stream, buf, 0, length, 0);\n if (opts.encoding === "utf8") {\n ret = UTF8ArrayToString(buf);\n } else if (opts.encoding === "binary") {\n ret = buf;\n }\n FS.close(stream);\n return ret;\n },\n writeFile(path, data, opts = {}) {\n opts.flags = opts.flags || 577;\n var stream = FS.open(path, opts.flags, opts.mode);\n if (typeof data == "string") {\n var buf = new Uint8Array(lengthBytesUTF8(data) + 1);\n var actualNumBytes = stringToUTF8Array(data, buf, 0, buf.length);\n FS.write(stream, buf, 0, actualNumBytes, void 0, opts.canOwn);\n } else if (ArrayBuffer.isView(data)) {\n FS.write(stream, data, 0, data.byteLength, void 0, opts.canOwn);\n } else {\n throw new Error("Unsupported data type");\n }\n FS.close(stream);\n },\n cwd: () => FS.currentPath,\n chdir(path) {\n var lookup = FS.lookupPath(path, { follow: true });\n if (lookup.node === null) {\n throw new FS.ErrnoError(44);\n }\n if (!FS.isDir(lookup.node.mode)) {\n throw new FS.ErrnoError(54);\n }\n var errCode = FS.nodePermissions(lookup.node, "x");\n if (errCode) {\n throw new FS.ErrnoError(errCode);\n }\n FS.currentPath = lookup.path;\n },\n createDefaultDirectories() {\n FS.mkdir("/tmp");\n FS.mkdir("/home");\n FS.mkdir("/home/web_user");\n },\n createDefaultDevices() {\n FS.mkdir("/dev");\n FS.registerDevice(FS.makedev(1, 3), {\n read: () => 0,\n write: (stream, buffer, offset, length, pos) => length\n });\n FS.mkdev("/dev/null", FS.makedev(1, 3));\n TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);\n TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);\n FS.mkdev("/dev/tty", FS.makedev(5, 0));\n FS.mkdev("/dev/tty1", FS.makedev(6, 0));\n var randomBuffer = new Uint8Array(1024), randomLeft = 0;\n var randomByte = () => {\n if (randomLeft === 0) {\n randomLeft = randomFill(randomBuffer).byteLength;\n }\n return randomBuffer[--randomLeft];\n };\n FS.createDevice("/dev", "random", randomByte);\n FS.createDevice("/dev", "urandom", randomByte);\n FS.mkdir("/dev/shm");\n FS.mkdir("/dev/shm/tmp");\n },\n createSpecialDirectories() {\n FS.mkdir("/proc");\n var proc_self = FS.mkdir("/proc/self");\n FS.mkdir("/proc/self/fd");\n FS.mount(\n {\n mount() {\n var node = FS.createNode(proc_self, "fd", 16384 | 511, 73);\n node.node_ops = {\n lookup(parent, name) {\n var fd = +name;\n var stream = FS.getStreamChecked(fd);\n var ret = {\n parent: null,\n mount: { mountpoint: "fake" },\n node_ops: { readlink: () => stream.path }\n };\n ret.parent = ret;\n return ret;\n }\n };\n return node;\n }\n },\n {},\n "/proc/self/fd"\n );\n },\n createStandardStreams(input, output, error) {\n if (input) {\n FS.createDevice("/dev", "stdin", input);\n } else {\n FS.symlink("/dev/tty", "/dev/stdin");\n }\n if (output) {\n FS.createDevice("/dev", "stdout", null, output);\n } else {\n FS.symlink("/dev/tty", "/dev/stdout");\n }\n if (error) {\n FS.createDevice("/dev", "stderr", null, error);\n } else {\n FS.symlink("/dev/tty1", "/dev/stderr");\n }\n var stdin = FS.open("/dev/stdin", 0);\n var stdout = FS.open("/dev/stdout", 1);\n var stderr = FS.open("/dev/stderr", 1);\n assert(stdin.fd === 0, `invalid handle for stdin (${stdin.fd})`);\n assert(stdout.fd === 1, `invalid handle for stdout (${stdout.fd})`);\n assert(stderr.fd === 2, `invalid handle for stderr (${stderr.fd})`);\n },\n staticInit() {\n [44].forEach((code) => {\n FS.genericErrors[code] = new FS.ErrnoError(code);\n FS.genericErrors[code].stack = "";\n });\n FS.nameTable = new Array(4096);\n FS.mount(MEMFS, {}, "/");\n FS.createDefaultDirectories();\n FS.createDefaultDevices();\n FS.createSpecialDirectories();\n FS.filesystems = {\n MEMFS\n };\n },\n init(input, output, error) {\n assert(\n !FS.initialized,\n "FS.init was previously called. If you want to initialize later with custom parameters, remove any earlier calls (note that one is automatically added to the generated code)"\n );\n FS.initialized = true;\n input ?? (input = Module["stdin"]);\n output ?? (output = Module["stdout"]);\n error ?? (error = Module["stderr"]);\n FS.createStandardStreams(input, output, error);\n },\n quit() {\n FS.initialized = false;\n _fflush(0);\n for (var i = 0; i < FS.streams.length; i++) {\n var stream = FS.streams[i];\n if (!stream) {\n continue;\n }\n FS.close(stream);\n }\n },\n findObject(path, dontResolveLastLink) {\n var ret = FS.analyzePath(path, dontResolveLastLink);\n if (!ret.exists) {\n return null;\n }\n return ret.object;\n },\n analyzePath(path, dontResolveLastLink) {\n try {\n var lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });\n path = lookup.path;\n } catch (e) {\n }\n var ret = {\n isRoot: false,\n exists: false,\n error: 0,\n name: null,\n path: null,\n object: null,\n parentExists: false,\n parentPath: null,\n parentObject: null\n };\n try {\n var lookup = FS.lookupPath(path, { parent: true });\n ret.parentExists = true;\n ret.parentPath = lookup.path;\n ret.parentObject = lookup.node;\n ret.name = PATH.basename(path);\n lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });\n ret.exists = true;\n ret.path = lookup.path;\n ret.object = lookup.node;\n ret.name = lookup.node.name;\n ret.isRoot = lookup.path === "/";\n } catch (e) {\n ret.error = e.errno;\n }\n return ret;\n },\n createPath(parent, path, canRead, canWrite) {\n parent = typeof parent == "string" ? parent : FS.getPath(parent);\n var parts = path.split("/").reverse();\n while (parts.length) {\n var part = parts.pop();\n if (!part) continue;\n var current = PATH.join2(parent, part);\n try {\n FS.mkdir(current);\n } catch (e) {\n }\n parent = current;\n }\n return current;\n },\n createFile(parent, name, properties, canRead, canWrite) {\n var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name);\n var mode = FS_getMode(canRead, canWrite);\n return FS.create(path, mode);\n },\n createDataFile(parent, name, data, canRead, canWrite, canOwn) {\n var path = name;\n if (parent) {\n parent = typeof parent == "string" ? parent : FS.getPath(parent);\n path = name ? PATH.join2(parent, name) : parent;\n }\n var mode = FS_getMode(canRead, canWrite);\n var node = FS.create(path, mode);\n if (data) {\n if (typeof data == "string") {\n var arr = new Array(data.length);\n for (var i = 0, len = data.length; i < len; ++i) arr[i] = data.charCodeAt(i);\n data = arr;\n }\n FS.chmod(node, mode | 146);\n var stream = FS.open(node, 577);\n FS.write(stream, data, 0, data.length, 0, canOwn);\n FS.close(stream);\n FS.chmod(node, mode);\n }\n },\n createDevice(parent, name, input, output) {\n var _a;\n var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name);\n var mode = FS_getMode(!!input, !!output);\n (_a = FS.createDevice).major ?? (_a.major = 64);\n var dev = FS.makedev(FS.createDevice.major++, 0);\n FS.registerDevice(dev, {\n open(stream) {\n stream.seekable = false;\n },\n close(stream) {\n var _a2;\n if ((_a2 = output == null ? void 0 : output.buffer) == null ? void 0 : _a2.length) {\n output(10);\n }\n },\n read(stream, buffer, offset, length, pos) {\n var bytesRead = 0;\n for (var i = 0; i < length; i++) {\n var result;\n try {\n result = input();\n } catch (e) {\n throw new FS.ErrnoError(29);\n }\n if (result === void 0 && bytesRead === 0) {\n throw new FS.ErrnoError(6);\n }\n if (result === null || result === void 0) break;\n bytesRead++;\n buffer[offset + i] = result;\n }\n if (bytesRead) {\n stream.node.timestamp = Date.now();\n }\n return bytesRead;\n },\n write(stream, buffer, offset, length, pos) {\n for (var i = 0; i < length; i++) {\n try {\n output(buffer[offset + i]);\n } catch (e) {\n throw new FS.ErrnoError(29);\n }\n }\n if (length) {\n stream.node.timestamp = Date.now();\n }\n return i;\n }\n });\n return FS.mkdev(path, mode, dev);\n },\n forceLoadFile(obj) {\n if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true;\n if (typeof XMLHttpRequest != "undefined") {\n throw new Error(\n "Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread."\n );\n } else {\n try {\n obj.contents = readBinary(obj.url);\n obj.usedBytes = obj.contents.length;\n } catch (e) {\n throw new FS.ErrnoError(29);\n }\n }\n },\n createLazyFile(parent, name, url, canRead, canWrite) {\n class LazyUint8Array {\n constructor() {\n this.lengthKnown = false;\n this.chunks = [];\n }\n get(idx) {\n if (idx > this.length - 1 || idx < 0) {\n return void 0;\n }\n var chunkOffset = idx % this.chunkSize;\n var chunkNum = idx / this.chunkSize | 0;\n return this.getter(chunkNum)[chunkOffset];\n }\n setDataGetter(getter) {\n this.getter = getter;\n }\n cacheLength() {\n var xhr = new XMLHttpRequest();\n xhr.open("HEAD", url, false);\n xhr.send(null);\n if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304))\n throw new Error("Couldn\'t load " + url + ". Status: " + xhr.status);\n var datalength = Number(xhr.getResponseHeader("Content-length"));\n var header;\n var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";\n var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip";\n var chunkSize = 1024 * 1024;\n if (!hasByteServing) chunkSize = datalength;\n var doXHR = (from, to) => {\n if (from > to)\n throw new Error("invalid range (" + from + ", " + to + ") or no bytes requested!");\n if (to > datalength - 1)\n throw new Error("only " + datalength + " bytes available! programmer error!");\n var xhr2 = new XMLHttpRequest();\n xhr2.open("GET", url, false);\n if (datalength !== chunkSize)\n xhr2.setRequestHeader("Range", "bytes=" + from + "-" + to);\n xhr2.responseType = "arraybuffer";\n if (xhr2.overrideMimeType) {\n xhr2.overrideMimeType("text/plain; charset=x-user-defined");\n }\n xhr2.send(null);\n if (!(xhr2.status >= 200 && xhr2.status < 300 || xhr2.status === 304))\n throw new Error("Couldn\'t load " + url + ". Status: " + xhr2.status);\n if (xhr2.response !== void 0) {\n return new Uint8Array(\n /** @type{Array} */\n xhr2.response || []\n );\n }\n return intArrayFromString(xhr2.responseText || "");\n };\n var lazyArray2 = this;\n lazyArray2.setDataGetter((chunkNum) => {\n var start = chunkNum * chunkSize;\n var end = (chunkNum + 1) * chunkSize - 1;\n end = Math.min(end, datalength - 1);\n if (typeof lazyArray2.chunks[chunkNum] == "undefined") {\n lazyArray2.chunks[chunkNum] = doXHR(start, end);\n }\n if (typeof lazyArray2.chunks[chunkNum] == "undefined")\n throw new Error("doXHR failed!");\n return lazyArray2.chunks[chunkNum];\n });\n if (usesGzip || !datalength) {\n chunkSize = datalength = 1;\n datalength = this.getter(0).length;\n chunkSize = datalength;\n out("LazyFiles on gzip forces download of the whole file when length is accessed");\n }\n this._length = datalength;\n this._chunkSize = chunkSize;\n this.lengthKnown = true;\n }\n get length() {\n if (!this.lengthKnown) {\n this.cacheLength();\n }\n return this._length;\n }\n get chunkSize() {\n if (!this.lengthKnown) {\n this.cacheLength();\n }\n return this._chunkSize;\n }\n }\n if (typeof XMLHttpRequest != "undefined") {\n if (!ENVIRONMENT_IS_WORKER)\n throw "Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";\n var lazyArray = new LazyUint8Array();\n var properties = { isDevice: false, contents: lazyArray };\n } else {\n var properties = { isDevice: false, url };\n }\n var node = FS.createFile(parent, name, properties, canRead, canWrite);\n if (properties.contents) {\n node.contents = properties.contents;\n } else if (properties.url) {\n node.contents = null;\n node.url = properties.url;\n }\n Object.defineProperties(node, {\n usedBytes: {\n get: function() {\n return this.contents.length;\n }\n }\n });\n var stream_ops = {};\n var keys = Object.keys(node.stream_ops);\n keys.forEach((key) => {\n var fn = node.stream_ops[key];\n stream_ops[key] = (...args) => {\n FS.forceLoadFile(node);\n return fn(...args);\n };\n });\n function writeChunks(stream, buffer, offset, length, position) {\n var contents = stream.node.contents;\n if (position >= contents.length) return 0;\n var size = Math.min(contents.length - position, length);\n assert(size >= 0);\n if (contents.slice) {\n for (var i = 0; i < size; i++) {\n buffer[offset + i] = contents[position + i];\n }\n } else {\n for (var i = 0; i < size; i++) {\n buffer[offset + i] = contents.get(position + i);\n }\n }\n return size;\n }\n stream_ops.read = (stream, buffer, offset, length, position) => {\n FS.forceLoadFile(node);\n return writeChunks(stream, buffer, offset, length, position);\n };\n stream_ops.mmap = (stream, length, position, prot, flags) => {\n FS.forceLoadFile(node);\n var ptr = mmapAlloc(length);\n if (!ptr) {\n throw new FS.ErrnoError(48);\n }\n writeChunks(stream, HEAP8, ptr, length, position);\n return { ptr, allocated: true };\n };\n node.stream_ops = stream_ops;\n return node;\n },\n absolutePath() {\n abort("FS.absolutePath has been removed; use PATH_FS.resolve instead");\n },\n createFolder() {\n abort("FS.createFolder has been removed; use FS.mkdir instead");\n },\n createLink() {\n abort("FS.createLink has been removed; use FS.symlink instead");\n },\n joinPath() {\n abort("FS.joinPath has been removed; use PATH.join instead");\n },\n mmapAlloc() {\n abort("FS.mmapAlloc has been replaced by the top level function mmapAlloc");\n },\n standardizePath() {\n abort("FS.standardizePath has been removed; use PATH.normalize instead");\n }\n };\n var SYSCALLS = {\n DEFAULT_POLLMASK: 5,\n calculateAt(dirfd, path, allowEmpty) {\n if (PATH.isAbs(path)) {\n return path;\n }\n var dir;\n if (dirfd === -100) {\n dir = FS.cwd();\n } else {\n var dirstream = SYSCALLS.getStreamFromFD(dirfd);\n dir = dirstream.path;\n }\n if (path.length == 0) {\n if (!allowEmpty) {\n throw new FS.ErrnoError(44);\n }\n return dir;\n }\n return PATH.join2(dir, path);\n },\n doStat(func, path, buf) {\n var stat = func(path);\n HEAP32[buf >> 2] = stat.dev;\n HEAP32[buf + 4 >> 2] = stat.mode;\n HEAPU32[buf + 8 >> 2] = stat.nlink;\n HEAP32[buf + 12 >> 2] = stat.uid;\n HEAP32[buf + 16 >> 2] = stat.gid;\n HEAP32[buf + 20 >> 2] = stat.rdev;\n tempI64 = [\n stat.size >>> 0,\n (tempDouble = stat.size, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)\n ], HEAP32[buf + 24 >> 2] = tempI64[0], HEAP32[buf + 28 >> 2] = tempI64[1];\n HEAP32[buf + 32 >> 2] = 4096;\n HEAP32[buf + 36 >> 2] = stat.blocks;\n var atime = stat.atime.getTime();\n var mtime = stat.mtime.getTime();\n var ctime = stat.ctime.getTime();\n tempI64 = [\n Math.floor(atime / 1e3) >>> 0,\n (tempDouble = Math.floor(atime / 1e3), +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)\n ], HEAP32[buf + 40 >> 2] = tempI64[0], HEAP32[buf + 44 >> 2] = tempI64[1];\n HEAPU32[buf + 48 >> 2] = atime % 1e3 * 1e3 * 1e3;\n tempI64 = [\n Math.floor(mtime / 1e3) >>> 0,\n (tempDouble = Math.floor(mtime / 1e3), +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)\n ], HEAP32[buf + 56 >> 2] = tempI64[0], HEAP32[buf + 60 >> 2] = tempI64[1];\n HEAPU32[buf + 64 >> 2] = mtime % 1e3 * 1e3 * 1e3;\n tempI64 = [\n Math.floor(ctime / 1e3) >>> 0,\n (tempDouble = Math.floor(ctime / 1e3), +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)\n ], HEAP32[buf + 72 >> 2] = tempI64[0], HEAP32[buf + 76 >> 2] = tempI64[1];\n HEAPU32[buf + 80 >> 2] = ctime % 1e3 * 1e3 * 1e3;\n tempI64 = [\n stat.ino >>> 0,\n (tempDouble = stat.ino, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)\n ], HEAP32[buf + 88 >> 2] = tempI64[0], HEAP32[buf + 92 >> 2] = tempI64[1];\n return 0;\n },\n doMsync(addr, stream, len, flags, offset) {\n if (!FS.isFile(stream.node.mode)) {\n throw new FS.ErrnoError(43);\n }\n if (flags & 2) {\n return 0;\n }\n var buffer = HEAPU8.slice(addr, addr + len);\n FS.msync(stream, buffer, offset, len, flags);\n },\n getStreamFromFD(fd) {\n var stream = FS.getStreamChecked(fd);\n return stream;\n },\n varargs: void 0,\n getStr(ptr) {\n var ret = UTF8ToString(ptr);\n return ret;\n }\n };\n function ___syscall_fcntl64(fd, cmd, varargs) {\n SYSCALLS.varargs = varargs;\n try {\n var stream = SYSCALLS.getStreamFromFD(fd);\n switch (cmd) {\n case 0: {\n var arg = syscallGetVarargI();\n if (arg < 0) {\n return -28;\n }\n while (FS.streams[arg]) {\n arg++;\n }\n var newStream;\n newStream = FS.dupStream(stream, arg);\n return newStream.fd;\n }\n case 1:\n case 2:\n return 0;\n // FD_CLOEXEC makes no sense for a single process.\n case 3:\n return stream.flags;\n case 4: {\n var arg = syscallGetVarargI();\n stream.flags |= arg;\n return 0;\n }\n case 12: {\n var arg = syscallGetVarargP();\n var offset = 0;\n HEAP16[arg + offset >> 1] = 2;\n return 0;\n }\n case 13:\n case 14:\n return 0;\n }\n return -28;\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return -e.errno;\n }\n }\n function ___syscall_fstat64(fd, buf) {\n try {\n var stream = SYSCALLS.getStreamFromFD(fd);\n return SYSCALLS.doStat(FS.stat, stream.path, buf);\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return -e.errno;\n }\n }\n var convertI32PairToI53Checked = (lo, hi) => {\n assert(lo == lo >>> 0 || lo == (lo | 0));\n assert(hi === (hi | 0));\n return hi + 2097152 >>> 0 < 4194305 - !!lo ? (lo >>> 0) + hi * 4294967296 : NaN;\n };\n function ___syscall_ftruncate64(fd, length_low, length_high) {\n var length = convertI32PairToI53Checked(length_low, length_high);\n try {\n if (isNaN(length)) return 61;\n FS.ftruncate(fd, length);\n return 0;\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return -e.errno;\n }\n }\n var stringToUTF8 = (str, outPtr, maxBytesToWrite) => {\n assert(\n typeof maxBytesToWrite == "number",\n "stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!"\n );\n return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);\n };\n function ___syscall_getdents64(fd, dirp, count) {\n try {\n var stream = SYSCALLS.getStreamFromFD(fd);\n stream.getdents || (stream.getdents = FS.readdir(stream.path));\n var struct_size = 280;\n var pos = 0;\n var off = FS.llseek(stream, 0, 1);\n var idx = Math.floor(off / struct_size);\n while (idx < stream.getdents.length && pos + struct_size <= count) {\n var id;\n var type;\n var name = stream.getdents[idx];\n if (name === ".") {\n id = stream.node.id;\n type = 4;\n } else if (name === "..") {\n var lookup = FS.lookupPath(stream.path, { parent: true });\n id = lookup.node.id;\n type = 4;\n } else {\n var child = FS.lookupNode(stream.node, name);\n id = child.id;\n type = FS.isChrdev(child.mode) ? 2 : FS.isDir(child.mode) ? 4 : FS.isLink(child.mode) ? 10 : 8;\n }\n assert(id);\n tempI64 = [\n id >>> 0,\n (tempDouble = id, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)\n ], HEAP32[dirp + pos >> 2] = tempI64[0], HEAP32[dirp + pos + 4 >> 2] = tempI64[1];\n tempI64 = [\n (idx + 1) * struct_size >>> 0,\n (tempDouble = (idx + 1) * struct_size, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)\n ], HEAP32[dirp + pos + 8 >> 2] = tempI64[0], HEAP32[dirp + pos + 12 >> 2] = tempI64[1];\n HEAP16[dirp + pos + 16 >> 1] = 280;\n HEAP8[dirp + pos + 18] = type;\n stringToUTF8(name, dirp + pos + 19, 256);\n pos += struct_size;\n idx += 1;\n }\n FS.llseek(stream, idx * struct_size, 0);\n return pos;\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return -e.errno;\n }\n }\n function ___syscall_ioctl(fd, op, varargs) {\n SYSCALLS.varargs = varargs;\n try {\n var stream = SYSCALLS.getStreamFromFD(fd);\n switch (op) {\n case 21509: {\n if (!stream.tty) return -59;\n return 0;\n }\n case 21505: {\n if (!stream.tty) return -59;\n if (stream.tty.ops.ioctl_tcgets) {\n var termios = stream.tty.ops.ioctl_tcgets(stream);\n var argp = syscallGetVarargP();\n HEAP32[argp >> 2] = termios.c_iflag || 0;\n HEAP32[argp + 4 >> 2] = termios.c_oflag || 0;\n HEAP32[argp + 8 >> 2] = termios.c_cflag || 0;\n HEAP32[argp + 12 >> 2] = termios.c_lflag || 0;\n for (var i = 0; i < 32; i++) {\n HEAP8[argp + i + 17] = termios.c_cc[i] || 0;\n }\n return 0;\n }\n return 0;\n }\n case 21510:\n case 21511:\n case 21512: {\n if (!stream.tty) return -59;\n return 0;\n }\n case 21506:\n case 21507:\n case 21508: {\n if (!stream.tty) return -59;\n if (stream.tty.ops.ioctl_tcsets) {\n var argp = syscallGetVarargP();\n var c_iflag = HEAP32[argp >> 2];\n var c_oflag = HEAP32[argp + 4 >> 2];\n var c_cflag = HEAP32[argp + 8 >> 2];\n var c_lflag = HEAP32[argp + 12 >> 2];\n var c_cc = [];\n for (var i = 0; i < 32; i++) {\n c_cc.push(HEAP8[argp + i + 17]);\n }\n return stream.tty.ops.ioctl_tcsets(stream.tty, op, {\n c_iflag,\n c_oflag,\n c_cflag,\n c_lflag,\n c_cc\n });\n }\n return 0;\n }\n case 21519: {\n if (!stream.tty) return -59;\n var argp = syscallGetVarargP();\n HEAP32[argp >> 2] = 0;\n return 0;\n }\n case 21520: {\n if (!stream.tty) return -59;\n return -28;\n }\n case 21531: {\n var argp = syscallGetVarargP();\n return FS.ioctl(stream, op, argp);\n }\n case 21523: {\n if (!stream.tty) return -59;\n if (stream.tty.ops.ioctl_tiocgwinsz) {\n var winsize = stream.tty.ops.ioctl_tiocgwinsz(stream.tty);\n var argp = syscallGetVarargP();\n HEAP16[argp >> 1] = winsize[0];\n HEAP16[argp + 2 >> 1] = winsize[1];\n }\n return 0;\n }\n case 21524: {\n if (!stream.tty) return -59;\n return 0;\n }\n case 21515: {\n if (!stream.tty) return -59;\n return 0;\n }\n default:\n return -28;\n }\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return -e.errno;\n }\n }\n function ___syscall_lstat64(path, buf) {\n try {\n path = SYSCALLS.getStr(path);\n return SYSCALLS.doStat(FS.lstat, path, buf);\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return -e.errno;\n }\n }\n function ___syscall_newfstatat(dirfd, path, buf, flags) {\n try {\n path = SYSCALLS.getStr(path);\n var nofollow = flags & 256;\n var allowEmpty = flags & 4096;\n flags = flags & ~6400;\n assert(!flags, `unknown flags in __syscall_newfstatat: ${flags}`);\n path = SYSCALLS.calculateAt(dirfd, path, allowEmpty);\n return SYSCALLS.doStat(nofollow ? FS.lstat : FS.stat, path, buf);\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return -e.errno;\n }\n }\n function ___syscall_openat(dirfd, path, flags, varargs) {\n SYSCALLS.varargs = varargs;\n try {\n path = SYSCALLS.getStr(path);\n path = SYSCALLS.calculateAt(dirfd, path);\n var mode = varargs ? syscallGetVarargI() : 0;\n return FS.open(path, flags, mode).fd;\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return -e.errno;\n }\n }\n function ___syscall_rmdir(path) {\n try {\n path = SYSCALLS.getStr(path);\n FS.rmdir(path);\n return 0;\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return -e.errno;\n }\n }\n function ___syscall_stat64(path, buf) {\n try {\n path = SYSCALLS.getStr(path);\n return SYSCALLS.doStat(FS.stat, path, buf);\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return -e.errno;\n }\n }\n function ___syscall_unlinkat(dirfd, path, flags) {\n try {\n path = SYSCALLS.getStr(path);\n path = SYSCALLS.calculateAt(dirfd, path);\n if (flags === 0) {\n FS.unlink(path);\n } else if (flags === 512) {\n FS.rmdir(path);\n } else {\n abort("Invalid flags passed to unlinkat");\n }\n return 0;\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return -e.errno;\n }\n }\n var __abort_js = () => {\n abort("native code called abort()");\n };\n var __emscripten_memcpy_js = (dest, src, num) => HEAPU8.copyWithin(dest, src, src + num);\n var __emscripten_throw_longjmp = () => {\n throw Infinity;\n };\n function __gmtime_js(time_low, time_high, tmPtr) {\n var time = convertI32PairToI53Checked(time_low, time_high);\n var date = new Date(time * 1e3);\n HEAP32[tmPtr >> 2] = date.getUTCSeconds();\n HEAP32[tmPtr + 4 >> 2] = date.getUTCMinutes();\n HEAP32[tmPtr + 8 >> 2] = date.getUTCHours();\n HEAP32[tmPtr + 12 >> 2] = date.getUTCDate();\n HEAP32[tmPtr + 16 >> 2] = date.getUTCMonth();\n HEAP32[tmPtr + 20 >> 2] = date.getUTCFullYear() - 1900;\n HEAP32[tmPtr + 24 >> 2] = date.getUTCDay();\n var start = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0);\n var yday = (date.getTime() - start) / (1e3 * 60 * 60 * 24) | 0;\n HEAP32[tmPtr + 28 >> 2] = yday;\n }\n var isLeapYear = (year) => year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n var MONTH_DAYS_LEAP_CUMULATIVE = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];\n var MONTH_DAYS_REGULAR_CUMULATIVE = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];\n var ydayFromDate = (date) => {\n var leap = isLeapYear(date.getFullYear());\n var monthDaysCumulative = leap ? MONTH_DAYS_LEAP_CUMULATIVE : MONTH_DAYS_REGULAR_CUMULATIVE;\n var yday = monthDaysCumulative[date.getMonth()] + date.getDate() - 1;\n return yday;\n };\n function __localtime_js(time_low, time_high, tmPtr) {\n var time = convertI32PairToI53Checked(time_low, time_high);\n var date = new Date(time * 1e3);\n HEAP32[tmPtr >> 2] = date.getSeconds();\n HEAP32[tmPtr + 4 >> 2] = date.getMinutes();\n HEAP32[tmPtr + 8 >> 2] = date.getHours();\n HEAP32[tmPtr + 12 >> 2] = date.getDate();\n HEAP32[tmPtr + 16 >> 2] = date.getMonth();\n HEAP32[tmPtr + 20 >> 2] = date.getFullYear() - 1900;\n HEAP32[tmPtr + 24 >> 2] = date.getDay();\n var yday = ydayFromDate(date) | 0;\n HEAP32[tmPtr + 28 >> 2] = yday;\n HEAP32[tmPtr + 36 >> 2] = -(date.getTimezoneOffset() * 60);\n var start = new Date(date.getFullYear(), 0, 1);\n var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();\n var winterOffset = start.getTimezoneOffset();\n var dst = (summerOffset != winterOffset && date.getTimezoneOffset() == Math.min(winterOffset, summerOffset)) | 0;\n HEAP32[tmPtr + 32 >> 2] = dst;\n }\n var __tzset_js = (timezone, daylight, std_name, dst_name) => {\n var currentYear = (/* @__PURE__ */ new Date()).getFullYear();\n var winter = new Date(currentYear, 0, 1);\n var summer = new Date(currentYear, 6, 1);\n var winterOffset = winter.getTimezoneOffset();\n var summerOffset = summer.getTimezoneOffset();\n var stdTimezoneOffset = Math.max(winterOffset, summerOffset);\n HEAPU32[timezone >> 2] = stdTimezoneOffset * 60;\n HEAP32[daylight >> 2] = Number(winterOffset != summerOffset);\n var extractZone = (timezoneOffset) => {\n var sign = timezoneOffset >= 0 ? "-" : "+";\n var absOffset = Math.abs(timezoneOffset);\n var hours = String(Math.floor(absOffset / 60)).padStart(2, "0");\n var minutes = String(absOffset % 60).padStart(2, "0");\n return `UTC${sign}${hours}${minutes}`;\n };\n var winterName = extractZone(winterOffset);\n var summerName = extractZone(summerOffset);\n assert(winterName);\n assert(summerName);\n assert(\n lengthBytesUTF8(winterName) <= 16,\n `timezone name truncated to fit in TZNAME_MAX (${winterName})`\n );\n assert(\n lengthBytesUTF8(summerName) <= 16,\n `timezone name truncated to fit in TZNAME_MAX (${summerName})`\n );\n if (summerOffset < winterOffset) {\n stringToUTF8(winterName, std_name, 17);\n stringToUTF8(summerName, dst_name, 17);\n } else {\n stringToUTF8(winterName, dst_name, 17);\n stringToUTF8(summerName, std_name, 17);\n }\n };\n var _emscripten_date_now = () => Date.now();\n var getHeapMax = () => (\n // Stay one Wasm page short of 4GB: while e.g. Chrome is able to allocate\n // full 4GB Wasm memories, the size will wrap back to 0 bytes in Wasm side\n // for any code that deals with heap sizes, which would require special\n // casing all heap size related code to treat 0 specially.\n 2147483648\n );\n var growMemory = (size) => {\n var b = wasmMemory.buffer;\n var pages = (size - b.byteLength + 65535) / 65536 | 0;\n try {\n wasmMemory.grow(pages);\n updateMemoryViews();\n return 1;\n } catch (e) {\n err(\n `growMemory: Attempted to grow heap from ${b.byteLength} bytes to ${size} bytes, but got error: ${e}`\n );\n }\n };\n var _emscripten_resize_heap = (requestedSize) => {\n var oldSize = HEAPU8.length;\n requestedSize >>>= 0;\n assert(requestedSize > oldSize);\n var maxHeapSize = getHeapMax();\n if (requestedSize > maxHeapSize) {\n err(\n `Cannot enlarge memory, requested ${requestedSize} bytes, but the limit is ${maxHeapSize} bytes!`\n );\n return false;\n }\n for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {\n var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);\n overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);\n var newSize = Math.min(\n maxHeapSize,\n alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536)\n );\n var replacement = growMemory(newSize);\n if (replacement) {\n return true;\n }\n }\n err(`Failed to grow the heap from ${oldSize} bytes to ${newSize} bytes, not enough memory!`);\n return false;\n };\n var ENV = {};\n var getExecutableName = () => {\n return thisProgram || "./this.program";\n };\n var getEnvStrings = () => {\n if (!getEnvStrings.strings) {\n var lang = (typeof navigator == "object" && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8";\n var env = {\n USER: "web_user",\n LOGNAME: "web_user",\n PATH: "/",\n PWD: "/",\n HOME: "/home/web_user",\n LANG: lang,\n _: getExecutableName()\n };\n for (var x in ENV) {\n if (ENV[x] === void 0) delete env[x];\n else env[x] = ENV[x];\n }\n var strings = [];\n for (var x in env) {\n strings.push(`${x}=${env[x]}`);\n }\n getEnvStrings.strings = strings;\n }\n return getEnvStrings.strings;\n };\n var stringToAscii = (str, buffer) => {\n for (var i = 0; i < str.length; ++i) {\n assert(str.charCodeAt(i) === (str.charCodeAt(i) & 255));\n HEAP8[buffer++] = str.charCodeAt(i);\n }\n HEAP8[buffer] = 0;\n };\n var _environ_get = (__environ, environ_buf) => {\n var bufSize = 0;\n getEnvStrings().forEach((string, i) => {\n var ptr = environ_buf + bufSize;\n HEAPU32[__environ + i * 4 >> 2] = ptr;\n stringToAscii(string, ptr);\n bufSize += string.length + 1;\n });\n return 0;\n };\n var _environ_sizes_get = (penviron_count, penviron_buf_size) => {\n var strings = getEnvStrings();\n HEAPU32[penviron_count >> 2] = strings.length;\n var bufSize = 0;\n strings.forEach((string) => bufSize += string.length + 1);\n HEAPU32[penviron_buf_size >> 2] = bufSize;\n return 0;\n };\n function _fd_close(fd) {\n try {\n var stream = SYSCALLS.getStreamFromFD(fd);\n FS.close(stream);\n return 0;\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return e.errno;\n }\n }\n var doReadv = (stream, iov, iovcnt, offset) => {\n var ret = 0;\n for (var i = 0; i < iovcnt; i++) {\n var ptr = HEAPU32[iov >> 2];\n var len = HEAPU32[iov + 4 >> 2];\n iov += 8;\n var curr = FS.read(stream, HEAP8, ptr, len, offset);\n if (curr < 0) return -1;\n ret += curr;\n if (curr < len) break;\n }\n return ret;\n };\n function _fd_read(fd, iov, iovcnt, pnum) {\n try {\n var stream = SYSCALLS.getStreamFromFD(fd);\n var num = doReadv(stream, iov, iovcnt);\n HEAPU32[pnum >> 2] = num;\n return 0;\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return e.errno;\n }\n }\n function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {\n var offset = convertI32PairToI53Checked(offset_low, offset_high);\n try {\n if (isNaN(offset)) return 61;\n var stream = SYSCALLS.getStreamFromFD(fd);\n FS.llseek(stream, offset, whence);\n tempI64 = [\n stream.position >>> 0,\n (tempDouble = stream.position, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)\n ], HEAP32[newOffset >> 2] = tempI64[0], HEAP32[newOffset + 4 >> 2] = tempI64[1];\n if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null;\n return 0;\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return e.errno;\n }\n }\n function _fd_sync(fd) {\n var _a;\n try {\n var stream = SYSCALLS.getStreamFromFD(fd);\n if ((_a = stream.stream_ops) == null ? void 0 : _a.fsync) {\n return stream.stream_ops.fsync(stream);\n }\n return 0;\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return e.errno;\n }\n }\n var doWritev = (stream, iov, iovcnt, offset) => {\n var ret = 0;\n for (var i = 0; i < iovcnt; i++) {\n var ptr = HEAPU32[iov >> 2];\n var len = HEAPU32[iov + 4 >> 2];\n iov += 8;\n var curr = FS.write(stream, HEAP8, ptr, len, offset);\n if (curr < 0) return -1;\n ret += curr;\n if (curr < len) {\n break;\n }\n }\n return ret;\n };\n function _fd_write(fd, iov, iovcnt, pnum) {\n try {\n var stream = SYSCALLS.getStreamFromFD(fd);\n var num = doWritev(stream, iov, iovcnt);\n HEAPU32[pnum >> 2] = num;\n return 0;\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return e.errno;\n }\n }\n var wasmTableMirror = [];\n var wasmTable;\n var getWasmTableEntry = (funcPtr) => {\n var func = wasmTableMirror[funcPtr];\n if (!func) {\n if (funcPtr >= wasmTableMirror.length) wasmTableMirror.length = funcPtr + 1;\n wasmTableMirror[funcPtr] = func = wasmTable.get(funcPtr);\n }\n assert(\n wasmTable.get(funcPtr) == func,\n "JavaScript-side Wasm function table mirror is out of date!"\n );\n return func;\n };\n var UTF16Decoder = typeof TextDecoder != "undefined" ? new TextDecoder("utf-16le") : void 0;\n var UTF16ToString = (ptr, maxBytesToRead) => {\n assert(ptr % 2 == 0, "Pointer passed to UTF16ToString must be aligned to two bytes!");\n var endPtr = ptr;\n var idx = endPtr >> 1;\n var maxIdx = idx + maxBytesToRead / 2;\n while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx;\n endPtr = idx << 1;\n if (endPtr - ptr > 32 && UTF16Decoder)\n return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr));\n var str = "";\n for (var i = 0; !(i >= maxBytesToRead / 2); ++i) {\n var codeUnit = HEAP16[ptr + i * 2 >> 1];\n if (codeUnit == 0) break;\n str += String.fromCharCode(codeUnit);\n }\n return str;\n };\n var uleb128Encode = (n, target) => {\n assert(n < 16384);\n if (n < 128) {\n target.push(n);\n } else {\n target.push(n % 128 | 128, n >> 7);\n }\n };\n var sigToWasmTypes = (sig) => {\n assert(\n !sig.includes("j"),\n "i64 not permitted in function signatures when WASM_BIGINT is disabled"\n );\n var typeNames = {\n i: "i32",\n j: "i64",\n f: "f32",\n d: "f64",\n e: "externref",\n p: "i32"\n };\n var type = {\n parameters: [],\n results: sig[0] == "v" ? [] : [typeNames[sig[0]]]\n };\n for (var i = 1; i < sig.length; ++i) {\n assert(sig[i] in typeNames, "invalid signature char: " + sig[i]);\n type.parameters.push(typeNames[sig[i]]);\n }\n return type;\n };\n var generateFuncType = (sig, target) => {\n var sigRet = sig.slice(0, 1);\n var sigParam = sig.slice(1);\n var typeCodes = {\n i: 127,\n // i32\n p: 127,\n // i32\n j: 126,\n // i64\n f: 125,\n // f32\n d: 124,\n // f64\n e: 111\n // externref\n };\n target.push(\n 96\n /* form: func */\n );\n uleb128Encode(sigParam.length, target);\n for (var i = 0; i < sigParam.length; ++i) {\n assert(sigParam[i] in typeCodes, "invalid signature char: " + sigParam[i]);\n target.push(typeCodes[sigParam[i]]);\n }\n if (sigRet == "v") {\n target.push(0);\n } else {\n target.push(1, typeCodes[sigRet]);\n }\n };\n var convertJsFunctionToWasm = (func, sig) => {\n assert(\n !sig.includes("j"),\n "i64 not permitted in function signatures when WASM_BIGINT is disabled"\n );\n if (typeof WebAssembly.Function == "function") {\n return new WebAssembly.Function(sigToWasmTypes(sig), func);\n }\n var typeSectionBody = [\n 1\n // count: 1\n ];\n generateFuncType(sig, typeSectionBody);\n var bytes = [\n 0,\n 97,\n 115,\n 109,\n // magic ("\\0asm")\n 1,\n 0,\n 0,\n 0,\n // version: 1\n 1\n // Type section code\n ];\n uleb128Encode(typeSectionBody.length, bytes);\n bytes.push(...typeSectionBody);\n bytes.push(\n 2,\n 7,\n // import section\n // (import "e" "f" (func 0 (type 0)))\n 1,\n 1,\n 101,\n 1,\n 102,\n 0,\n 0,\n 7,\n 5,\n // export section\n // (export "f" (func 0 (type 0)))\n 1,\n 1,\n 102,\n 0,\n 0\n );\n var module = new WebAssembly.Module(new Uint8Array(bytes));\n var instance = new WebAssembly.Instance(module, { e: { f: func } });\n var wrappedFunc = instance.exports["f"];\n return wrappedFunc;\n };\n var updateTableMap = (offset, count) => {\n if (functionsInTableMap) {\n for (var i = offset; i < offset + count; i++) {\n var item = getWasmTableEntry(i);\n if (item) {\n functionsInTableMap.set(item, i);\n }\n }\n }\n };\n var functionsInTableMap;\n var getFunctionAddress = (func) => {\n if (!functionsInTableMap) {\n functionsInTableMap = /* @__PURE__ */ new WeakMap();\n updateTableMap(0, wasmTable.length);\n }\n return functionsInTableMap.get(func) || 0;\n };\n var freeTableIndexes = [];\n var getEmptyTableSlot = () => {\n if (freeTableIndexes.length) {\n return freeTableIndexes.pop();\n }\n try {\n wasmTable.grow(1);\n } catch (err2) {\n if (!(err2 instanceof RangeError)) {\n throw err2;\n }\n throw "Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.";\n }\n return wasmTable.length - 1;\n };\n var setWasmTableEntry = (idx, func) => {\n wasmTable.set(idx, func);\n wasmTableMirror[idx] = wasmTable.get(idx);\n };\n var addFunction = (func, sig) => {\n assert(typeof func != "undefined");\n var rtn = getFunctionAddress(func);\n if (rtn) {\n return rtn;\n }\n var ret = getEmptyTableSlot();\n try {\n setWasmTableEntry(ret, func);\n } catch (err2) {\n if (!(err2 instanceof TypeError)) {\n throw err2;\n }\n assert(typeof sig != "undefined", "Missing signature argument to addFunction: " + func);\n var wrapped = convertJsFunctionToWasm(func, sig);\n setWasmTableEntry(ret, wrapped);\n }\n functionsInTableMap.set(func, ret);\n return ret;\n };\n var getCFunc = (ident) => {\n var func = Module["_" + ident];\n assert(func, "Cannot call unknown function " + ident + ", make sure it is exported");\n return func;\n };\n var writeArrayToMemory = (array, buffer) => {\n assert(\n array.length >= 0,\n "writeArrayToMemory array must have a length (should be an array or typed array)"\n );\n HEAP8.set(array, buffer);\n };\n var stackAlloc = (sz) => __emscripten_stack_alloc(sz);\n var stringToUTF8OnStack = (str) => {\n var size = lengthBytesUTF8(str) + 1;\n var ret = stackAlloc(size);\n stringToUTF8(str, ret, size);\n return ret;\n };\n var ccall = (ident, returnType, argTypes, args, opts) => {\n var toC = {\n string: (str) => {\n var ret2 = 0;\n if (str !== null && str !== void 0 && str !== 0) {\n ret2 = stringToUTF8OnStack(str);\n }\n return ret2;\n },\n array: (arr) => {\n var ret2 = stackAlloc(arr.length);\n writeArrayToMemory(arr, ret2);\n return ret2;\n }\n };\n function convertReturnValue(ret2) {\n if (returnType === "string") {\n return UTF8ToString(ret2);\n }\n if (returnType === "boolean") return Boolean(ret2);\n return ret2;\n }\n var func = getCFunc(ident);\n var cArgs = [];\n var stack = 0;\n assert(returnType !== "array", \'Return type should not be "array".\');\n if (args) {\n for (var i = 0; i < args.length; i++) {\n var converter = toC[argTypes[i]];\n if (converter) {\n if (stack === 0) stack = stackSave();\n cArgs[i] = converter(args[i]);\n } else {\n cArgs[i] = args[i];\n }\n }\n }\n var ret = func(...cArgs);\n function onDone(ret2) {\n if (stack !== 0) stackRestore(stack);\n return convertReturnValue(ret2);\n }\n ret = onDone(ret);\n return ret;\n };\n var cwrap = (ident, returnType, argTypes, opts) => {\n return (...args) => ccall(ident, returnType, argTypes, args);\n };\n var removeFunction = (index) => {\n functionsInTableMap.delete(getWasmTableEntry(index));\n setWasmTableEntry(index, null);\n freeTableIndexes.push(index);\n };\n var stringToUTF16 = (str, outPtr, maxBytesToWrite) => {\n assert(outPtr % 2 == 0, "Pointer passed to stringToUTF16 must be aligned to two bytes!");\n assert(\n typeof maxBytesToWrite == "number",\n "stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!"\n );\n maxBytesToWrite ?? (maxBytesToWrite = 2147483647);\n if (maxBytesToWrite < 2) return 0;\n maxBytesToWrite -= 2;\n var startPtr = outPtr;\n var numCharsToWrite = maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length;\n for (var i = 0; i < numCharsToWrite; ++i) {\n var codeUnit = str.charCodeAt(i);\n HEAP16[outPtr >> 1] = codeUnit;\n outPtr += 2;\n }\n HEAP16[outPtr >> 1] = 0;\n return outPtr - startPtr;\n };\n FS.createPreloadedFile = FS_createPreloadedFile;\n FS.staticInit();\n function checkIncomingModuleAPI() {\n ignoredModuleProp("fetchSettings");\n }\n var wasmImports = {\n /** @export */\n __assert_fail: ___assert_fail,\n /** @export */\n __syscall_fcntl64: ___syscall_fcntl64,\n /** @export */\n __syscall_fstat64: ___syscall_fstat64,\n /** @export */\n __syscall_ftruncate64: ___syscall_ftruncate64,\n /** @export */\n __syscall_getdents64: ___syscall_getdents64,\n /** @export */\n __syscall_ioctl: ___syscall_ioctl,\n /** @export */\n __syscall_lstat64: ___syscall_lstat64,\n /** @export */\n __syscall_newfstatat: ___syscall_newfstatat,\n /** @export */\n __syscall_openat: ___syscall_openat,\n /** @export */\n __syscall_rmdir: ___syscall_rmdir,\n /** @export */\n __syscall_stat64: ___syscall_stat64,\n /** @export */\n __syscall_unlinkat: ___syscall_unlinkat,\n /** @export */\n _abort_js: __abort_js,\n /** @export */\n _emscripten_memcpy_js: __emscripten_memcpy_js,\n /** @export */\n _emscripten_throw_longjmp: __emscripten_throw_longjmp,\n /** @export */\n _gmtime_js: __gmtime_js,\n /** @export */\n _localtime_js: __localtime_js,\n /** @export */\n _tzset_js: __tzset_js,\n /** @export */\n emscripten_date_now: _emscripten_date_now,\n /** @export */\n emscripten_resize_heap: _emscripten_resize_heap,\n /** @export */\n environ_get: _environ_get,\n /** @export */\n environ_sizes_get: _environ_sizes_get,\n /** @export */\n fd_close: _fd_close,\n /** @export */\n fd_read: _fd_read,\n /** @export */\n fd_seek: _fd_seek,\n /** @export */\n fd_sync: _fd_sync,\n /** @export */\n fd_write: _fd_write,\n /** @export */\n invoke_ii,\n /** @export */\n invoke_iii,\n /** @export */\n invoke_iiii,\n /** @export */\n invoke_iiiii,\n /** @export */\n invoke_v,\n /** @export */\n invoke_vii,\n /** @export */\n invoke_viii,\n /** @export */\n invoke_viiii,\n /** @export */\n invoke_viiiiiiiii\n };\n var wasmExports = createWasm();\n Module["_PDFiumExt_Init"] = createExportWrapper("PDFiumExt_Init", 0);\n Module["_FPDF_InitLibraryWithConfig"] = createExportWrapper(\n "FPDF_InitLibraryWithConfig",\n 1\n );\n Module["_PDFiumExt_OpenFileWriter"] = createExportWrapper(\n "PDFiumExt_OpenFileWriter",\n 0\n );\n Module["_PDFiumExt_GetFileWriterSize"] = createExportWrapper("PDFiumExt_GetFileWriterSize", 1);\n Module["_PDFiumExt_GetFileWriterData"] = createExportWrapper("PDFiumExt_GetFileWriterData", 3);\n Module["_PDFiumExt_CloseFileWriter"] = createExportWrapper(\n "PDFiumExt_CloseFileWriter",\n 1\n );\n Module["_PDFiumExt_SaveAsCopy"] = createExportWrapper(\n "PDFiumExt_SaveAsCopy",\n 2\n );\n Module["_FPDF_SaveAsCopy"] = createExportWrapper("FPDF_SaveAsCopy", 3);\n Module["_PDFiumExt_OpenFormFillInfo"] = createExportWrapper(\n "PDFiumExt_OpenFormFillInfo",\n 0\n );\n Module["_PDFiumExt_CloseFormFillInfo"] = createExportWrapper("PDFiumExt_CloseFormFillInfo", 1);\n Module["_PDFiumExt_InitFormFillEnvironment"] = createExportWrapper("PDFiumExt_InitFormFillEnvironment", 2);\n Module["_FPDFDOC_InitFormFillEnvironment"] = createExportWrapper("FPDFDOC_InitFormFillEnvironment", 2);\n Module["_PDFiumExt_ExitFormFillEnvironment"] = createExportWrapper("PDFiumExt_ExitFormFillEnvironment", 1);\n Module["_FPDFDOC_ExitFormFillEnvironment"] = createExportWrapper("FPDFDOC_ExitFormFillEnvironment", 1);\n Module["_EPDFNamedDest_SetDest"] = createExportWrapper(\n "EPDFNamedDest_SetDest",\n 3\n );\n Module["_EPDFNamedDest_Remove"] = createExportWrapper(\n "EPDFNamedDest_Remove",\n 2\n );\n Module["_EPDFDest_CreateView"] = createExportWrapper(\n "EPDFDest_CreateView",\n 4\n );\n Module["_EPDFDest_CreateXYZ"] = createExportWrapper(\n "EPDFDest_CreateXYZ",\n 7\n );\n Module["_EPDFDest_CreateRemoteView"] = createExportWrapper(\n "EPDFDest_CreateRemoteView",\n 5\n );\n Module["_EPDFDest_CreateRemoteXYZ"] = createExportWrapper(\n "EPDFDest_CreateRemoteXYZ",\n 8\n );\n Module["_EPDFAction_CreateGoTo"] = createExportWrapper(\n "EPDFAction_CreateGoTo",\n 2\n );\n Module["_EPDFAction_CreateGoToNamed"] = createExportWrapper(\n "EPDFAction_CreateGoToNamed",\n 2\n );\n Module["_EPDFAction_CreateLaunch"] = createExportWrapper(\n "EPDFAction_CreateLaunch",\n 2\n );\n Module["_EPDFAction_CreateRemoteGoToByName"] = createExportWrapper("EPDFAction_CreateRemoteGoToByName", 3);\n Module["_EPDFAction_CreateRemoteGoToDest"] = createExportWrapper("EPDFAction_CreateRemoteGoToDest", 3);\n Module["_EPDFAction_CreateURI"] = createExportWrapper(\n "EPDFAction_CreateURI",\n 2\n );\n Module["_EPDFBookmark_Create"] = createExportWrapper(\n "EPDFBookmark_Create",\n 2\n );\n Module["_EPDFBookmark_Delete"] = createExportWrapper(\n "EPDFBookmark_Delete",\n 2\n );\n Module["_EPDFBookmark_AppendChild"] = createExportWrapper(\n "EPDFBookmark_AppendChild",\n 3\n );\n Module["_EPDFBookmark_InsertAfter"] = createExportWrapper(\n "EPDFBookmark_InsertAfter",\n 4\n );\n Module["_EPDFBookmark_Clear"] = createExportWrapper(\n "EPDFBookmark_Clear",\n 1\n );\n Module["_EPDFBookmark_SetTitle"] = createExportWrapper(\n "EPDFBookmark_SetTitle",\n 2\n );\n Module["_EPDFBookmark_SetDest"] = createExportWrapper(\n "EPDFBookmark_SetDest",\n 3\n );\n Module["_EPDFBookmark_SetAction"] = createExportWrapper(\n "EPDFBookmark_SetAction",\n 3\n );\n Module["_EPDFBookmark_ClearTarget"] = createExportWrapper(\n "EPDFBookmark_ClearTarget",\n 1\n );\n Module["_EPDF_PNG_EncodeRGBA"] = createExportWrapper(\n "EPDF_PNG_EncodeRGBA",\n 6\n );\n Module["_FPDFAnnot_IsSupportedSubtype"] = createExportWrapper("FPDFAnnot_IsSupportedSubtype", 1);\n Module["_FPDFPage_CreateAnnot"] = createExportWrapper(\n "FPDFPage_CreateAnnot",\n 2\n );\n Module["_FPDFPage_GetAnnotCount"] = createExportWrapper(\n "FPDFPage_GetAnnotCount",\n 1\n );\n Module["_FPDFPage_GetAnnot"] = createExportWrapper(\n "FPDFPage_GetAnnot",\n 2\n );\n Module["_FPDFPage_GetAnnotIndex"] = createExportWrapper(\n "FPDFPage_GetAnnotIndex",\n 2\n );\n Module["_FPDFPage_CloseAnnot"] = createExportWrapper(\n "FPDFPage_CloseAnnot",\n 1\n );\n Module["_FPDFPage_RemoveAnnot"] = createExportWrapper(\n "FPDFPage_RemoveAnnot",\n 2\n );\n Module["_FPDFAnnot_GetSubtype"] = createExportWrapper(\n "FPDFAnnot_GetSubtype",\n 1\n );\n Module["_FPDFAnnot_IsObjectSupportedSubtype"] = createExportWrapper("FPDFAnnot_IsObjectSupportedSubtype", 1);\n Module["_FPDFAnnot_UpdateObject"] = createExportWrapper(\n "FPDFAnnot_UpdateObject",\n 2\n );\n Module["_FPDFAnnot_AddInkStroke"] = createExportWrapper(\n "FPDFAnnot_AddInkStroke",\n 3\n );\n Module["_FPDFAnnot_RemoveInkList"] = createExportWrapper(\n "FPDFAnnot_RemoveInkList",\n 1\n );\n Module["_FPDFAnnot_AppendObject"] = createExportWrapper(\n "FPDFAnnot_AppendObject",\n 2\n );\n Module["_FPDFAnnot_GetObjectCount"] = createExportWrapper(\n "FPDFAnnot_GetObjectCount",\n 1\n );\n Module["_FPDFAnnot_GetObject"] = createExportWrapper(\n "FPDFAnnot_GetObject",\n 2\n );\n Module["_FPDFAnnot_RemoveObject"] = createExportWrapper(\n "FPDFAnnot_RemoveObject",\n 2\n );\n Module["_FPDFAnnot_SetColor"] = createExportWrapper(\n "FPDFAnnot_SetColor",\n 6\n );\n Module["_FPDFAnnot_GetColor"] = createExportWrapper(\n "FPDFAnnot_GetColor",\n 6\n );\n Module["_FPDFAnnot_HasAttachmentPoints"] = createExportWrapper("FPDFAnnot_HasAttachmentPoints", 1);\n Module["_FPDFAnnot_SetAttachmentPoints"] = createExportWrapper("FPDFAnnot_SetAttachmentPoints", 3);\n Module["_FPDFAnnot_AppendAttachmentPoints"] = createExportWrapper("FPDFAnnot_AppendAttachmentPoints", 2);\n Module["_FPDFAnnot_CountAttachmentPoints"] = createExportWrapper("FPDFAnnot_CountAttachmentPoints", 1);\n Module["_FPDFAnnot_GetAttachmentPoints"] = createExportWrapper("FPDFAnnot_GetAttachmentPoints", 3);\n Module["_FPDFAnnot_SetRect"] = createExportWrapper(\n "FPDFAnnot_SetRect",\n 2\n );\n Module["_FPDFAnnot_GetRect"] = createExportWrapper(\n "FPDFAnnot_GetRect",\n 2\n );\n Module["_FPDFAnnot_GetVertices"] = createExportWrapper(\n "FPDFAnnot_GetVertices",\n 3\n );\n Module["_FPDFAnnot_GetInkListCount"] = createExportWrapper(\n "FPDFAnnot_GetInkListCount",\n 1\n );\n Module["_FPDFAnnot_GetInkListPath"] = createExportWrapper(\n "FPDFAnnot_GetInkListPath",\n 4\n );\n Module["_FPDFAnnot_GetLine"] = createExportWrapper(\n "FPDFAnnot_GetLine",\n 3\n );\n Module["_FPDFAnnot_SetBorder"] = createExportWrapper(\n "FPDFAnnot_SetBorder",\n 4\n );\n Module["_FPDFAnnot_GetBorder"] = createExportWrapper(\n "FPDFAnnot_GetBorder",\n 4\n );\n Module["_FPDFAnnot_HasKey"] = createExportWrapper(\n "FPDFAnnot_HasKey",\n 2\n );\n Module["_FPDFAnnot_GetValueType"] = createExportWrapper(\n "FPDFAnnot_GetValueType",\n 2\n );\n Module["_FPDFAnnot_SetStringValue"] = createExportWrapper(\n "FPDFAnnot_SetStringValue",\n 3\n );\n Module["_FPDFAnnot_GetStringValue"] = createExportWrapper(\n "FPDFAnnot_GetStringValue",\n 4\n );\n Module["_FPDFAnnot_GetNumberValue"] = createExportWrapper(\n "FPDFAnnot_GetNumberValue",\n 3\n );\n Module["_FPDFAnnot_SetAP"] = createExportWrapper("FPDFAnnot_SetAP", 3);\n Module["_FPDFAnnot_GetAP"] = createExportWrapper("FPDFAnnot_GetAP", 4);\n Module["_FPDFAnnot_GetLinkedAnnot"] = createExportWrapper(\n "FPDFAnnot_GetLinkedAnnot",\n 2\n );\n Module["_FPDFAnnot_GetFlags"] = createExportWrapper(\n "FPDFAnnot_GetFlags",\n 1\n );\n Module["_FPDFAnnot_SetFlags"] = createExportWrapper(\n "FPDFAnnot_SetFlags",\n 2\n );\n Module["_FPDFAnnot_GetFormFieldFlags"] = createExportWrapper("FPDFAnnot_GetFormFieldFlags", 2);\n Module["_FPDFAnnot_SetFormFieldFlags"] = createExportWrapper("FPDFAnnot_SetFormFieldFlags", 3);\n Module["_FPDFAnnot_GetFormFieldAtPoint"] = createExportWrapper("FPDFAnnot_GetFormFieldAtPoint", 3);\n Module["_FPDFAnnot_GetFormFieldName"] = createExportWrapper(\n "FPDFAnnot_GetFormFieldName",\n 4\n );\n Module["_FPDFAnnot_GetFormFieldType"] = createExportWrapper(\n "FPDFAnnot_GetFormFieldType",\n 2\n );\n Module["_FPDFAnnot_GetFormAdditionalActionJavaScript"] = createExportWrapper("FPDFAnnot_GetFormAdditionalActionJavaScript", 5);\n Module["_FPDFAnnot_GetFormFieldAlternateName"] = createExportWrapper("FPDFAnnot_GetFormFieldAlternateName", 4);\n Module["_FPDFAnnot_GetFormFieldValue"] = createExportWrapper("FPDFAnnot_GetFormFieldValue", 4);\n Module["_FPDFAnnot_GetOptionCount"] = createExportWrapper(\n "FPDFAnnot_GetOptionCount",\n 2\n );\n Module["_FPDFAnnot_GetOptionLabel"] = createExportWrapper(\n "FPDFAnnot_GetOptionLabel",\n 5\n );\n Module["_FPDFAnnot_IsOptionSelected"] = createExportWrapper(\n "FPDFAnnot_IsOptionSelected",\n 3\n );\n Module["_FPDFAnnot_GetFontSize"] = createExportWrapper(\n "FPDFAnnot_GetFontSize",\n 3\n );\n Module["_FPDFAnnot_SetFontColor"] = createExportWrapper(\n "FPDFAnnot_SetFontColor",\n 5\n );\n Module["_FPDFAnnot_GetFontColor"] = createExportWrapper(\n "FPDFAnnot_GetFontColor",\n 5\n );\n Module["_FPDFAnnot_IsChecked"] = createExportWrapper(\n "FPDFAnnot_IsChecked",\n 2\n );\n Module["_FPDFAnnot_SetFocusableSubtypes"] = createExportWrapper("FPDFAnnot_SetFocusableSubtypes", 3);\n Module["_FPDFAnnot_GetFocusableSubtypesCount"] = createExportWrapper("FPDFAnnot_GetFocusableSubtypesCount", 1);\n Module["_FPDFAnnot_GetFocusableSubtypes"] = createExportWrapper("FPDFAnnot_GetFocusableSubtypes", 3);\n Module["_FPDFAnnot_GetLink"] = createExportWrapper(\n "FPDFAnnot_GetLink",\n 1\n );\n Module["_FPDFAnnot_GetFormControlCount"] = createExportWrapper("FPDFAnnot_GetFormControlCount", 2);\n Module["_FPDFAnnot_GetFormControlIndex"] = createExportWrapper("FPDFAnnot_GetFormControlIndex", 2);\n Module["_FPDFAnnot_GetFormFieldExportValue"] = createExportWrapper("FPDFAnnot_GetFormFieldExportValue", 4);\n Module["_FPDFAnnot_SetURI"] = createExportWrapper(\n "FPDFAnnot_SetURI",\n 2\n );\n Module["_EPDFAnnot_SetAction"] = createExportWrapper(\n "EPDFAnnot_SetAction",\n 2\n );\n Module["_FPDFAnnot_GetFileAttachment"] = createExportWrapper("FPDFAnnot_GetFileAttachment", 1);\n Module["_FPDFAnnot_AddFileAttachment"] = createExportWrapper("FPDFAnnot_AddFileAttachment", 2);\n Module["_EPDFAnnot_SetColor"] = createExportWrapper(\n "EPDFAnnot_SetColor",\n 5\n );\n Module["_EPDFAnnot_GetColor"] = createExportWrapper(\n "EPDFAnnot_GetColor",\n 5\n );\n Module["_EPDFAnnot_ClearColor"] = createExportWrapper(\n "EPDFAnnot_ClearColor",\n 2\n );\n Module["_EPDFAnnot_SetOpacity"] = createExportWrapper(\n "EPDFAnnot_SetOpacity",\n 2\n );\n Module["_EPDFAnnot_GetOpacity"] = createExportWrapper(\n "EPDFAnnot_GetOpacity",\n 2\n );\n Module["_EPDFAnnot_GetBorderEffect"] = createExportWrapper(\n "EPDFAnnot_GetBorderEffect",\n 2\n );\n Module["_EPDFAnnot_GetRectangleDifferences"] = createExportWrapper("EPDFAnnot_GetRectangleDifferences", 5);\n Module["_EPDFAnnot_SetRectangleDifferences"] = createExportWrapper("EPDFAnnot_SetRectangleDifferences", 5);\n Module["_EPDFAnnot_ClearRectangleDifferences"] = createExportWrapper("EPDFAnnot_ClearRectangleDifferences", 1);\n Module["_EPDFAnnot_GetBorderDashPatternCount"] = createExportWrapper("EPDFAnnot_GetBorderDashPatternCount", 1);\n Module["_EPDFAnnot_GetBorderDashPattern"] = createExportWrapper("EPDFAnnot_GetBorderDashPattern", 3);\n Module["_EPDFAnnot_SetBorderDashPattern"] = createExportWrapper("EPDFAnnot_SetBorderDashPattern", 3);\n Module["_EPDFAnnot_GetBorderStyle"] = createExportWrapper(\n "EPDFAnnot_GetBorderStyle",\n 2\n );\n Module["_EPDFAnnot_SetBorderStyle"] = createExportWrapper(\n "EPDFAnnot_SetBorderStyle",\n 3\n );\n Module["_EPDFAnnot_GenerateAppearance"] = createExportWrapper("EPDFAnnot_GenerateAppearance", 1);\n Module["_EPDFAnnot_GenerateAppearanceWithBlend"] = createExportWrapper("EPDFAnnot_GenerateAppearanceWithBlend", 2);\n Module["_EPDFAnnot_GetBlendMode"] = createExportWrapper(\n "EPDFAnnot_GetBlendMode",\n 1\n );\n Module["_EPDFAnnot_SetIntent"] = createExportWrapper(\n "EPDFAnnot_SetIntent",\n 2\n );\n Module["_EPDFAnnot_GetIntent"] = createExportWrapper(\n "EPDFAnnot_GetIntent",\n 3\n );\n Module["_EPDFAnnot_GetRichContent"] = createExportWrapper(\n "EPDFAnnot_GetRichContent",\n 3\n );\n Module["_EPDFAnnot_SetLineEndings"] = createExportWrapper(\n "EPDFAnnot_SetLineEndings",\n 3\n );\n Module["_EPDFAnnot_GetLineEndings"] = createExportWrapper(\n "EPDFAnnot_GetLineEndings",\n 3\n );\n Module["_EPDFAnnot_SetVertices"] = createExportWrapper(\n "EPDFAnnot_SetVertices",\n 3\n );\n Module["_EPDFAnnot_SetLine"] = createExportWrapper(\n "EPDFAnnot_SetLine",\n 3\n );\n Module["_EPDFAnnot_SetDefaultAppearance"] = createExportWrapper("EPDFAnnot_SetDefaultAppearance", 6);\n Module["_EPDFAnnot_GetDefaultAppearance"] = createExportWrapper("EPDFAnnot_GetDefaultAppearance", 6);\n Module["_EPDFAnnot_SetTextAlignment"] = createExportWrapper(\n "EPDFAnnot_SetTextAlignment",\n 2\n );\n Module["_EPDFAnnot_GetTextAlignment"] = createExportWrapper(\n "EPDFAnnot_GetTextAlignment",\n 1\n );\n Module["_EPDFAnnot_SetVerticalAlignment"] = createExportWrapper("EPDFAnnot_SetVerticalAlignment", 2);\n Module["_EPDFAnnot_GetVerticalAlignment"] = createExportWrapper("EPDFAnnot_GetVerticalAlignment", 1);\n Module["_EPDFPage_GetAnnotByName"] = createExportWrapper(\n "EPDFPage_GetAnnotByName",\n 2\n );\n Module["_EPDFPage_RemoveAnnotByName"] = createExportWrapper(\n "EPDFPage_RemoveAnnotByName",\n 2\n );\n Module["_EPDFAnnot_SetLinkedAnnot"] = createExportWrapper(\n "EPDFAnnot_SetLinkedAnnot",\n 3\n );\n Module["_EPDFPage_GetAnnotCountRaw"] = createExportWrapper(\n "EPDFPage_GetAnnotCountRaw",\n 2\n );\n Module["_EPDFPage_GetAnnotRaw"] = createExportWrapper(\n "EPDFPage_GetAnnotRaw",\n 3\n );\n Module["_EPDFPage_RemoveAnnotRaw"] = createExportWrapper(\n "EPDFPage_RemoveAnnotRaw",\n 3\n );\n Module["_EPDFAnnot_SetIcon"] = createExportWrapper(\n "EPDFAnnot_SetIcon",\n 2\n );\n Module["_EPDFAnnot_GetIcon"] = createExportWrapper(\n "EPDFAnnot_GetIcon",\n 1\n );\n Module["_EPDFAnnot_UpdateAppearanceToRect"] = createExportWrapper("EPDFAnnot_UpdateAppearanceToRect", 2);\n Module["_EPDFPage_CreateAnnot"] = createExportWrapper(\n "EPDFPage_CreateAnnot",\n 2\n );\n Module["_EPDFAnnot_SetRotate"] = createExportWrapper(\n "EPDFAnnot_SetRotate",\n 2\n );\n Module["_EPDFAnnot_GetRotate"] = createExportWrapper(\n "EPDFAnnot_GetRotate",\n 2\n );\n Module["_EPDFAnnot_GetReplyType"] = createExportWrapper(\n "EPDFAnnot_GetReplyType",\n 1\n );\n Module["_EPDFAnnot_SetReplyType"] = createExportWrapper(\n "EPDFAnnot_SetReplyType",\n 2\n );\n Module["_EPDFAnnot_SetOverlayText"] = createExportWrapper(\n "EPDFAnnot_SetOverlayText",\n 2\n );\n Module["_EPDFAnnot_GetOverlayText"] = createExportWrapper(\n "EPDFAnnot_GetOverlayText",\n 3\n );\n Module["_EPDFAnnot_SetOverlayTextRepeat"] = createExportWrapper("EPDFAnnot_SetOverlayTextRepeat", 2);\n Module["_EPDFAnnot_GetOverlayTextRepeat"] = createExportWrapper("EPDFAnnot_GetOverlayTextRepeat", 1);\n Module["_EPDFAnnot_ApplyRedaction"] = createExportWrapper(\n "EPDFAnnot_ApplyRedaction",\n 2\n );\n Module["_EPDFPage_ApplyRedactions"] = createExportWrapper(\n "EPDFPage_ApplyRedactions",\n 1\n );\n Module["_EPDFAnnot_Flatten"] = createExportWrapper(\n "EPDFAnnot_Flatten",\n 2\n );\n Module["_EPDFAnnot_SetExtendedRotation"] = createExportWrapper("EPDFAnnot_SetExtendedRotation", 2);\n Module["_EPDFAnnot_GetExtendedRotation"] = createExportWrapper("EPDFAnnot_GetExtendedRotation", 2);\n Module["_EPDFAnnot_SetUnrotatedRect"] = createExportWrapper(\n "EPDFAnnot_SetUnrotatedRect",\n 2\n );\n Module["_EPDFAnnot_GetUnrotatedRect"] = createExportWrapper(\n "EPDFAnnot_GetUnrotatedRect",\n 2\n );\n Module["_EPDFAnnot_GetRect"] = createExportWrapper(\n "EPDFAnnot_GetRect",\n 2\n );\n Module["_EPDFAnnot_SetAPMatrix"] = createExportWrapper(\n "EPDFAnnot_SetAPMatrix",\n 3\n );\n Module["_EPDFAnnot_GetAPMatrix"] = createExportWrapper(\n "EPDFAnnot_GetAPMatrix",\n 3\n );\n Module["_EPDFAnnot_GetAvailableAppearanceModes"] = createExportWrapper("EPDFAnnot_GetAvailableAppearanceModes", 1);\n Module["_EPDFAnnot_HasAppearanceStream"] = createExportWrapper("EPDFAnnot_HasAppearanceStream", 2);\n Module["_FPDFDoc_GetAttachmentCount"] = createExportWrapper(\n "FPDFDoc_GetAttachmentCount",\n 1\n );\n Module["_FPDFDoc_AddAttachment"] = createExportWrapper(\n "FPDFDoc_AddAttachment",\n 2\n );\n Module["_FPDFDoc_GetAttachment"] = createExportWrapper(\n "FPDFDoc_GetAttachment",\n 2\n );\n Module["_FPDFDoc_DeleteAttachment"] = createExportWrapper(\n "FPDFDoc_DeleteAttachment",\n 2\n );\n Module["_FPDFAttachment_GetName"] = createExportWrapper(\n "FPDFAttachment_GetName",\n 3\n );\n Module["_FPDFAttachment_HasKey"] = createExportWrapper(\n "FPDFAttachment_HasKey",\n 2\n );\n Module["_FPDFAttachment_GetValueType"] = createExportWrapper("FPDFAttachment_GetValueType", 2);\n Module["_FPDFAttachment_SetStringValue"] = createExportWrapper("FPDFAttachment_SetStringValue", 3);\n Module["_FPDFAttachment_GetStringValue"] = createExportWrapper("FPDFAttachment_GetStringValue", 4);\n Module["_FPDFAttachment_SetFile"] = createExportWrapper(\n "FPDFAttachment_SetFile",\n 4\n );\n Module["_FPDFAttachment_GetFile"] = createExportWrapper(\n "FPDFAttachment_GetFile",\n 4\n );\n Module["_FPDFAttachment_GetSubtype"] = createExportWrapper(\n "FPDFAttachment_GetSubtype",\n 3\n );\n Module["_EPDFAttachment_SetSubtype"] = createExportWrapper(\n "EPDFAttachment_SetSubtype",\n 2\n );\n Module["_EPDFAttachment_SetDescription"] = createExportWrapper("EPDFAttachment_SetDescription", 2);\n Module["_EPDFAttachment_GetDescription"] = createExportWrapper("EPDFAttachment_GetDescription", 3);\n Module["_EPDFAttachment_GetIntegerValue"] = createExportWrapper("EPDFAttachment_GetIntegerValue", 3);\n Module["_FPDFCatalog_IsTagged"] = createExportWrapper(\n "FPDFCatalog_IsTagged",\n 1\n );\n Module["_FPDFCatalog_GetLanguage"] = createExportWrapper(\n "FPDFCatalog_GetLanguage",\n 3\n );\n Module["_FPDFCatalog_SetLanguage"] = createExportWrapper(\n "FPDFCatalog_SetLanguage",\n 2\n );\n Module["_EPDFCatalog_GetLanguage"] = createExportWrapper(\n "EPDFCatalog_GetLanguage",\n 3\n );\n Module["_FPDFAvail_Create"] = createExportWrapper(\n "FPDFAvail_Create",\n 2\n );\n Module["_FPDFAvail_Destroy"] = createExportWrapper(\n "FPDFAvail_Destroy",\n 1\n );\n Module["_FPDFAvail_IsDocAvail"] = createExportWrapper(\n "FPDFAvail_IsDocAvail",\n 2\n );\n Module["_FPDFAvail_GetDocument"] = createExportWrapper(\n "FPDFAvail_GetDocument",\n 2\n );\n Module["_FPDFAvail_GetFirstPageNum"] = createExportWrapper(\n "FPDFAvail_GetFirstPageNum",\n 1\n );\n Module["_FPDFAvail_IsPageAvail"] = createExportWrapper(\n "FPDFAvail_IsPageAvail",\n 3\n );\n Module["_FPDFAvail_IsFormAvail"] = createExportWrapper(\n "FPDFAvail_IsFormAvail",\n 2\n );\n Module["_FPDFAvail_IsLinearized"] = createExportWrapper(\n "FPDFAvail_IsLinearized",\n 1\n );\n Module["_FPDFBookmark_GetFirstChild"] = createExportWrapper(\n "FPDFBookmark_GetFirstChild",\n 2\n );\n Module["_FPDFBookmark_GetNextSibling"] = createExportWrapper("FPDFBookmark_GetNextSibling", 2);\n Module["_FPDFBookmark_GetTitle"] = createExportWrapper(\n "FPDFBookmark_GetTitle",\n 3\n );\n Module["_FPDFBookmark_GetCount"] = createExportWrapper(\n "FPDFBookmark_GetCount",\n 1\n );\n Module["_FPDFBookmark_Find"] = createExportWrapper(\n "FPDFBookmark_Find",\n 2\n );\n Module["_FPDFBookmark_GetDest"] = createExportWrapper(\n "FPDFBookmark_GetDest",\n 2\n );\n Module["_FPDFBookmark_GetAction"] = createExportWrapper(\n "FPDFBookmark_GetAction",\n 1\n );\n Module["_FPDFAction_GetType"] = createExportWrapper(\n "FPDFAction_GetType",\n 1\n );\n Module["_FPDFAction_GetDest"] = createExportWrapper(\n "FPDFAction_GetDest",\n 2\n );\n Module["_FPDFAction_GetFilePath"] = createExportWrapper(\n "FPDFAction_GetFilePath",\n 3\n );\n Module["_FPDFAction_GetURIPath"] = createExportWrapper(\n "FPDFAction_GetURIPath",\n 4\n );\n Module["_FPDFDest_GetDestPageIndex"] = createExportWrapper(\n "FPDFDest_GetDestPageIndex",\n 2\n );\n Module["_FPDFDest_GetView"] = createExportWrapper(\n "FPDFDest_GetView",\n 3\n );\n Module["_FPDFDest_GetLocationInPage"] = createExportWrapper(\n "FPDFDest_GetLocationInPage",\n 7\n );\n Module["_FPDFLink_GetLinkAtPoint"] = createExportWrapper(\n "FPDFLink_GetLinkAtPoint",\n 3\n );\n Module["_FPDFLink_GetLinkZOrderAtPoint"] = createExportWrapper("FPDFLink_GetLinkZOrderAtPoint", 3);\n Module["_FPDFLink_GetDest"] = createExportWrapper(\n "FPDFLink_GetDest",\n 2\n );\n Module["_FPDFLink_GetAction"] = createExportWrapper(\n "FPDFLink_GetAction",\n 1\n );\n Module["_FPDFLink_Enumerate"] = createExportWrapper(\n "FPDFLink_Enumerate",\n 3\n );\n Module["_FPDFLink_GetAnnot"] = createExportWrapper(\n "FPDFLink_GetAnnot",\n 2\n );\n Module["_FPDFLink_GetAnnotRect"] = createExportWrapper(\n "FPDFLink_GetAnnotRect",\n 2\n );\n Module["_FPDFLink_CountQuadPoints"] = createExportWrapper(\n "FPDFLink_CountQuadPoints",\n 1\n );\n Module["_FPDFLink_GetQuadPoints"] = createExportWrapper(\n "FPDFLink_GetQuadPoints",\n 3\n );\n Module["_FPDF_GetPageAAction"] = createExportWrapper(\n "FPDF_GetPageAAction",\n 2\n );\n Module["_FPDF_GetFileIdentifier"] = createExportWrapper(\n "FPDF_GetFileIdentifier",\n 4\n );\n Module["_FPDF_GetMetaText"] = createExportWrapper(\n "FPDF_GetMetaText",\n 4\n );\n Module["_FPDF_GetPageLabel"] = createExportWrapper(\n "FPDF_GetPageLabel",\n 4\n );\n Module["_EPDF_SetMetaText"] = createExportWrapper(\n "EPDF_SetMetaText",\n 3\n );\n Module["_EPDF_HasMetaText"] = createExportWrapper(\n "EPDF_HasMetaText",\n 2\n );\n Module["_EPDF_GetMetaTrapped"] = createExportWrapper(\n "EPDF_GetMetaTrapped",\n 1\n );\n Module["_EPDF_SetMetaTrapped"] = createExportWrapper(\n "EPDF_SetMetaTrapped",\n 2\n );\n Module["_EPDF_GetMetaKeyCount"] = createExportWrapper(\n "EPDF_GetMetaKeyCount",\n 2\n );\n Module["_EPDF_GetMetaKeyName"] = createExportWrapper(\n "EPDF_GetMetaKeyName",\n 5\n );\n Module["_FPDFPageObj_NewImageObj"] = createExportWrapper(\n "FPDFPageObj_NewImageObj",\n 1\n );\n Module["_FPDFImageObj_LoadJpegFile"] = createExportWrapper(\n "FPDFImageObj_LoadJpegFile",\n 4\n );\n Module["_FPDFImageObj_LoadJpegFileInline"] = createExportWrapper("FPDFImageObj_LoadJpegFileInline", 4);\n Module["_FPDFImageObj_SetMatrix"] = createExportWrapper(\n "FPDFImageObj_SetMatrix",\n 7\n );\n Module["_FPDFImageObj_SetBitmap"] = createExportWrapper(\n "FPDFImageObj_SetBitmap",\n 4\n );\n Module["_FPDFImageObj_GetBitmap"] = createExportWrapper(\n "FPDFImageObj_GetBitmap",\n 1\n );\n Module["_FPDFImageObj_GetRenderedBitmap"] = createExportWrapper("FPDFImageObj_GetRenderedBitmap", 3);\n Module["_FPDFImageObj_GetImageDataDecoded"] = createExportWrapper("FPDFImageObj_GetImageDataDecoded", 3);\n Module["_FPDFImageObj_GetImageDataRaw"] = createExportWrapper("FPDFImageObj_GetImageDataRaw", 3);\n Module["_FPDFImageObj_GetImageFilterCount"] = createExportWrapper("FPDFImageObj_GetImageFilterCount", 1);\n Module["_FPDFImageObj_GetImageFilter"] = createExportWrapper("FPDFImageObj_GetImageFilter", 4);\n Module["_FPDFImageObj_GetImageMetadata"] = createExportWrapper("FPDFImageObj_GetImageMetadata", 3);\n Module["_FPDFImageObj_GetImagePixelSize"] = createExportWrapper("FPDFImageObj_GetImagePixelSize", 3);\n Module["_FPDFImageObj_GetIccProfileDataDecoded"] = createExportWrapper("FPDFImageObj_GetIccProfileDataDecoded", 5);\n Module["_FPDF_CreateNewDocument"] = createExportWrapper(\n "FPDF_CreateNewDocument",\n 0\n );\n Module["_FPDFPage_Delete"] = createExportWrapper("FPDFPage_Delete", 2);\n Module["_FPDF_MovePages"] = createExportWrapper("FPDF_MovePages", 4);\n Module["_FPDFPage_New"] = createExportWrapper("FPDFPage_New", 4);\n Module["_FPDFPage_GetRotation"] = createExportWrapper(\n "FPDFPage_GetRotation",\n 1\n );\n Module["_FPDFPage_InsertObject"] = createExportWrapper(\n "FPDFPage_InsertObject",\n 2\n );\n Module["_FPDFPage_InsertObjectAtIndex"] = createExportWrapper("FPDFPage_InsertObjectAtIndex", 3);\n Module["_FPDFPage_RemoveObject"] = createExportWrapper(\n "FPDFPage_RemoveObject",\n 2\n );\n Module["_FPDFPage_CountObjects"] = createExportWrapper(\n "FPDFPage_CountObjects",\n 1\n );\n Module["_FPDFPage_GetObject"] = createExportWrapper(\n "FPDFPage_GetObject",\n 2\n );\n Module["_FPDFPage_HasTransparency"] = createExportWrapper(\n "FPDFPage_HasTransparency",\n 1\n );\n Module["_FPDFPageObj_Destroy"] = createExportWrapper(\n "FPDFPageObj_Destroy",\n 1\n );\n Module["_FPDFPageObj_GetMarkedContentID"] = createExportWrapper("FPDFPageObj_GetMarkedContentID", 1);\n Module["_FPDFPageObj_CountMarks"] = createExportWrapper(\n "FPDFPageObj_CountMarks",\n 1\n );\n Module["_FPDFPageObj_GetMark"] = createExportWrapper(\n "FPDFPageObj_GetMark",\n 2\n );\n Module["_FPDFPageObj_AddMark"] = createExportWrapper(\n "FPDFPageObj_AddMark",\n 2\n );\n Module["_FPDFPageObj_RemoveMark"] = createExportWrapper(\n "FPDFPageObj_RemoveMark",\n 2\n );\n Module["_FPDFPageObjMark_GetName"] = createExportWrapper(\n "FPDFPageObjMark_GetName",\n 4\n );\n Module["_FPDFPageObjMark_CountParams"] = createExportWrapper("FPDFPageObjMark_CountParams", 1);\n Module["_FPDFPageObjMark_GetParamKey"] = createExportWrapper("FPDFPageObjMark_GetParamKey", 5);\n Module["_FPDFPageObjMark_GetParamValueType"] = createExportWrapper("FPDFPageObjMark_GetParamValueType", 2);\n Module["_FPDFPageObjMark_GetParamIntValue"] = createExportWrapper("FPDFPageObjMark_GetParamIntValue", 3);\n Module["_FPDFPageObjMark_GetParamFloatValue"] = createExportWrapper("FPDFPageObjMark_GetParamFloatValue", 3);\n Module["_FPDFPageObjMark_GetParamStringValue"] = createExportWrapper("FPDFPageObjMark_GetParamStringValue", 5);\n Module["_FPDFPageObjMark_GetParamBlobValue"] = createExportWrapper("FPDFPageObjMark_GetParamBlobValue", 5);\n Module["_FPDFPageObj_HasTransparency"] = createExportWrapper("FPDFPageObj_HasTransparency", 1);\n Module["_FPDFPageObjMark_SetIntParam"] = createExportWrapper("FPDFPageObjMark_SetIntParam", 5);\n Module["_FPDFPageObjMark_SetFloatParam"] = createExportWrapper("FPDFPageObjMark_SetFloatParam", 5);\n Module["_FPDFPageObjMark_SetStringParam"] = createExportWrapper("FPDFPageObjMark_SetStringParam", 5);\n Module["_FPDFPageObjMark_SetBlobParam"] = createExportWrapper("FPDFPageObjMark_SetBlobParam", 6);\n Module["_FPDFPageObjMark_RemoveParam"] = createExportWrapper("FPDFPageObjMark_RemoveParam", 3);\n Module["_FPDFPageObj_GetType"] = createExportWrapper(\n "FPDFPageObj_GetType",\n 1\n );\n Module["_FPDFPageObj_GetIsActive"] = createExportWrapper(\n "FPDFPageObj_GetIsActive",\n 2\n );\n Module["_FPDFPageObj_SetIsActive"] = createExportWrapper(\n "FPDFPageObj_SetIsActive",\n 2\n );\n Module["_FPDFPage_GenerateContent"] = createExportWrapper(\n "FPDFPage_GenerateContent",\n 1\n );\n Module["_FPDFPageObj_Transform"] = createExportWrapper(\n "FPDFPageObj_Transform",\n 7\n );\n Module["_FPDFPageObj_TransformF"] = createExportWrapper(\n "FPDFPageObj_TransformF",\n 2\n );\n Module["_FPDFPageObj_GetMatrix"] = createExportWrapper(\n "FPDFPageObj_GetMatrix",\n 2\n );\n Module["_FPDFPageObj_SetMatrix"] = createExportWrapper(\n "FPDFPageObj_SetMatrix",\n 2\n );\n Module["_FPDFPageObj_SetBlendMode"] = createExportWrapper(\n "FPDFPageObj_SetBlendMode",\n 2\n );\n Module["_FPDFPage_TransformAnnots"] = createExportWrapper(\n "FPDFPage_TransformAnnots",\n 7\n );\n Module["_FPDFPage_SetRotation"] = createExportWrapper(\n "FPDFPage_SetRotation",\n 2\n );\n Module["_FPDFPageObj_SetFillColor"] = createExportWrapper(\n "FPDFPageObj_SetFillColor",\n 5\n );\n Module["_FPDFPageObj_GetFillColor"] = createExportWrapper(\n "FPDFPageObj_GetFillColor",\n 5\n );\n Module["_FPDFPageObj_GetBounds"] = createExportWrapper(\n "FPDFPageObj_GetBounds",\n 5\n );\n Module["_FPDFPageObj_GetRotatedBounds"] = createExportWrapper("FPDFPageObj_GetRotatedBounds", 2);\n Module["_FPDFPageObj_SetStrokeColor"] = createExportWrapper(\n "FPDFPageObj_SetStrokeColor",\n 5\n );\n Module["_FPDFPageObj_GetStrokeColor"] = createExportWrapper(\n "FPDFPageObj_GetStrokeColor",\n 5\n );\n Module["_FPDFPageObj_SetStrokeWidth"] = createExportWrapper(\n "FPDFPageObj_SetStrokeWidth",\n 2\n );\n Module["_FPDFPageObj_GetStrokeWidth"] = createExportWrapper(\n "FPDFPageObj_GetStrokeWidth",\n 2\n );\n Module["_FPDFPageObj_GetLineJoin"] = createExportWrapper(\n "FPDFPageObj_GetLineJoin",\n 1\n );\n Module["_FPDFPageObj_SetLineJoin"] = createExportWrapper(\n "FPDFPageObj_SetLineJoin",\n 2\n );\n Module["_FPDFPageObj_GetLineCap"] = createExportWrapper(\n "FPDFPageObj_GetLineCap",\n 1\n );\n Module["_FPDFPageObj_SetLineCap"] = createExportWrapper(\n "FPDFPageObj_SetLineCap",\n 2\n );\n Module["_FPDFPageObj_GetDashPhase"] = createExportWrapper(\n "FPDFPageObj_GetDashPhase",\n 2\n );\n Module["_FPDFPageObj_SetDashPhase"] = createExportWrapper(\n "FPDFPageObj_SetDashPhase",\n 2\n );\n Module["_FPDFPageObj_GetDashCount"] = createExportWrapper(\n "FPDFPageObj_GetDashCount",\n 1\n );\n Module["_FPDFPageObj_GetDashArray"] = createExportWrapper(\n "FPDFPageObj_GetDashArray",\n 3\n );\n Module["_FPDFPageObj_SetDashArray"] = createExportWrapper(\n "FPDFPageObj_SetDashArray",\n 4\n );\n Module["_FPDFFormObj_CountObjects"] = createExportWrapper(\n "FPDFFormObj_CountObjects",\n 1\n );\n Module["_FPDFFormObj_GetObject"] = createExportWrapper(\n "FPDFFormObj_GetObject",\n 2\n );\n Module["_FPDFFormObj_RemoveObject"] = createExportWrapper(\n "FPDFFormObj_RemoveObject",\n 2\n );\n Module["_FPDFPageObj_CreateNewPath"] = createExportWrapper(\n "FPDFPageObj_CreateNewPath",\n 2\n );\n Module["_FPDFPageObj_CreateNewRect"] = createExportWrapper(\n "FPDFPageObj_CreateNewRect",\n 4\n );\n Module["_FPDFPath_CountSegments"] = createExportWrapper(\n "FPDFPath_CountSegments",\n 1\n );\n Module["_FPDFPath_GetPathSegment"] = createExportWrapper(\n "FPDFPath_GetPathSegment",\n 2\n );\n Module["_FPDFPath_MoveTo"] = createExportWrapper("FPDFPath_MoveTo", 3);\n Module["_FPDFPath_LineTo"] = createExportWrapper("FPDFPath_LineTo", 3);\n Module["_FPDFPath_BezierTo"] = createExportWrapper(\n "FPDFPath_BezierTo",\n 7\n );\n Module["_FPDFPath_Close"] = createExportWrapper("FPDFPath_Close", 1);\n Module["_FPDFPath_SetDrawMode"] = createExportWrapper(\n "FPDFPath_SetDrawMode",\n 3\n );\n Module["_FPDFPath_GetDrawMode"] = createExportWrapper(\n "FPDFPath_GetDrawMode",\n 3\n );\n Module["_FPDFPathSegment_GetPoint"] = createExportWrapper(\n "FPDFPathSegment_GetPoint",\n 3\n );\n Module["_FPDFPathSegment_GetType"] = createExportWrapper(\n "FPDFPathSegment_GetType",\n 1\n );\n Module["_FPDFPathSegment_GetClose"] = createExportWrapper(\n "FPDFPathSegment_GetClose",\n 1\n );\n Module["_FPDFPageObj_NewTextObj"] = createExportWrapper(\n "FPDFPageObj_NewTextObj",\n 3\n );\n Module["_FPDFText_SetText"] = createExportWrapper(\n "FPDFText_SetText",\n 2\n );\n Module["_FPDFText_SetCharcodes"] = createExportWrapper(\n "FPDFText_SetCharcodes",\n 3\n );\n Module["_FPDFText_LoadFont"] = createExportWrapper(\n "FPDFText_LoadFont",\n 5\n );\n Module["_FPDFText_LoadStandardFont"] = createExportWrapper(\n "FPDFText_LoadStandardFont",\n 2\n );\n Module["_FPDFText_LoadCidType2Font"] = createExportWrapper(\n "FPDFText_LoadCidType2Font",\n 6\n );\n Module["_FPDFTextObj_GetFontSize"] = createExportWrapper(\n "FPDFTextObj_GetFontSize",\n 2\n );\n Module["_FPDFTextObj_GetText"] = createExportWrapper(\n "FPDFTextObj_GetText",\n 4\n );\n Module["_FPDFTextObj_GetRenderedBitmap"] = createExportWrapper("FPDFTextObj_GetRenderedBitmap", 4);\n Module["_FPDFFont_Close"] = createExportWrapper("FPDFFont_Close", 1);\n Module["_FPDFPageObj_CreateTextObj"] = createExportWrapper(\n "FPDFPageObj_CreateTextObj",\n 3\n );\n Module["_FPDFTextObj_GetTextRenderMode"] = createExportWrapper("FPDFTextObj_GetTextRenderMode", 1);\n Module["_FPDFTextObj_SetTextRenderMode"] = createExportWrapper("FPDFTextObj_SetTextRenderMode", 2);\n Module["_FPDFTextObj_GetFont"] = createExportWrapper(\n "FPDFTextObj_GetFont",\n 1\n );\n Module["_FPDFFont_GetBaseFontName"] = createExportWrapper(\n "FPDFFont_GetBaseFontName",\n 3\n );\n Module["_FPDFFont_GetFamilyName"] = createExportWrapper(\n "FPDFFont_GetFamilyName",\n 3\n );\n Module["_FPDFFont_GetFontData"] = createExportWrapper(\n "FPDFFont_GetFontData",\n 4\n );\n Module["_FPDFFont_GetIsEmbedded"] = createExportWrapper(\n "FPDFFont_GetIsEmbedded",\n 1\n );\n Module["_FPDFFont_GetFlags"] = createExportWrapper(\n "FPDFFont_GetFlags",\n 1\n );\n Module["_FPDFFont_GetWeight"] = createExportWrapper(\n "FPDFFont_GetWeight",\n 1\n );\n Module["_FPDFFont_GetItalicAngle"] = createExportWrapper(\n "FPDFFont_GetItalicAngle",\n 2\n );\n Module["_FPDFFont_GetAscent"] = createExportWrapper(\n "FPDFFont_GetAscent",\n 3\n );\n Module["_FPDFFont_GetDescent"] = createExportWrapper(\n "FPDFFont_GetDescent",\n 3\n );\n Module["_FPDFFont_GetGlyphWidth"] = createExportWrapper(\n "FPDFFont_GetGlyphWidth",\n 4\n );\n Module["_FPDFFont_GetGlyphPath"] = createExportWrapper(\n "FPDFFont_GetGlyphPath",\n 3\n );\n Module["_FPDFGlyphPath_CountGlyphSegments"] = createExportWrapper("FPDFGlyphPath_CountGlyphSegments", 1);\n Module["_FPDFGlyphPath_GetGlyphPathSegment"] = createExportWrapper("FPDFGlyphPath_GetGlyphPathSegment", 2);\n Module["_EPDFText_RedactInRect"] = createExportWrapper(\n "EPDFText_RedactInRect",\n 4\n );\n Module["_EPDFText_RedactInQuads"] = createExportWrapper(\n "EPDFText_RedactInQuads",\n 5\n );\n Module["_FPDFDoc_GetPageMode"] = createExportWrapper(\n "FPDFDoc_GetPageMode",\n 1\n );\n Module["_FPDFPage_Flatten"] = createExportWrapper(\n "FPDFPage_Flatten",\n 2\n );\n Module["_FPDFPage_HasFormFieldAtPoint"] = createExportWrapper("FPDFPage_HasFormFieldAtPoint", 4);\n Module["_FPDFPage_FormFieldZOrderAtPoint"] = createExportWrapper("FPDFPage_FormFieldZOrderAtPoint", 4);\n Module["_malloc"] = createExportWrapper("malloc", 1);\n Module["_free"] = createExportWrapper("free", 1);\n Module["_FORM_OnMouseMove"] = createExportWrapper(\n "FORM_OnMouseMove",\n 5\n );\n Module["_FORM_OnMouseWheel"] = createExportWrapper(\n "FORM_OnMouseWheel",\n 6\n );\n Module["_FORM_OnFocus"] = createExportWrapper("FORM_OnFocus", 5);\n Module["_FORM_OnLButtonDown"] = createExportWrapper(\n "FORM_OnLButtonDown",\n 5\n );\n Module["_FORM_OnLButtonUp"] = createExportWrapper(\n "FORM_OnLButtonUp",\n 5\n );\n Module["_FORM_OnLButtonDoubleClick"] = createExportWrapper(\n "FORM_OnLButtonDoubleClick",\n 5\n );\n Module["_FORM_OnRButtonDown"] = createExportWrapper(\n "FORM_OnRButtonDown",\n 5\n );\n Module["_FORM_OnRButtonUp"] = createExportWrapper(\n "FORM_OnRButtonUp",\n 5\n );\n Module["_FORM_OnKeyDown"] = createExportWrapper("FORM_OnKeyDown", 4);\n Module["_FORM_OnKeyUp"] = createExportWrapper("FORM_OnKeyUp", 4);\n Module["_FORM_OnChar"] = createExportWrapper("FORM_OnChar", 4);\n Module["_FORM_GetFocusedText"] = createExportWrapper(\n "FORM_GetFocusedText",\n 4\n );\n Module["_FORM_GetSelectedText"] = createExportWrapper(\n "FORM_GetSelectedText",\n 4\n );\n Module["_FORM_ReplaceAndKeepSelection"] = createExportWrapper("FORM_ReplaceAndKeepSelection", 3);\n Module["_FORM_ReplaceSelection"] = createExportWrapper(\n "FORM_ReplaceSelection",\n 3\n );\n Module["_FORM_SelectAllText"] = createExportWrapper(\n "FORM_SelectAllText",\n 2\n );\n Module["_FORM_CanUndo"] = createExportWrapper("FORM_CanUndo", 2);\n Module["_FORM_CanRedo"] = createExportWrapper("FORM_CanRedo", 2);\n Module["_FORM_Undo"] = createExportWrapper("FORM_Undo", 2);\n Module["_FORM_Redo"] = createExportWrapper("FORM_Redo", 2);\n Module["_FORM_ForceToKillFocus"] = createExportWrapper(\n "FORM_ForceToKillFocus",\n 1\n );\n Module["_FORM_GetFocusedAnnot"] = createExportWrapper(\n "FORM_GetFocusedAnnot",\n 3\n );\n Module["_FORM_SetFocusedAnnot"] = createExportWrapper(\n "FORM_SetFocusedAnnot",\n 2\n );\n Module["_FPDF_FFLDraw"] = createExportWrapper("FPDF_FFLDraw", 9);\n Module["_FPDF_SetFormFieldHighlightColor"] = createExportWrapper("FPDF_SetFormFieldHighlightColor", 3);\n Module["_FPDF_SetFormFieldHighlightAlpha"] = createExportWrapper("FPDF_SetFormFieldHighlightAlpha", 2);\n Module["_FPDF_RemoveFormFieldHighlight"] = createExportWrapper("FPDF_RemoveFormFieldHighlight", 1);\n Module["_FORM_OnAfterLoadPage"] = createExportWrapper(\n "FORM_OnAfterLoadPage",\n 2\n );\n Module["_FORM_OnBeforeClosePage"] = createExportWrapper(\n "FORM_OnBeforeClosePage",\n 2\n );\n Module["_FORM_DoDocumentJSAction"] = createExportWrapper(\n "FORM_DoDocumentJSAction",\n 1\n );\n Module["_FORM_DoDocumentOpenAction"] = createExportWrapper(\n "FORM_DoDocumentOpenAction",\n 1\n );\n Module["_FORM_DoDocumentAAction"] = createExportWrapper(\n "FORM_DoDocumentAAction",\n 2\n );\n Module["_FORM_DoPageAAction"] = createExportWrapper(\n "FORM_DoPageAAction",\n 3\n );\n Module["_FORM_SetIndexSelected"] = createExportWrapper(\n "FORM_SetIndexSelected",\n 4\n );\n Module["_FORM_IsIndexSelected"] = createExportWrapper(\n "FORM_IsIndexSelected",\n 3\n );\n Module["_FPDFDoc_GetJavaScriptActionCount"] = createExportWrapper("FPDFDoc_GetJavaScriptActionCount", 1);\n Module["_FPDFDoc_GetJavaScriptAction"] = createExportWrapper("FPDFDoc_GetJavaScriptAction", 2);\n Module["_FPDFDoc_CloseJavaScriptAction"] = createExportWrapper("FPDFDoc_CloseJavaScriptAction", 1);\n Module["_FPDFJavaScriptAction_GetName"] = createExportWrapper("FPDFJavaScriptAction_GetName", 3);\n Module["_FPDFJavaScriptAction_GetScript"] = createExportWrapper("FPDFJavaScriptAction_GetScript", 3);\n Module["_FPDF_ImportPagesByIndex"] = createExportWrapper(\n "FPDF_ImportPagesByIndex",\n 5\n );\n Module["_FPDF_ImportPages"] = createExportWrapper(\n "FPDF_ImportPages",\n 4\n );\n Module["_FPDF_ImportNPagesToOne"] = createExportWrapper(\n "FPDF_ImportNPagesToOne",\n 5\n );\n Module["_FPDF_NewXObjectFromPage"] = createExportWrapper(\n "FPDF_NewXObjectFromPage",\n 3\n );\n Module["_FPDF_CloseXObject"] = createExportWrapper(\n "FPDF_CloseXObject",\n 1\n );\n Module["_FPDF_NewFormObjectFromXObject"] = createExportWrapper("FPDF_NewFormObjectFromXObject", 1);\n Module["_FPDF_CopyViewerPreferences"] = createExportWrapper(\n "FPDF_CopyViewerPreferences",\n 2\n );\n Module["_FPDF_RenderPageBitmapWithColorScheme_Start"] = createExportWrapper("FPDF_RenderPageBitmapWithColorScheme_Start", 10);\n Module["_FPDF_RenderPageBitmap_Start"] = createExportWrapper("FPDF_RenderPageBitmap_Start", 9);\n Module["_FPDF_RenderPage_Continue"] = createExportWrapper(\n "FPDF_RenderPage_Continue",\n 2\n );\n Module["_FPDF_RenderPage_Close"] = createExportWrapper(\n "FPDF_RenderPage_Close",\n 1\n );\n Module["_FPDF_SaveWithVersion"] = createExportWrapper(\n "FPDF_SaveWithVersion",\n 4\n );\n Module["_FPDFText_GetCharIndexFromTextIndex"] = createExportWrapper("FPDFText_GetCharIndexFromTextIndex", 2);\n Module["_FPDFText_GetTextIndexFromCharIndex"] = createExportWrapper("FPDFText_GetTextIndexFromCharIndex", 2);\n Module["_FPDF_GetSignatureCount"] = createExportWrapper(\n "FPDF_GetSignatureCount",\n 1\n );\n Module["_FPDF_GetSignatureObject"] = createExportWrapper(\n "FPDF_GetSignatureObject",\n 2\n );\n Module["_FPDFSignatureObj_GetContents"] = createExportWrapper("FPDFSignatureObj_GetContents", 3);\n Module["_FPDFSignatureObj_GetByteRange"] = createExportWrapper("FPDFSignatureObj_GetByteRange", 3);\n Module["_FPDFSignatureObj_GetSubFilter"] = createExportWrapper("FPDFSignatureObj_GetSubFilter", 3);\n Module["_FPDFSignatureObj_GetReason"] = createExportWrapper(\n "FPDFSignatureObj_GetReason",\n 3\n );\n Module["_FPDFSignatureObj_GetTime"] = createExportWrapper(\n "FPDFSignatureObj_GetTime",\n 3\n );\n Module["_FPDFSignatureObj_GetDocMDPPermission"] = createExportWrapper("FPDFSignatureObj_GetDocMDPPermission", 1);\n Module["_FPDF_StructTree_GetForPage"] = createExportWrapper(\n "FPDF_StructTree_GetForPage",\n 1\n );\n Module["_FPDF_StructTree_Close"] = createExportWrapper(\n "FPDF_StructTree_Close",\n 1\n );\n Module["_FPDF_StructTree_CountChildren"] = createExportWrapper("FPDF_StructTree_CountChildren", 1);\n Module["_FPDF_StructTree_GetChildAtIndex"] = createExportWrapper("FPDF_StructTree_GetChildAtIndex", 2);\n Module["_FPDF_StructElement_GetAltText"] = createExportWrapper("FPDF_StructElement_GetAltText", 3);\n Module["_FPDF_StructElement_GetActualText"] = createExportWrapper("FPDF_StructElement_GetActualText", 3);\n Module["_FPDF_StructElement_GetID"] = createExportWrapper(\n "FPDF_StructElement_GetID",\n 3\n );\n Module["_FPDF_StructElement_GetLang"] = createExportWrapper(\n "FPDF_StructElement_GetLang",\n 3\n );\n Module["_FPDF_StructElement_GetAttributeCount"] = createExportWrapper("FPDF_StructElement_GetAttributeCount", 1);\n Module["_FPDF_StructElement_GetAttributeAtIndex"] = createExportWrapper("FPDF_StructElement_GetAttributeAtIndex", 2);\n Module["_FPDF_StructElement_GetStringAttribute"] = createExportWrapper("FPDF_StructElement_GetStringAttribute", 4);\n Module["_FPDF_StructElement_GetMarkedContentID"] = createExportWrapper("FPDF_StructElement_GetMarkedContentID", 1);\n Module["_FPDF_StructElement_GetType"] = createExportWrapper(\n "FPDF_StructElement_GetType",\n 3\n );\n Module["_FPDF_StructElement_GetObjType"] = createExportWrapper("FPDF_StructElement_GetObjType", 3);\n Module["_FPDF_StructElement_GetTitle"] = createExportWrapper("FPDF_StructElement_GetTitle", 3);\n Module["_FPDF_StructElement_CountChildren"] = createExportWrapper("FPDF_StructElement_CountChildren", 1);\n Module["_FPDF_StructElement_GetChildAtIndex"] = createExportWrapper("FPDF_StructElement_GetChildAtIndex", 2);\n Module["_FPDF_StructElement_GetChildMarkedContentID"] = createExportWrapper("FPDF_StructElement_GetChildMarkedContentID", 2);\n Module["_FPDF_StructElement_GetParent"] = createExportWrapper("FPDF_StructElement_GetParent", 1);\n Module["_FPDF_StructElement_Attr_GetCount"] = createExportWrapper("FPDF_StructElement_Attr_GetCount", 1);\n Module["_FPDF_StructElement_Attr_GetName"] = createExportWrapper("FPDF_StructElement_Attr_GetName", 5);\n Module["_FPDF_StructElement_Attr_GetValue"] = createExportWrapper("FPDF_StructElement_Attr_GetValue", 2);\n Module["_FPDF_StructElement_Attr_GetType"] = createExportWrapper("FPDF_StructElement_Attr_GetType", 1);\n Module["_FPDF_StructElement_Attr_GetBooleanValue"] = createExportWrapper("FPDF_StructElement_Attr_GetBooleanValue", 2);\n Module["_FPDF_StructElement_Attr_GetNumberValue"] = createExportWrapper("FPDF_StructElement_Attr_GetNumberValue", 2);\n Module["_FPDF_StructElement_Attr_GetStringValue"] = createExportWrapper("FPDF_StructElement_Attr_GetStringValue", 4);\n Module["_FPDF_StructElement_Attr_GetBlobValue"] = createExportWrapper("FPDF_StructElement_Attr_GetBlobValue", 4);\n Module["_FPDF_StructElement_Attr_CountChildren"] = createExportWrapper("FPDF_StructElement_Attr_CountChildren", 1);\n Module["_FPDF_StructElement_Attr_GetChildAtIndex"] = createExportWrapper("FPDF_StructElement_Attr_GetChildAtIndex", 2);\n Module["_FPDF_StructElement_GetMarkedContentIdCount"] = createExportWrapper("FPDF_StructElement_GetMarkedContentIdCount", 1);\n Module["_FPDF_StructElement_GetMarkedContentIdAtIndex"] = createExportWrapper("FPDF_StructElement_GetMarkedContentIdAtIndex", 2);\n Module["_FPDF_AddInstalledFont"] = createExportWrapper(\n "FPDF_AddInstalledFont",\n 3\n );\n Module["_FPDF_SetSystemFontInfo"] = createExportWrapper(\n "FPDF_SetSystemFontInfo",\n 1\n );\n Module["_FPDF_GetDefaultTTFMap"] = createExportWrapper(\n "FPDF_GetDefaultTTFMap",\n 0\n );\n Module["_FPDF_GetDefaultTTFMapCount"] = createExportWrapper(\n "FPDF_GetDefaultTTFMapCount",\n 0\n );\n Module["_FPDF_GetDefaultTTFMapEntry"] = createExportWrapper(\n "FPDF_GetDefaultTTFMapEntry",\n 1\n );\n Module["_FPDF_GetDefaultSystemFontInfo"] = createExportWrapper("FPDF_GetDefaultSystemFontInfo", 0);\n Module["_FPDF_FreeDefaultSystemFontInfo"] = createExportWrapper("FPDF_FreeDefaultSystemFontInfo", 1);\n Module["_FPDFText_LoadPage"] = createExportWrapper(\n "FPDFText_LoadPage",\n 1\n );\n Module["_FPDFText_ClosePage"] = createExportWrapper(\n "FPDFText_ClosePage",\n 1\n );\n Module["_FPDFText_CountChars"] = createExportWrapper(\n "FPDFText_CountChars",\n 1\n );\n Module["_FPDFText_GetUnicode"] = createExportWrapper(\n "FPDFText_GetUnicode",\n 2\n );\n Module["_FPDFText_GetTextObject"] = createExportWrapper(\n "FPDFText_GetTextObject",\n 2\n );\n Module["_FPDFText_IsGenerated"] = createExportWrapper(\n "FPDFText_IsGenerated",\n 2\n );\n Module["_FPDFText_IsHyphen"] = createExportWrapper(\n "FPDFText_IsHyphen",\n 2\n );\n Module["_FPDFText_HasUnicodeMapError"] = createExportWrapper("FPDFText_HasUnicodeMapError", 2);\n Module["_FPDFText_GetFontSize"] = createExportWrapper(\n "FPDFText_GetFontSize",\n 2\n );\n Module["_FPDFText_GetFontInfo"] = createExportWrapper(\n "FPDFText_GetFontInfo",\n 5\n );\n Module["_FPDFText_GetFontWeight"] = createExportWrapper(\n "FPDFText_GetFontWeight",\n 2\n );\n Module["_FPDFText_GetFillColor"] = createExportWrapper(\n "FPDFText_GetFillColor",\n 6\n );\n Module["_FPDFText_GetStrokeColor"] = createExportWrapper(\n "FPDFText_GetStrokeColor",\n 6\n );\n Module["_FPDFText_GetCharAngle"] = createExportWrapper(\n "FPDFText_GetCharAngle",\n 2\n );\n Module["_FPDFText_GetCharBox"] = createExportWrapper(\n "FPDFText_GetCharBox",\n 6\n );\n Module["_FPDFText_GetLooseCharBox"] = createExportWrapper(\n "FPDFText_GetLooseCharBox",\n 3\n );\n Module["_FPDFText_GetMatrix"] = createExportWrapper(\n "FPDFText_GetMatrix",\n 3\n );\n Module["_FPDFText_GetCharOrigin"] = createExportWrapper(\n "FPDFText_GetCharOrigin",\n 4\n );\n Module["_FPDFText_GetCharIndexAtPos"] = createExportWrapper(\n "FPDFText_GetCharIndexAtPos",\n 5\n );\n Module["_FPDFText_GetText"] = createExportWrapper(\n "FPDFText_GetText",\n 4\n );\n Module["_FPDFText_CountRects"] = createExportWrapper(\n "FPDFText_CountRects",\n 3\n );\n Module["_FPDFText_GetRect"] = createExportWrapper(\n "FPDFText_GetRect",\n 6\n );\n Module["_FPDFText_GetBoundedText"] = createExportWrapper(\n "FPDFText_GetBoundedText",\n 7\n );\n Module["_FPDFText_FindStart"] = createExportWrapper(\n "FPDFText_FindStart",\n 4\n );\n Module["_FPDFText_FindNext"] = createExportWrapper(\n "FPDFText_FindNext",\n 1\n );\n Module["_FPDFText_FindPrev"] = createExportWrapper(\n "FPDFText_FindPrev",\n 1\n );\n Module["_FPDFText_GetSchResultIndex"] = createExportWrapper(\n "FPDFText_GetSchResultIndex",\n 1\n );\n Module["_FPDFText_GetSchCount"] = createExportWrapper(\n "FPDFText_GetSchCount",\n 1\n );\n Module["_FPDFText_FindClose"] = createExportWrapper(\n "FPDFText_FindClose",\n 1\n );\n Module["_FPDFLink_LoadWebLinks"] = createExportWrapper(\n "FPDFLink_LoadWebLinks",\n 1\n );\n Module["_FPDFLink_CountWebLinks"] = createExportWrapper(\n "FPDFLink_CountWebLinks",\n 1\n );\n Module["_FPDFLink_GetURL"] = createExportWrapper("FPDFLink_GetURL", 4);\n Module["_FPDFLink_CountRects"] = createExportWrapper(\n "FPDFLink_CountRects",\n 2\n );\n Module["_FPDFLink_GetRect"] = createExportWrapper(\n "FPDFLink_GetRect",\n 7\n );\n Module["_FPDFLink_GetTextRange"] = createExportWrapper(\n "FPDFLink_GetTextRange",\n 4\n );\n Module["_FPDFLink_CloseWebLinks"] = createExportWrapper(\n "FPDFLink_CloseWebLinks",\n 1\n );\n Module["_FPDFPage_GetDecodedThumbnailData"] = createExportWrapper("FPDFPage_GetDecodedThumbnailData", 3);\n Module["_FPDFPage_GetRawThumbnailData"] = createExportWrapper("FPDFPage_GetRawThumbnailData", 3);\n Module["_FPDFPage_GetThumbnailAsBitmap"] = createExportWrapper("FPDFPage_GetThumbnailAsBitmap", 1);\n Module["_FPDFPage_SetMediaBox"] = createExportWrapper(\n "FPDFPage_SetMediaBox",\n 5\n );\n Module["_FPDFPage_SetCropBox"] = createExportWrapper(\n "FPDFPage_SetCropBox",\n 5\n );\n Module["_FPDFPage_SetBleedBox"] = createExportWrapper(\n "FPDFPage_SetBleedBox",\n 5\n );\n Module["_FPDFPage_SetTrimBox"] = createExportWrapper(\n "FPDFPage_SetTrimBox",\n 5\n );\n Module["_FPDFPage_SetArtBox"] = createExportWrapper(\n "FPDFPage_SetArtBox",\n 5\n );\n Module["_FPDFPage_GetMediaBox"] = createExportWrapper(\n "FPDFPage_GetMediaBox",\n 5\n );\n Module["_FPDFPage_GetCropBox"] = createExportWrapper(\n "FPDFPage_GetCropBox",\n 5\n );\n Module["_FPDFPage_GetBleedBox"] = createExportWrapper(\n "FPDFPage_GetBleedBox",\n 5\n );\n Module["_FPDFPage_GetTrimBox"] = createExportWrapper(\n "FPDFPage_GetTrimBox",\n 5\n );\n Module["_FPDFPage_GetArtBox"] = createExportWrapper(\n "FPDFPage_GetArtBox",\n 5\n );\n Module["_FPDFPage_TransFormWithClip"] = createExportWrapper(\n "FPDFPage_TransFormWithClip",\n 3\n );\n Module["_FPDFPageObj_TransformClipPath"] = createExportWrapper("FPDFPageObj_TransformClipPath", 7);\n Module["_FPDFPageObj_GetClipPath"] = createExportWrapper(\n "FPDFPageObj_GetClipPath",\n 1\n );\n Module["_FPDFClipPath_CountPaths"] = createExportWrapper(\n "FPDFClipPath_CountPaths",\n 1\n );\n Module["_FPDFClipPath_CountPathSegments"] = createExportWrapper("FPDFClipPath_CountPathSegments", 2);\n Module["_FPDFClipPath_GetPathSegment"] = createExportWrapper("FPDFClipPath_GetPathSegment", 3);\n Module["_FPDF_CreateClipPath"] = createExportWrapper(\n "FPDF_CreateClipPath",\n 4\n );\n Module["_FPDF_DestroyClipPath"] = createExportWrapper(\n "FPDF_DestroyClipPath",\n 1\n );\n Module["_FPDFPage_InsertClipPath"] = createExportWrapper(\n "FPDFPage_InsertClipPath",\n 2\n );\n Module["_FPDF_InitLibrary"] = createExportWrapper(\n "FPDF_InitLibrary",\n 0\n );\n Module["_FPDF_DestroyLibrary"] = createExportWrapper(\n "FPDF_DestroyLibrary",\n 0\n );\n Module["_FPDF_SetSandBoxPolicy"] = createExportWrapper(\n "FPDF_SetSandBoxPolicy",\n 2\n );\n Module["_FPDF_LoadDocument"] = createExportWrapper(\n "FPDF_LoadDocument",\n 2\n );\n Module["_FPDF_GetFormType"] = createExportWrapper(\n "FPDF_GetFormType",\n 1\n );\n Module["_FPDF_LoadXFA"] = createExportWrapper("FPDF_LoadXFA", 1);\n Module["_FPDF_LoadMemDocument"] = createExportWrapper(\n "FPDF_LoadMemDocument",\n 3\n );\n Module["_FPDF_LoadMemDocument64"] = createExportWrapper(\n "FPDF_LoadMemDocument64",\n 3\n );\n Module["_FPDF_LoadCustomDocument"] = createExportWrapper(\n "FPDF_LoadCustomDocument",\n 2\n );\n Module["_FPDF_GetFileVersion"] = createExportWrapper(\n "FPDF_GetFileVersion",\n 2\n );\n Module["_FPDF_DocumentHasValidCrossReferenceTable"] = createExportWrapper("FPDF_DocumentHasValidCrossReferenceTable", 1);\n Module["_FPDF_GetDocPermissions"] = createExportWrapper(\n "FPDF_GetDocPermissions",\n 1\n );\n Module["_FPDF_GetDocUserPermissions"] = createExportWrapper(\n "FPDF_GetDocUserPermissions",\n 1\n );\n Module["_FPDF_GetSecurityHandlerRevision"] = createExportWrapper("FPDF_GetSecurityHandlerRevision", 1);\n Module["_EPDF_SetEncryption"] = createExportWrapper(\n "EPDF_SetEncryption",\n 4\n );\n Module["_EPDF_RemoveEncryption"] = createExportWrapper(\n "EPDF_RemoveEncryption",\n 1\n );\n Module["_EPDF_UnlockOwnerPermissions"] = createExportWrapper("EPDF_UnlockOwnerPermissions", 2);\n Module["_EPDF_IsEncrypted"] = createExportWrapper(\n "EPDF_IsEncrypted",\n 1\n );\n Module["_EPDF_IsOwnerUnlocked"] = createExportWrapper(\n "EPDF_IsOwnerUnlocked",\n 1\n );\n Module["_FPDF_GetPageCount"] = createExportWrapper(\n "FPDF_GetPageCount",\n 1\n );\n Module["_FPDF_LoadPage"] = createExportWrapper("FPDF_LoadPage", 2);\n Module["_FPDF_GetPageWidthF"] = createExportWrapper(\n "FPDF_GetPageWidthF",\n 1\n );\n Module["_FPDF_GetPageWidth"] = createExportWrapper(\n "FPDF_GetPageWidth",\n 1\n );\n Module["_FPDF_GetPageHeightF"] = createExportWrapper(\n "FPDF_GetPageHeightF",\n 1\n );\n Module["_FPDF_GetPageHeight"] = createExportWrapper(\n "FPDF_GetPageHeight",\n 1\n );\n Module["_FPDF_GetPageBoundingBox"] = createExportWrapper(\n "FPDF_GetPageBoundingBox",\n 2\n );\n Module["_FPDF_RenderPageBitmap"] = createExportWrapper(\n "FPDF_RenderPageBitmap",\n 8\n );\n Module["_FPDF_RenderPageBitmapWithMatrix"] = createExportWrapper("FPDF_RenderPageBitmapWithMatrix", 5);\n Module["_EPDF_RenderAnnotBitmap"] = createExportWrapper(\n "EPDF_RenderAnnotBitmap",\n 6\n );\n Module["_EPDF_RenderAnnotBitmapUnrotated"] = createExportWrapper("EPDF_RenderAnnotBitmapUnrotated", 6);\n Module["_FPDF_ClosePage"] = createExportWrapper("FPDF_ClosePage", 1);\n Module["_FPDF_CloseDocument"] = createExportWrapper(\n "FPDF_CloseDocument",\n 1\n );\n Module["_FPDF_GetLastError"] = createExportWrapper(\n "FPDF_GetLastError",\n 0\n );\n Module["_FPDF_DeviceToPage"] = createExportWrapper(\n "FPDF_DeviceToPage",\n 10\n );\n Module["_FPDF_PageToDevice"] = createExportWrapper(\n "FPDF_PageToDevice",\n 10\n );\n Module["_FPDFBitmap_Create"] = createExportWrapper(\n "FPDFBitmap_Create",\n 3\n );\n Module["_FPDFBitmap_CreateEx"] = createExportWrapper(\n "FPDFBitmap_CreateEx",\n 5\n );\n Module["_FPDFBitmap_GetFormat"] = createExportWrapper(\n "FPDFBitmap_GetFormat",\n 1\n );\n Module["_FPDFBitmap_FillRect"] = createExportWrapper(\n "FPDFBitmap_FillRect",\n 6\n );\n Module["_FPDFBitmap_GetBuffer"] = createExportWrapper(\n "FPDFBitmap_GetBuffer",\n 1\n );\n Module["_FPDFBitmap_GetWidth"] = createExportWrapper(\n "FPDFBitmap_GetWidth",\n 1\n );\n Module["_FPDFBitmap_GetHeight"] = createExportWrapper(\n "FPDFBitmap_GetHeight",\n 1\n );\n Module["_FPDFBitmap_GetStride"] = createExportWrapper(\n "FPDFBitmap_GetStride",\n 1\n );\n Module["_FPDFBitmap_Destroy"] = createExportWrapper(\n "FPDFBitmap_Destroy",\n 1\n );\n Module["_FPDF_GetPageSizeByIndexF"] = createExportWrapper(\n "FPDF_GetPageSizeByIndexF",\n 3\n );\n Module["_EPDF_GetPageRotationByIndex"] = createExportWrapper("EPDF_GetPageRotationByIndex", 2);\n Module["_EPDF_GetPageSizeByIndexNormalized"] = createExportWrapper("EPDF_GetPageSizeByIndexNormalized", 3);\n Module["_EPDF_LoadPageNormalized"] = createExportWrapper(\n "EPDF_LoadPageNormalized",\n 3\n );\n Module["_FPDF_GetPageSizeByIndex"] = createExportWrapper(\n "FPDF_GetPageSizeByIndex",\n 4\n );\n Module["_FPDF_VIEWERREF_GetPrintScaling"] = createExportWrapper("FPDF_VIEWERREF_GetPrintScaling", 1);\n Module["_FPDF_VIEWERREF_GetNumCopies"] = createExportWrapper("FPDF_VIEWERREF_GetNumCopies", 1);\n Module["_FPDF_VIEWERREF_GetPrintPageRange"] = createExportWrapper("FPDF_VIEWERREF_GetPrintPageRange", 1);\n Module["_FPDF_VIEWERREF_GetPrintPageRangeCount"] = createExportWrapper("FPDF_VIEWERREF_GetPrintPageRangeCount", 1);\n Module["_FPDF_VIEWERREF_GetPrintPageRangeElement"] = createExportWrapper("FPDF_VIEWERREF_GetPrintPageRangeElement", 2);\n Module["_FPDF_VIEWERREF_GetDuplex"] = createExportWrapper(\n "FPDF_VIEWERREF_GetDuplex",\n 1\n );\n Module["_FPDF_VIEWERREF_GetName"] = createExportWrapper(\n "FPDF_VIEWERREF_GetName",\n 4\n );\n Module["_FPDF_CountNamedDests"] = createExportWrapper(\n "FPDF_CountNamedDests",\n 1\n );\n Module["_FPDF_GetNamedDestByName"] = createExportWrapper(\n "FPDF_GetNamedDestByName",\n 2\n );\n Module["_FPDF_GetNamedDest"] = createExportWrapper(\n "FPDF_GetNamedDest",\n 4\n );\n Module["_FPDF_GetXFAPacketCount"] = createExportWrapper(\n "FPDF_GetXFAPacketCount",\n 1\n );\n Module["_FPDF_GetXFAPacketName"] = createExportWrapper(\n "FPDF_GetXFAPacketName",\n 4\n );\n Module["_FPDF_GetXFAPacketContent"] = createExportWrapper(\n "FPDF_GetXFAPacketContent",\n 5\n );\n Module["_FPDF_GetTrailerEnds"] = createExportWrapper(\n "FPDF_GetTrailerEnds",\n 3\n );\n var _fflush = createExportWrapper("fflush", 1);\n var _emscripten_builtin_memalign = createExportWrapper("emscripten_builtin_memalign", 2);\n var _strerror = createExportWrapper("strerror", 1);\n var _setThrew = createExportWrapper("setThrew", 2);\n var _emscripten_stack_init = () => (_emscripten_stack_init = wasmExports["emscripten_stack_init"])();\n var _emscripten_stack_get_end = () => (_emscripten_stack_get_end = wasmExports["emscripten_stack_get_end"])();\n var __emscripten_stack_restore = (a0) => (__emscripten_stack_restore = wasmExports["_emscripten_stack_restore"])(a0);\n var __emscripten_stack_alloc = (a0) => (__emscripten_stack_alloc = wasmExports["_emscripten_stack_alloc"])(a0);\n var _emscripten_stack_get_current = () => (_emscripten_stack_get_current = wasmExports["emscripten_stack_get_current"])();\n Module["dynCall_j"] = createExportWrapper("dynCall_j", 1);\n Module["dynCall_ji"] = createExportWrapper("dynCall_ji", 2);\n Module["dynCall_iiij"] = createExportWrapper("dynCall_iiij", 5);\n Module["dynCall_jji"] = createExportWrapper("dynCall_jji", 4);\n Module["dynCall_iji"] = createExportWrapper("dynCall_iji", 4);\n Module["dynCall_viijii"] = createExportWrapper("dynCall_viijii", 7);\n Module["dynCall_jij"] = createExportWrapper("dynCall_jij", 4);\n Module["dynCall_iij"] = createExportWrapper("dynCall_iij", 4);\n Module["dynCall_iiji"] = createExportWrapper("dynCall_iiji", 5);\n Module["dynCall_jiji"] = createExportWrapper("dynCall_jiji", 5);\n Module["dynCall_iiiiij"] = createExportWrapper("dynCall_iiiiij", 7);\n Module["dynCall_iiiiijj"] = createExportWrapper("dynCall_iiiiijj", 9);\n Module["dynCall_iiiiiijj"] = createExportWrapper(\n "dynCall_iiiiiijj",\n 10\n );\n Module["dynCall_viji"] = createExportWrapper("dynCall_viji", 5);\n function invoke_viii(index, a1, a2, a3) {\n var sp = stackSave();\n try {\n getWasmTableEntry(index)(a1, a2, a3);\n } catch (e) {\n stackRestore(sp);\n if (e !== e + 0) throw e;\n _setThrew(1, 0);\n }\n }\n function invoke_ii(index, a1) {\n var sp = stackSave();\n try {\n return getWasmTableEntry(index)(a1);\n } catch (e) {\n stackRestore(sp);\n if (e !== e + 0) throw e;\n _setThrew(1, 0);\n }\n }\n function invoke_iii(index, a1, a2) {\n var sp = stackSave();\n try {\n return getWasmTableEntry(index)(a1, a2);\n } catch (e) {\n stackRestore(sp);\n if (e !== e + 0) throw e;\n _setThrew(1, 0);\n }\n }\n function invoke_iiii(index, a1, a2, a3) {\n var sp = stackSave();\n try {\n return getWasmTableEntry(index)(a1, a2, a3);\n } catch (e) {\n stackRestore(sp);\n if (e !== e + 0) throw e;\n _setThrew(1, 0);\n }\n }\n function invoke_viiii(index, a1, a2, a3, a4) {\n var sp = stackSave();\n try {\n getWasmTableEntry(index)(a1, a2, a3, a4);\n } catch (e) {\n stackRestore(sp);\n if (e !== e + 0) throw e;\n _setThrew(1, 0);\n }\n }\n function invoke_iiiii(index, a1, a2, a3, a4) {\n var sp = stackSave();\n try {\n return getWasmTableEntry(index)(a1, a2, a3, a4);\n } catch (e) {\n stackRestore(sp);\n if (e !== e + 0) throw e;\n _setThrew(1, 0);\n }\n }\n function invoke_v(index) {\n var sp = stackSave();\n try {\n getWasmTableEntry(index)();\n } catch (e) {\n stackRestore(sp);\n if (e !== e + 0) throw e;\n _setThrew(1, 0);\n }\n }\n function invoke_vii(index, a1, a2) {\n var sp = stackSave();\n try {\n getWasmTableEntry(index)(a1, a2);\n } catch (e) {\n stackRestore(sp);\n if (e !== e + 0) throw e;\n _setThrew(1, 0);\n }\n }\n function invoke_viiiiiiiii(index, a1, a2, a3, a4, a5, a6, a7, a8, a9) {\n var sp = stackSave();\n try {\n getWasmTableEntry(index)(a1, a2, a3, a4, a5, a6, a7, a8, a9);\n } catch (e) {\n stackRestore(sp);\n if (e !== e + 0) throw e;\n _setThrew(1, 0);\n }\n }\n Module["wasmExports"] = wasmExports;\n Module["ccall"] = ccall;\n Module["cwrap"] = cwrap;\n Module["addFunction"] = addFunction;\n Module["removeFunction"] = removeFunction;\n Module["setValue"] = setValue;\n Module["getValue"] = getValue;\n Module["UTF8ToString"] = UTF8ToString;\n Module["stringToUTF8"] = stringToUTF8;\n Module["UTF16ToString"] = UTF16ToString;\n Module["stringToUTF16"] = stringToUTF16;\n var missingLibrarySymbols = [\n "writeI53ToI64",\n "writeI53ToI64Clamped",\n "writeI53ToI64Signaling",\n "writeI53ToU64Clamped",\n "writeI53ToU64Signaling",\n "readI53FromI64",\n "readI53FromU64",\n "convertI32PairToI53",\n "convertU32PairToI53",\n "getTempRet0",\n "setTempRet0",\n "exitJS",\n "inetPton4",\n "inetNtop4",\n "inetPton6",\n "inetNtop6",\n "readSockaddr",\n "writeSockaddr",\n "emscriptenLog",\n "readEmAsmArgs",\n "jstoi_q",\n "listenOnce",\n "autoResumeAudioContext",\n "dynCallLegacy",\n "getDynCaller",\n "dynCall",\n "handleException",\n "keepRuntimeAlive",\n "runtimeKeepalivePush",\n "runtimeKeepalivePop",\n "callUserCallback",\n "maybeExit",\n "asmjsMangle",\n "HandleAllocator",\n "getNativeTypeSize",\n "STACK_SIZE",\n "STACK_ALIGN",\n "POINTER_SIZE",\n "ASSERTIONS",\n "reallyNegative",\n "unSign",\n "strLen",\n "reSign",\n "formatString",\n "intArrayToString",\n "AsciiToString",\n "lengthBytesUTF16",\n "UTF32ToString",\n "stringToUTF32",\n "lengthBytesUTF32",\n "stringToNewUTF8",\n "registerKeyEventCallback",\n "maybeCStringToJsString",\n "findEventTarget",\n "getBoundingClientRect",\n "fillMouseEventData",\n "registerMouseEventCallback",\n "registerWheelEventCallback",\n "registerUiEventCallback",\n "registerFocusEventCallback",\n "fillDeviceOrientationEventData",\n "registerDeviceOrientationEventCallback",\n "fillDeviceMotionEventData",\n "registerDeviceMotionEventCallback",\n "screenOrientation",\n "fillOrientationChangeEventData",\n "registerOrientationChangeEventCallback",\n "fillFullscreenChangeEventData",\n "registerFullscreenChangeEventCallback",\n "JSEvents_requestFullscreen",\n "JSEvents_resizeCanvasForFullscreen",\n "registerRestoreOldStyle",\n "hideEverythingExceptGivenElement",\n "restoreHiddenElements",\n "setLetterbox",\n "softFullscreenResizeWebGLRenderTarget",\n "doRequestFullscreen",\n "fillPointerlockChangeEventData",\n "registerPointerlockChangeEventCallback",\n "registerPointerlockErrorEventCallback",\n "requestPointerLock",\n "fillVisibilityChangeEventData",\n "registerVisibilityChangeEventCallback",\n "registerTouchEventCallback",\n "fillGamepadEventData",\n "registerGamepadEventCallback",\n "registerBeforeUnloadEventCallback",\n "fillBatteryEventData",\n "battery",\n "registerBatteryEventCallback",\n "setCanvasElementSize",\n "getCanvasElementSize",\n "jsStackTrace",\n "getCallstack",\n "convertPCtoSourceLocation",\n "checkWasiClock",\n "wasiRightsToMuslOFlags",\n "wasiOFlagsToMuslOFlags",\n "createDyncallWrapper",\n "safeSetTimeout",\n "setImmediateWrapped",\n "clearImmediateWrapped",\n "polyfillSetImmediate",\n "registerPostMainLoop",\n "registerPreMainLoop",\n "getPromise",\n "makePromise",\n "idsToPromises",\n "makePromiseCallback",\n "ExceptionInfo",\n "findMatchingCatch",\n "Browser_asyncPrepareDataCounter",\n "safeRequestAnimationFrame",\n "arraySum",\n "addDays",\n "getSocketFromFD",\n "getSocketAddress",\n "FS_unlink",\n "FS_mkdirTree",\n "_setNetworkCallback",\n "heapObjectForWebGLType",\n "toTypedArrayIndex",\n "webgl_enable_ANGLE_instanced_arrays",\n "webgl_enable_OES_vertex_array_object",\n "webgl_enable_WEBGL_draw_buffers",\n "webgl_enable_WEBGL_multi_draw",\n "webgl_enable_EXT_polygon_offset_clamp",\n "webgl_enable_EXT_clip_control",\n "webgl_enable_WEBGL_polygon_mode",\n "emscriptenWebGLGet",\n "computeUnpackAlignedImageSize",\n "colorChannelsInGlTextureFormat",\n "emscriptenWebGLGetTexPixelData",\n "emscriptenWebGLGetUniform",\n "webglGetUniformLocation",\n "webglPrepareUniformLocationsBeforeFirstUse",\n "webglGetLeftBracePos",\n "emscriptenWebGLGetVertexAttrib",\n "__glGetActiveAttribOrUniform",\n "writeGLArray",\n "registerWebGlEventCallback",\n "runAndAbortIfError",\n "ALLOC_NORMAL",\n "ALLOC_STACK",\n "allocate",\n "writeStringToMemory",\n "writeAsciiToMemory",\n "setErrNo",\n "demangle",\n "stackTrace"\n ];\n missingLibrarySymbols.forEach(missingLibrarySymbol);\n var unexportedSymbols = [\n "run",\n "addOnPreRun",\n "addOnInit",\n "addOnPreMain",\n "addOnExit",\n "addOnPostRun",\n "addRunDependency",\n "removeRunDependency",\n "out",\n "err",\n "callMain",\n "abort",\n "wasmMemory",\n "writeStackCookie",\n "checkStackCookie",\n "convertI32PairToI53Checked",\n "stackSave",\n "stackRestore",\n "stackAlloc",\n "ptrToString",\n "zeroMemory",\n "getHeapMax",\n "growMemory",\n "ENV",\n "ERRNO_CODES",\n "strError",\n "DNS",\n "Protocols",\n "Sockets",\n "initRandomFill",\n "randomFill",\n "timers",\n "warnOnce",\n "readEmAsmArgsArray",\n "jstoi_s",\n "getExecutableName",\n "asyncLoad",\n "alignMemory",\n "mmapAlloc",\n "wasmTable",\n "noExitRuntime",\n "getCFunc",\n "uleb128Encode",\n "sigToWasmTypes",\n "generateFuncType",\n "convertJsFunctionToWasm",\n "freeTableIndexes",\n "functionsInTableMap",\n "getEmptyTableSlot",\n "updateTableMap",\n "getFunctionAddress",\n "PATH",\n "PATH_FS",\n "UTF8Decoder",\n "UTF8ArrayToString",\n "stringToUTF8Array",\n "lengthBytesUTF8",\n "intArrayFromString",\n "stringToAscii",\n "UTF16Decoder",\n "stringToUTF8OnStack",\n "writeArrayToMemory",\n "JSEvents",\n "specialHTMLTargets",\n "findCanvasEventTarget",\n "currentFullscreenStrategy",\n "restoreOldWindowedStyle",\n "UNWIND_CACHE",\n "ExitStatus",\n "getEnvStrings",\n "doReadv",\n "doWritev",\n "promiseMap",\n "uncaughtExceptionCount",\n "exceptionLast",\n "exceptionCaught",\n "Browser",\n "getPreloadedImageData__data",\n "wget",\n "MONTH_DAYS_REGULAR",\n "MONTH_DAYS_LEAP",\n "MONTH_DAYS_REGULAR_CUMULATIVE",\n "MONTH_DAYS_LEAP_CUMULATIVE",\n "isLeapYear",\n "ydayFromDate",\n "SYSCALLS",\n "preloadPlugins",\n "FS_createPreloadedFile",\n "FS_modeStringToFlags",\n "FS_getMode",\n "FS_stdin_getChar_buffer",\n "FS_stdin_getChar",\n "FS_createPath",\n "FS_createDevice",\n "FS_readFile",\n "FS",\n "FS_createDataFile",\n "FS_createLazyFile",\n "MEMFS",\n "TTY",\n "PIPEFS",\n "SOCKFS",\n "tempFixedLengthArray",\n "miniTempWebGLFloatBuffers",\n "miniTempWebGLIntBuffers",\n "GL",\n "AL",\n "GLUT",\n "EGL",\n "GLEW",\n "IDBStore",\n "SDL",\n "SDL_gfx",\n "allocateUTF8",\n "allocateUTF8OnStack",\n "print",\n "printErr"\n ];\n unexportedSymbols.forEach(unexportedRuntimeSymbol);\n var calledRun;\n var calledPrerun;\n dependenciesFulfilled = function runCaller() {\n if (!calledRun) run();\n if (!calledRun) dependenciesFulfilled = runCaller;\n };\n function stackCheckInit() {\n _emscripten_stack_init();\n writeStackCookie();\n }\n function run() {\n if (runDependencies > 0) {\n return;\n }\n stackCheckInit();\n if (!calledPrerun) {\n calledPrerun = 1;\n preRun();\n if (runDependencies > 0) {\n return;\n }\n }\n function doRun() {\n var _a;\n if (calledRun) return;\n calledRun = 1;\n Module["calledRun"] = 1;\n if (ABORT) return;\n initRuntime();\n readyPromiseResolve(Module);\n (_a = Module["onRuntimeInitialized"]) == null ? void 0 : _a.call(Module);\n assert(\n !Module["_main"],\n \'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]\'\n );\n postRun();\n }\n if (Module["setStatus"]) {\n Module["setStatus"]("Running...");\n setTimeout(() => {\n setTimeout(() => Module["setStatus"](""), 1);\n doRun();\n }, 1);\n } else {\n doRun();\n }\n checkStackCookie();\n }\n if (Module["preInit"]) {\n if (typeof Module["preInit"] == "function") Module["preInit"] = [Module["preInit"]];\n while (Module["preInit"].length > 0) {\n Module["preInit"].pop()();\n }\n }\n run();\n moduleRtn = readyPromise;\n for (const prop of Object.keys(Module)) {\n if (!(prop in moduleArg)) {\n Object.defineProperty(moduleArg, prop, {\n configurable: true,\n get() {\n abort(\n `Access to module property (\'${prop}\') is no longer possible via the module constructor argument; Instead, use the result of the module constructor.`\n );\n }\n });\n }\n }\n return moduleRtn;\n };\n})();\nconst functions = {\n EPDF_GetMetaKeyCount: [["number", "boolean"], "number"],\n EPDF_GetMetaKeyName: [\n ["number", "number", "boolean", "number", "number"],\n "number"\n ],\n EPDF_GetMetaTrapped: [["number"], "number"],\n EPDF_GetPageRotationByIndex: [["number", "number"], "number"],\n EPDF_GetPageSizeByIndexNormalized: [["number", "number", "number"], "boolean"],\n EPDF_HasMetaText: [["number", "string"], "boolean"],\n EPDF_IsEncrypted: [["number"], "boolean"],\n EPDF_IsOwnerUnlocked: [["number"], "boolean"],\n EPDF_LoadPageNormalized: [["number", "number", "number"], "number"],\n EPDF_PNG_EncodeRGBA: [\n ["number", "number", "number", "number", "number", "number"],\n "number"\n ],\n EPDF_RemoveEncryption: [["number"], "boolean"],\n EPDF_RenderAnnotBitmap: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n EPDF_RenderAnnotBitmapUnrotated: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n EPDF_SetEncryption: [["number", "string", "string", "number"], "boolean"],\n EPDF_SetMetaText: [["number", "string", "number"], "boolean"],\n EPDF_SetMetaTrapped: [["number", "number"], "boolean"],\n EPDF_UnlockOwnerPermissions: [["number", "string"], "boolean"],\n EPDFAction_CreateGoTo: [["number", "number"], "number"],\n EPDFAction_CreateGoToNamed: [["number", "string"], "number"],\n EPDFAction_CreateLaunch: [["number", "number"], "number"],\n EPDFAction_CreateRemoteGoToByName: [["number", "number", "number"], "number"],\n EPDFAction_CreateRemoteGoToDest: [["number", "number", "number"], "number"],\n EPDFAction_CreateURI: [["number", "string"], "number"],\n EPDFAnnot_ApplyRedaction: [["number", "number"], "boolean"],\n EPDFAnnot_ClearColor: [["number", "number"], "boolean"],\n EPDFAnnot_ClearRectangleDifferences: [["number"], "boolean"],\n EPDFAnnot_Flatten: [["number", "number"], "boolean"],\n EPDFAnnot_GenerateAppearance: [["number"], "boolean"],\n EPDFAnnot_GenerateAppearanceWithBlend: [["number", "number"], "boolean"],\n EPDFAnnot_GetAPMatrix: [["number", "number", "number"], "boolean"],\n EPDFAnnot_GetAvailableAppearanceModes: [["number"], "number"],\n EPDFAnnot_GetBlendMode: [["number"], "number"],\n EPDFAnnot_GetBorderDashPattern: [["number", "number", "number"], "boolean"],\n EPDFAnnot_GetBorderDashPatternCount: [["number"], "number"],\n EPDFAnnot_GetBorderEffect: [["number", "number"], "boolean"],\n EPDFAnnot_GetBorderStyle: [["number", "number"], "number"],\n EPDFAnnot_GetColor: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n EPDFAnnot_GetDefaultAppearance: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n EPDFAnnot_GetExtendedRotation: [["number", "number"], "boolean"],\n EPDFAnnot_GetIcon: [["number"], "number"],\n EPDFAnnot_GetIntent: [["number", "number", "number"], "number"],\n EPDFAnnot_GetLineEndings: [["number", "number", "number"], "boolean"],\n EPDFAnnot_GetOpacity: [["number", "number"], "boolean"],\n EPDFAnnot_GetOverlayText: [["number", "number", "number"], "number"],\n EPDFAnnot_GetOverlayTextRepeat: [["number"], "boolean"],\n EPDFAnnot_GetRect: [["number", "number"], "boolean"],\n EPDFAnnot_GetRectangleDifferences: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n EPDFAnnot_GetReplyType: [["number"], "number"],\n EPDFAnnot_GetRichContent: [["number", "number", "number"], "number"],\n EPDFAnnot_GetRotate: [["number", "number"], "boolean"],\n EPDFAnnot_GetTextAlignment: [["number"], "number"],\n EPDFAnnot_GetUnrotatedRect: [["number", "number"], "boolean"],\n EPDFAnnot_GetVerticalAlignment: [["number"], "number"],\n EPDFAnnot_HasAppearanceStream: [["number", "number"], "boolean"],\n EPDFAnnot_SetAction: [["number", "number"], "boolean"],\n EPDFAnnot_SetAPMatrix: [["number", "number", "number"], "boolean"],\n EPDFAnnot_SetBorderDashPattern: [["number", "number", "number"], "boolean"],\n EPDFAnnot_SetBorderStyle: [["number", "number", "number"], "boolean"],\n EPDFAnnot_SetColor: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n EPDFAnnot_SetDefaultAppearance: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n EPDFAnnot_SetExtendedRotation: [["number", "number"], "boolean"],\n EPDFAnnot_SetIcon: [["number", "number"], "boolean"],\n EPDFAnnot_SetIntent: [["number", "string"], "boolean"],\n EPDFAnnot_SetLine: [["number", "number", "number"], "boolean"],\n EPDFAnnot_SetLineEndings: [["number", "number", "number"], "boolean"],\n EPDFAnnot_SetLinkedAnnot: [["number", "string", "number"], "boolean"],\n EPDFAnnot_SetOpacity: [["number", "number"], "boolean"],\n EPDFAnnot_SetOverlayText: [["number", "number"], "boolean"],\n EPDFAnnot_SetOverlayTextRepeat: [["number", "boolean"], "boolean"],\n EPDFAnnot_SetRectangleDifferences: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n EPDFAnnot_SetReplyType: [["number", "number"], "boolean"],\n EPDFAnnot_SetRotate: [["number", "number"], "boolean"],\n EPDFAnnot_SetTextAlignment: [["number", "number"], "boolean"],\n EPDFAnnot_SetUnrotatedRect: [["number", "number"], "boolean"],\n EPDFAnnot_SetVerticalAlignment: [["number", "number"], "boolean"],\n EPDFAnnot_SetVertices: [["number", "number", "number"], "boolean"],\n EPDFAnnot_UpdateAppearanceToRect: [["number", "number"], "boolean"],\n EPDFAttachment_GetDescription: [["number", "number", "number"], "number"],\n EPDFAttachment_GetIntegerValue: [["number", "string", "number"], "boolean"],\n EPDFAttachment_SetDescription: [["number", "number"], "boolean"],\n EPDFAttachment_SetSubtype: [["number", "string"], "boolean"],\n EPDFBookmark_AppendChild: [["number", "number", "number"], "number"],\n EPDFBookmark_Clear: [["number"], "boolean"],\n EPDFBookmark_ClearTarget: [["number"], "boolean"],\n EPDFBookmark_Create: [["number", "number"], "number"],\n EPDFBookmark_Delete: [["number", "number"], "boolean"],\n EPDFBookmark_InsertAfter: [["number", "number", "number", "number"], "number"],\n EPDFBookmark_SetAction: [["number", "number", "number"], "boolean"],\n EPDFBookmark_SetDest: [["number", "number", "number"], "boolean"],\n EPDFBookmark_SetTitle: [["number", "number"], "boolean"],\n EPDFCatalog_GetLanguage: [["number", "number", "number"], "number"],\n EPDFDest_CreateRemoteView: [\n ["number", "number", "number", "number", "number"],\n "number"\n ],\n EPDFDest_CreateRemoteXYZ: [\n ["number", "number", "boolean", "number", "boolean", "number", "boolean", "number"],\n "number"\n ],\n EPDFDest_CreateView: [["number", "number", "number", "number"], "number"],\n EPDFDest_CreateXYZ: [\n ["number", "boolean", "number", "boolean", "number", "boolean", "number"],\n "number"\n ],\n EPDFNamedDest_Remove: [["number", "string"], "boolean"],\n EPDFNamedDest_SetDest: [["number", "string", "number"], "boolean"],\n EPDFPage_ApplyRedactions: [["number"], "boolean"],\n EPDFPage_CreateAnnot: [["number", "number"], "number"],\n EPDFPage_GetAnnotByName: [["number", "number"], "number"],\n EPDFPage_GetAnnotCountRaw: [["number", "number"], "number"],\n EPDFPage_GetAnnotRaw: [["number", "number", "number"], "number"],\n EPDFPage_RemoveAnnotByName: [["number", "number"], "boolean"],\n EPDFPage_RemoveAnnotRaw: [["number", "number", "number"], "boolean"],\n EPDFText_RedactInQuads: [\n ["number", "number", "number", "boolean", "boolean"],\n "boolean"\n ],\n EPDFText_RedactInRect: [["number", "number", "boolean", "boolean"], "boolean"],\n FORM_CanRedo: [["number", "number"], "boolean"],\n FORM_CanUndo: [["number", "number"], "boolean"],\n FORM_DoDocumentAAction: [["number", "number"], null],\n FORM_DoDocumentJSAction: [["number"], null],\n FORM_DoDocumentOpenAction: [["number"], null],\n FORM_DoPageAAction: [["number", "number", "number"], null],\n FORM_ForceToKillFocus: [["number"], "boolean"],\n FORM_GetFocusedAnnot: [["number", "number", "number"], "boolean"],\n FORM_GetFocusedText: [["number", "number", "number", "number"], "number"],\n FORM_GetSelectedText: [["number", "number", "number", "number"], "number"],\n FORM_IsIndexSelected: [["number", "number", "number"], "boolean"],\n FORM_OnAfterLoadPage: [["number", "number"], null],\n FORM_OnBeforeClosePage: [["number", "number"], null],\n FORM_OnChar: [["number", "number", "number", "number"], "boolean"],\n FORM_OnFocus: [["number", "number", "number", "number", "number"], "boolean"],\n FORM_OnKeyDown: [["number", "number", "number", "number"], "boolean"],\n FORM_OnKeyUp: [["number", "number", "number", "number"], "boolean"],\n FORM_OnLButtonDoubleClick: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FORM_OnLButtonDown: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FORM_OnLButtonUp: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FORM_OnMouseMove: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FORM_OnMouseWheel: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FORM_OnRButtonDown: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FORM_OnRButtonUp: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FORM_Redo: [["number", "number"], "boolean"],\n FORM_ReplaceAndKeepSelection: [["number", "number", "number"], null],\n FORM_ReplaceSelection: [["number", "number", "number"], null],\n FORM_SelectAllText: [["number", "number"], "boolean"],\n FORM_SetFocusedAnnot: [["number", "number"], "boolean"],\n FORM_SetIndexSelected: [["number", "number", "number", "boolean"], "boolean"],\n FORM_Undo: [["number", "number"], "boolean"],\n FPDF_AddInstalledFont: [["number", "number", "number"], null],\n FPDF_CloseDocument: [["number"], null],\n FPDF_ClosePage: [["number"], null],\n FPDF_CloseXObject: [["number"], null],\n FPDF_CopyViewerPreferences: [["number", "number"], "boolean"],\n FPDF_CountNamedDests: [["number"], "number"],\n FPDF_CreateClipPath: [["number", "number", "number", "number"], "number"],\n FPDF_CreateNewDocument: [[], "number"],\n FPDF_DestroyClipPath: [["number"], null],\n FPDF_DestroyLibrary: [[], null],\n FPDF_DeviceToPage: [\n [\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number"\n ],\n "boolean"\n ],\n FPDF_DocumentHasValidCrossReferenceTable: [["number"], "boolean"],\n FPDF_FFLDraw: [\n [\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number"\n ],\n null\n ],\n FPDF_FreeDefaultSystemFontInfo: [["number"], null],\n FPDF_GetDefaultSystemFontInfo: [[], "number"],\n FPDF_GetDefaultTTFMap: [[], "number"],\n FPDF_GetDefaultTTFMapCount: [[], "number"],\n FPDF_GetDefaultTTFMapEntry: [["number"], "number"],\n FPDF_GetDocPermissions: [["number"], "number"],\n FPDF_GetDocUserPermissions: [["number"], "number"],\n FPDF_GetFileIdentifier: [["number", "number", "number", "number"], "number"],\n FPDF_GetFileVersion: [["number", "number"], "boolean"],\n FPDF_GetFormType: [["number"], "number"],\n FPDF_GetLastError: [[], "number"],\n FPDF_GetMetaText: [["number", "string", "number", "number"], "number"],\n FPDF_GetNamedDest: [["number", "number", "number", "number"], "number"],\n FPDF_GetNamedDestByName: [["number", "string"], "number"],\n FPDF_GetPageAAction: [["number", "number"], "number"],\n FPDF_GetPageBoundingBox: [["number", "number"], "boolean"],\n FPDF_GetPageCount: [["number"], "number"],\n FPDF_GetPageHeight: [["number"], "number"],\n FPDF_GetPageHeightF: [["number"], "number"],\n FPDF_GetPageLabel: [["number", "number", "number", "number"], "number"],\n FPDF_GetPageSizeByIndex: [["number", "number", "number", "number"], "number"],\n FPDF_GetPageSizeByIndexF: [["number", "number", "number"], "boolean"],\n FPDF_GetPageWidth: [["number"], "number"],\n FPDF_GetPageWidthF: [["number"], "number"],\n FPDF_GetSecurityHandlerRevision: [["number"], "number"],\n FPDF_GetSignatureCount: [["number"], "number"],\n FPDF_GetSignatureObject: [["number", "number"], "number"],\n FPDF_GetTrailerEnds: [["number", "number", "number"], "number"],\n FPDF_GetXFAPacketContent: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDF_GetXFAPacketCount: [["number"], "number"],\n FPDF_GetXFAPacketName: [["number", "number", "number", "number"], "number"],\n FPDF_ImportNPagesToOne: [\n ["number", "number", "number", "number", "number"],\n "number"\n ],\n FPDF_ImportPages: [["number", "number", "string", "number"], "boolean"],\n FPDF_ImportPagesByIndex: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDF_InitLibrary: [[], null],\n FPDF_InitLibraryWithConfig: [["number"], null],\n FPDF_LoadCustomDocument: [["number", "string"], "number"],\n FPDF_LoadDocument: [["number", "string"], "number"],\n FPDF_LoadMemDocument: [["number", "number", "string"], "number"],\n FPDF_LoadMemDocument64: [["number", "number", "string"], "number"],\n FPDF_LoadPage: [["number", "number"], "number"],\n FPDF_LoadXFA: [["number"], "boolean"],\n FPDF_MovePages: [["number", "number", "number", "number"], "boolean"],\n FPDF_NewFormObjectFromXObject: [["number"], "number"],\n FPDF_NewXObjectFromPage: [["number", "number", "number"], "number"],\n FPDF_PageToDevice: [\n [\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number"\n ],\n "boolean"\n ],\n FPDF_RemoveFormFieldHighlight: [["number"], null],\n FPDF_RenderPage_Close: [["number"], null],\n FPDF_RenderPage_Continue: [["number", "number"], "number"],\n FPDF_RenderPageBitmap: [\n ["number", "number", "number", "number", "number", "number", "number", "number"],\n null\n ],\n FPDF_RenderPageBitmap_Start: [\n [\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number"\n ],\n "number"\n ],\n FPDF_RenderPageBitmapWithColorScheme_Start: [\n [\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number"\n ],\n "number"\n ],\n FPDF_RenderPageBitmapWithMatrix: [\n ["number", "number", "number", "number", "number"],\n null\n ],\n FPDF_SaveAsCopy: [["number", "number", "number"], "boolean"],\n FPDF_SaveWithVersion: [["number", "number", "number", "number"], "boolean"],\n FPDF_SetFormFieldHighlightAlpha: [["number", "number"], null],\n FPDF_SetFormFieldHighlightColor: [["number", "number", "number"], null],\n FPDF_SetSandBoxPolicy: [["number", "boolean"], null],\n FPDF_SetSystemFontInfo: [["number"], null],\n FPDF_StructElement_Attr_CountChildren: [["number"], "number"],\n FPDF_StructElement_Attr_GetBlobValue: [\n ["number", "number", "number", "number"],\n "boolean"\n ],\n FPDF_StructElement_Attr_GetBooleanValue: [["number", "number"], "boolean"],\n FPDF_StructElement_Attr_GetChildAtIndex: [["number", "number"], "number"],\n FPDF_StructElement_Attr_GetCount: [["number"], "number"],\n FPDF_StructElement_Attr_GetName: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDF_StructElement_Attr_GetNumberValue: [["number", "number"], "boolean"],\n FPDF_StructElement_Attr_GetStringValue: [\n ["number", "number", "number", "number"],\n "boolean"\n ],\n FPDF_StructElement_Attr_GetType: [["number"], "number"],\n FPDF_StructElement_Attr_GetValue: [["number", "string"], "number"],\n FPDF_StructElement_CountChildren: [["number"], "number"],\n FPDF_StructElement_GetActualText: [["number", "number", "number"], "number"],\n FPDF_StructElement_GetAltText: [["number", "number", "number"], "number"],\n FPDF_StructElement_GetAttributeAtIndex: [["number", "number"], "number"],\n FPDF_StructElement_GetAttributeCount: [["number"], "number"],\n FPDF_StructElement_GetChildAtIndex: [["number", "number"], "number"],\n FPDF_StructElement_GetChildMarkedContentID: [["number", "number"], "number"],\n FPDF_StructElement_GetID: [["number", "number", "number"], "number"],\n FPDF_StructElement_GetLang: [["number", "number", "number"], "number"],\n FPDF_StructElement_GetMarkedContentID: [["number"], "number"],\n FPDF_StructElement_GetMarkedContentIdAtIndex: [["number", "number"], "number"],\n FPDF_StructElement_GetMarkedContentIdCount: [["number"], "number"],\n FPDF_StructElement_GetObjType: [["number", "number", "number"], "number"],\n FPDF_StructElement_GetParent: [["number"], "number"],\n FPDF_StructElement_GetStringAttribute: [\n ["number", "string", "number", "number"],\n "number"\n ],\n FPDF_StructElement_GetTitle: [["number", "number", "number"], "number"],\n FPDF_StructElement_GetType: [["number", "number", "number"], "number"],\n FPDF_StructTree_Close: [["number"], null],\n FPDF_StructTree_CountChildren: [["number"], "number"],\n FPDF_StructTree_GetChildAtIndex: [["number", "number"], "number"],\n FPDF_StructTree_GetForPage: [["number"], "number"],\n FPDF_VIEWERREF_GetDuplex: [["number"], "number"],\n FPDF_VIEWERREF_GetName: [["number", "string", "number", "number"], "number"],\n FPDF_VIEWERREF_GetNumCopies: [["number"], "number"],\n FPDF_VIEWERREF_GetPrintPageRange: [["number"], "number"],\n FPDF_VIEWERREF_GetPrintPageRangeCount: [["number"], "number"],\n FPDF_VIEWERREF_GetPrintPageRangeElement: [["number", "number"], "number"],\n FPDF_VIEWERREF_GetPrintScaling: [["number"], "boolean"],\n FPDFAction_GetDest: [["number", "number"], "number"],\n FPDFAction_GetFilePath: [["number", "number", "number"], "number"],\n FPDFAction_GetType: [["number"], "number"],\n FPDFAction_GetURIPath: [["number", "number", "number", "number"], "number"],\n FPDFAnnot_AddFileAttachment: [["number", "number"], "number"],\n FPDFAnnot_AddInkStroke: [["number", "number", "number"], "number"],\n FPDFAnnot_AppendAttachmentPoints: [["number", "number"], "boolean"],\n FPDFAnnot_AppendObject: [["number", "number"], "boolean"],\n FPDFAnnot_CountAttachmentPoints: [["number"], "number"],\n FPDFAnnot_GetAP: [["number", "number", "number", "number"], "number"],\n FPDFAnnot_GetAttachmentPoints: [["number", "number", "number"], "boolean"],\n FPDFAnnot_GetBorder: [["number", "number", "number", "number"], "boolean"],\n FPDFAnnot_GetColor: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFAnnot_GetFileAttachment: [["number"], "number"],\n FPDFAnnot_GetFlags: [["number"], "number"],\n FPDFAnnot_GetFocusableSubtypes: [["number", "number", "number"], "boolean"],\n FPDFAnnot_GetFocusableSubtypesCount: [["number"], "number"],\n FPDFAnnot_GetFontColor: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFAnnot_GetFontSize: [["number", "number", "number"], "boolean"],\n FPDFAnnot_GetFormAdditionalActionJavaScript: [\n ["number", "number", "number", "number", "number"],\n "number"\n ],\n FPDFAnnot_GetFormControlCount: [["number", "number"], "number"],\n FPDFAnnot_GetFormControlIndex: [["number", "number"], "number"],\n FPDFAnnot_GetFormFieldAlternateName: [\n ["number", "number", "number", "number"],\n "number"\n ],\n FPDFAnnot_GetFormFieldAtPoint: [["number", "number", "number"], "number"],\n FPDFAnnot_GetFormFieldExportValue: [\n ["number", "number", "number", "number"],\n "number"\n ],\n FPDFAnnot_GetFormFieldFlags: [["number", "number"], "number"],\n FPDFAnnot_GetFormFieldName: [\n ["number", "number", "number", "number"],\n "number"\n ],\n FPDFAnnot_GetFormFieldType: [["number", "number"], "number"],\n FPDFAnnot_GetFormFieldValue: [\n ["number", "number", "number", "number"],\n "number"\n ],\n FPDFAnnot_GetInkListCount: [["number"], "number"],\n FPDFAnnot_GetInkListPath: [["number", "number", "number", "number"], "number"],\n FPDFAnnot_GetLine: [["number", "number", "number"], "boolean"],\n FPDFAnnot_GetLink: [["number"], "number"],\n FPDFAnnot_GetLinkedAnnot: [["number", "string"], "number"],\n FPDFAnnot_GetNumberValue: [["number", "string", "number"], "boolean"],\n FPDFAnnot_GetObject: [["number", "number"], "number"],\n FPDFAnnot_GetObjectCount: [["number"], "number"],\n FPDFAnnot_GetOptionCount: [["number", "number"], "number"],\n FPDFAnnot_GetOptionLabel: [\n ["number", "number", "number", "number", "number"],\n "number"\n ],\n FPDFAnnot_GetRect: [["number", "number"], "boolean"],\n FPDFAnnot_GetStringValue: [["number", "string", "number", "number"], "number"],\n FPDFAnnot_GetSubtype: [["number"], "number"],\n FPDFAnnot_GetValueType: [["number", "string"], "number"],\n FPDFAnnot_GetVertices: [["number", "number", "number"], "number"],\n FPDFAnnot_HasAttachmentPoints: [["number"], "boolean"],\n FPDFAnnot_HasKey: [["number", "string"], "boolean"],\n FPDFAnnot_IsChecked: [["number", "number"], "boolean"],\n FPDFAnnot_IsObjectSupportedSubtype: [["number"], "boolean"],\n FPDFAnnot_IsOptionSelected: [["number", "number", "number"], "boolean"],\n FPDFAnnot_IsSupportedSubtype: [["number"], "boolean"],\n FPDFAnnot_RemoveInkList: [["number"], "boolean"],\n FPDFAnnot_RemoveObject: [["number", "number"], "boolean"],\n FPDFAnnot_SetAP: [["number", "number", "number"], "boolean"],\n FPDFAnnot_SetAttachmentPoints: [["number", "number", "number"], "boolean"],\n FPDFAnnot_SetBorder: [["number", "number", "number", "number"], "boolean"],\n FPDFAnnot_SetColor: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFAnnot_SetFlags: [["number", "number"], "boolean"],\n FPDFAnnot_SetFocusableSubtypes: [["number", "number", "number"], "boolean"],\n FPDFAnnot_SetFontColor: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFAnnot_SetFormFieldFlags: [["number", "number", "number"], "boolean"],\n FPDFAnnot_SetRect: [["number", "number"], "boolean"],\n FPDFAnnot_SetStringValue: [["number", "string", "number"], "boolean"],\n FPDFAnnot_SetURI: [["number", "number"], "boolean"],\n FPDFAnnot_UpdateObject: [["number", "number"], "boolean"],\n FPDFAttachment_GetFile: [["number", "number", "number", "number"], "boolean"],\n FPDFAttachment_GetName: [["number", "number", "number"], "number"],\n FPDFAttachment_GetStringValue: [\n ["number", "string", "number", "number"],\n "number"\n ],\n FPDFAttachment_GetSubtype: [["number", "number", "number"], "number"],\n FPDFAttachment_GetValueType: [["number", "string"], "number"],\n FPDFAttachment_HasKey: [["number", "string"], "boolean"],\n FPDFAttachment_SetFile: [["number", "number", "number", "number"], "boolean"],\n FPDFAttachment_SetStringValue: [["number", "string", "number"], "boolean"],\n FPDFAvail_Create: [["number", "number"], "number"],\n FPDFAvail_Destroy: [["number"], null],\n FPDFAvail_GetDocument: [["number", "string"], "number"],\n FPDFAvail_GetFirstPageNum: [["number"], "number"],\n FPDFAvail_IsDocAvail: [["number", "number"], "number"],\n FPDFAvail_IsFormAvail: [["number", "number"], "number"],\n FPDFAvail_IsLinearized: [["number"], "number"],\n FPDFAvail_IsPageAvail: [["number", "number", "number"], "number"],\n FPDFBitmap_Create: [["number", "number", "number"], "number"],\n FPDFBitmap_CreateEx: [\n ["number", "number", "number", "number", "number"],\n "number"\n ],\n FPDFBitmap_Destroy: [["number"], null],\n FPDFBitmap_FillRect: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFBitmap_GetBuffer: [["number"], "number"],\n FPDFBitmap_GetFormat: [["number"], "number"],\n FPDFBitmap_GetHeight: [["number"], "number"],\n FPDFBitmap_GetStride: [["number"], "number"],\n FPDFBitmap_GetWidth: [["number"], "number"],\n FPDFBookmark_Find: [["number", "number"], "number"],\n FPDFBookmark_GetAction: [["number"], "number"],\n FPDFBookmark_GetCount: [["number"], "number"],\n FPDFBookmark_GetDest: [["number", "number"], "number"],\n FPDFBookmark_GetFirstChild: [["number", "number"], "number"],\n FPDFBookmark_GetNextSibling: [["number", "number"], "number"],\n FPDFBookmark_GetTitle: [["number", "number", "number"], "number"],\n FPDFCatalog_GetLanguage: [["number", "number", "number"], "number"],\n FPDFCatalog_IsTagged: [["number"], "boolean"],\n FPDFCatalog_SetLanguage: [["number", "number"], "boolean"],\n FPDFClipPath_CountPaths: [["number"], "number"],\n FPDFClipPath_CountPathSegments: [["number", "number"], "number"],\n FPDFClipPath_GetPathSegment: [["number", "number", "number"], "number"],\n FPDFDest_GetDestPageIndex: [["number", "number"], "number"],\n FPDFDest_GetLocationInPage: [\n ["number", "number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFDest_GetView: [["number", "number", "number"], "number"],\n FPDFDoc_AddAttachment: [["number", "number"], "number"],\n FPDFDoc_CloseJavaScriptAction: [["number"], null],\n FPDFDoc_DeleteAttachment: [["number", "number"], "boolean"],\n FPDFDOC_ExitFormFillEnvironment: [["number"], null],\n FPDFDoc_GetAttachment: [["number", "number"], "number"],\n FPDFDoc_GetAttachmentCount: [["number"], "number"],\n FPDFDoc_GetJavaScriptAction: [["number", "number"], "number"],\n FPDFDoc_GetJavaScriptActionCount: [["number"], "number"],\n FPDFDoc_GetPageMode: [["number"], "number"],\n FPDFDOC_InitFormFillEnvironment: [["number", "number"], "number"],\n FPDFFont_Close: [["number"], null],\n FPDFFont_GetAscent: [["number", "number", "number"], "boolean"],\n FPDFFont_GetBaseFontName: [["number", "number", "number"], "number"],\n FPDFFont_GetDescent: [["number", "number", "number"], "boolean"],\n FPDFFont_GetFamilyName: [["number", "number", "number"], "number"],\n FPDFFont_GetFlags: [["number"], "number"],\n FPDFFont_GetFontData: [["number", "number", "number", "number"], "boolean"],\n FPDFFont_GetGlyphPath: [["number", "number", "number"], "number"],\n FPDFFont_GetGlyphWidth: [["number", "number", "number", "number"], "boolean"],\n FPDFFont_GetIsEmbedded: [["number"], "number"],\n FPDFFont_GetItalicAngle: [["number", "number"], "boolean"],\n FPDFFont_GetWeight: [["number"], "number"],\n FPDFFormObj_CountObjects: [["number"], "number"],\n FPDFFormObj_GetObject: [["number", "number"], "number"],\n FPDFFormObj_RemoveObject: [["number", "number"], "boolean"],\n FPDFGlyphPath_CountGlyphSegments: [["number"], "number"],\n FPDFGlyphPath_GetGlyphPathSegment: [["number", "number"], "number"],\n FPDFImageObj_GetBitmap: [["number"], "number"],\n FPDFImageObj_GetIccProfileDataDecoded: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFImageObj_GetImageDataDecoded: [["number", "number", "number"], "number"],\n FPDFImageObj_GetImageDataRaw: [["number", "number", "number"], "number"],\n FPDFImageObj_GetImageFilter: [\n ["number", "number", "number", "number"],\n "number"\n ],\n FPDFImageObj_GetImageFilterCount: [["number"], "number"],\n FPDFImageObj_GetImageMetadata: [["number", "number", "number"], "boolean"],\n FPDFImageObj_GetImagePixelSize: [["number", "number", "number"], "boolean"],\n FPDFImageObj_GetRenderedBitmap: [["number", "number", "number"], "number"],\n FPDFImageObj_LoadJpegFile: [\n ["number", "number", "number", "number"],\n "boolean"\n ],\n FPDFImageObj_LoadJpegFileInline: [\n ["number", "number", "number", "number"],\n "boolean"\n ],\n FPDFImageObj_SetBitmap: [["number", "number", "number", "number"], "boolean"],\n FPDFImageObj_SetMatrix: [\n ["number", "number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFJavaScriptAction_GetName: [["number", "number", "number"], "number"],\n FPDFJavaScriptAction_GetScript: [["number", "number", "number"], "number"],\n FPDFLink_CloseWebLinks: [["number"], null],\n FPDFLink_CountQuadPoints: [["number"], "number"],\n FPDFLink_CountRects: [["number", "number"], "number"],\n FPDFLink_CountWebLinks: [["number"], "number"],\n FPDFLink_Enumerate: [["number", "number", "number"], "boolean"],\n FPDFLink_GetAction: [["number"], "number"],\n FPDFLink_GetAnnot: [["number", "number"], "number"],\n FPDFLink_GetAnnotRect: [["number", "number"], "boolean"],\n FPDFLink_GetDest: [["number", "number"], "number"],\n FPDFLink_GetLinkAtPoint: [["number", "number", "number"], "number"],\n FPDFLink_GetLinkZOrderAtPoint: [["number", "number", "number"], "number"],\n FPDFLink_GetQuadPoints: [["number", "number", "number"], "boolean"],\n FPDFLink_GetRect: [\n ["number", "number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFLink_GetTextRange: [["number", "number", "number", "number"], "boolean"],\n FPDFLink_GetURL: [["number", "number", "number", "number"], "number"],\n FPDFLink_LoadWebLinks: [["number"], "number"],\n FPDFPage_CloseAnnot: [["number"], null],\n FPDFPage_CountObjects: [["number"], "number"],\n FPDFPage_CreateAnnot: [["number", "number"], "number"],\n FPDFPage_Delete: [["number", "number"], null],\n FPDFPage_Flatten: [["number", "number"], "number"],\n FPDFPage_FormFieldZOrderAtPoint: [\n ["number", "number", "number", "number"],\n "number"\n ],\n FPDFPage_GenerateContent: [["number"], "boolean"],\n FPDFPage_GetAnnot: [["number", "number"], "number"],\n FPDFPage_GetAnnotCount: [["number"], "number"],\n FPDFPage_GetAnnotIndex: [["number", "number"], "number"],\n FPDFPage_GetArtBox: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPage_GetBleedBox: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPage_GetCropBox: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPage_GetDecodedThumbnailData: [["number", "number", "number"], "number"],\n FPDFPage_GetMediaBox: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPage_GetObject: [["number", "number"], "number"],\n FPDFPage_GetRawThumbnailData: [["number", "number", "number"], "number"],\n FPDFPage_GetRotation: [["number"], "number"],\n FPDFPage_GetThumbnailAsBitmap: [["number"], "number"],\n FPDFPage_GetTrimBox: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPage_HasFormFieldAtPoint: [\n ["number", "number", "number", "number"],\n "number"\n ],\n FPDFPage_HasTransparency: [["number"], "boolean"],\n FPDFPage_InsertClipPath: [["number", "number"], null],\n FPDFPage_InsertObject: [["number", "number"], null],\n FPDFPage_InsertObjectAtIndex: [["number", "number", "number"], "boolean"],\n FPDFPage_New: [["number", "number", "number", "number"], "number"],\n FPDFPage_RemoveAnnot: [["number", "number"], "boolean"],\n FPDFPage_RemoveObject: [["number", "number"], "boolean"],\n FPDFPage_SetArtBox: [["number", "number", "number", "number", "number"], null],\n FPDFPage_SetBleedBox: [\n ["number", "number", "number", "number", "number"],\n null\n ],\n FPDFPage_SetCropBox: [["number", "number", "number", "number", "number"], null],\n FPDFPage_SetMediaBox: [\n ["number", "number", "number", "number", "number"],\n null\n ],\n FPDFPage_SetRotation: [["number", "number"], null],\n FPDFPage_SetTrimBox: [["number", "number", "number", "number", "number"], null],\n FPDFPage_TransformAnnots: [\n ["number", "number", "number", "number", "number", "number", "number"],\n null\n ],\n FPDFPage_TransFormWithClip: [["number", "number", "number"], "boolean"],\n FPDFPageObj_AddMark: [["number", "string"], "number"],\n FPDFPageObj_CountMarks: [["number"], "number"],\n FPDFPageObj_CreateNewPath: [["number", "number"], "number"],\n FPDFPageObj_CreateNewRect: [["number", "number", "number", "number"], "number"],\n FPDFPageObj_CreateTextObj: [["number", "number", "number"], "number"],\n FPDFPageObj_Destroy: [["number"], null],\n FPDFPageObj_GetBounds: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPageObj_GetClipPath: [["number"], "number"],\n FPDFPageObj_GetDashArray: [["number", "number", "number"], "boolean"],\n FPDFPageObj_GetDashCount: [["number"], "number"],\n FPDFPageObj_GetDashPhase: [["number", "number"], "boolean"],\n FPDFPageObj_GetFillColor: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPageObj_GetIsActive: [["number", "number"], "boolean"],\n FPDFPageObj_GetLineCap: [["number"], "number"],\n FPDFPageObj_GetLineJoin: [["number"], "number"],\n FPDFPageObj_GetMark: [["number", "number"], "number"],\n FPDFPageObj_GetMarkedContentID: [["number"], "number"],\n FPDFPageObj_GetMatrix: [["number", "number"], "boolean"],\n FPDFPageObj_GetRotatedBounds: [["number", "number"], "boolean"],\n FPDFPageObj_GetStrokeColor: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPageObj_GetStrokeWidth: [["number", "number"], "boolean"],\n FPDFPageObj_GetType: [["number"], "number"],\n FPDFPageObj_HasTransparency: [["number"], "boolean"],\n FPDFPageObj_NewImageObj: [["number"], "number"],\n FPDFPageObj_NewTextObj: [["number", "string", "number"], "number"],\n FPDFPageObj_RemoveMark: [["number", "number"], "boolean"],\n FPDFPageObj_SetBlendMode: [["number", "string"], null],\n FPDFPageObj_SetDashArray: [["number", "number", "number", "number"], "boolean"],\n FPDFPageObj_SetDashPhase: [["number", "number"], "boolean"],\n FPDFPageObj_SetFillColor: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPageObj_SetIsActive: [["number", "boolean"], "boolean"],\n FPDFPageObj_SetLineCap: [["number", "number"], "boolean"],\n FPDFPageObj_SetLineJoin: [["number", "number"], "boolean"],\n FPDFPageObj_SetMatrix: [["number", "number"], "boolean"],\n FPDFPageObj_SetStrokeColor: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPageObj_SetStrokeWidth: [["number", "number"], "boolean"],\n FPDFPageObj_Transform: [\n ["number", "number", "number", "number", "number", "number", "number"],\n null\n ],\n FPDFPageObj_TransformClipPath: [\n ["number", "number", "number", "number", "number", "number", "number"],\n null\n ],\n FPDFPageObj_TransformF: [["number", "number"], "boolean"],\n FPDFPageObjMark_CountParams: [["number"], "number"],\n FPDFPageObjMark_GetName: [["number", "number", "number", "number"], "boolean"],\n FPDFPageObjMark_GetParamBlobValue: [\n ["number", "string", "number", "number", "number"],\n "boolean"\n ],\n FPDFPageObjMark_GetParamFloatValue: [["number", "string", "number"], "boolean"],\n FPDFPageObjMark_GetParamIntValue: [["number", "string", "number"], "boolean"],\n FPDFPageObjMark_GetParamKey: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPageObjMark_GetParamStringValue: [\n ["number", "string", "number", "number", "number"],\n "boolean"\n ],\n FPDFPageObjMark_GetParamValueType: [["number", "string"], "number"],\n FPDFPageObjMark_RemoveParam: [["number", "number", "string"], "boolean"],\n FPDFPageObjMark_SetBlobParam: [\n ["number", "number", "number", "string", "number", "number"],\n "boolean"\n ],\n FPDFPageObjMark_SetFloatParam: [\n ["number", "number", "number", "string", "number"],\n "boolean"\n ],\n FPDFPageObjMark_SetIntParam: [\n ["number", "number", "number", "string", "number"],\n "boolean"\n ],\n FPDFPageObjMark_SetStringParam: [\n ["number", "number", "number", "string", "string"],\n "boolean"\n ],\n FPDFPath_BezierTo: [\n ["number", "number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPath_Close: [["number"], "boolean"],\n FPDFPath_CountSegments: [["number"], "number"],\n FPDFPath_GetDrawMode: [["number", "number", "number"], "boolean"],\n FPDFPath_GetPathSegment: [["number", "number"], "number"],\n FPDFPath_LineTo: [["number", "number", "number"], "boolean"],\n FPDFPath_MoveTo: [["number", "number", "number"], "boolean"],\n FPDFPath_SetDrawMode: [["number", "number", "boolean"], "boolean"],\n FPDFPathSegment_GetClose: [["number"], "boolean"],\n FPDFPathSegment_GetPoint: [["number", "number", "number"], "boolean"],\n FPDFPathSegment_GetType: [["number"], "number"],\n FPDFSignatureObj_GetByteRange: [["number", "number", "number"], "number"],\n FPDFSignatureObj_GetContents: [["number", "number", "number"], "number"],\n FPDFSignatureObj_GetDocMDPPermission: [["number"], "number"],\n FPDFSignatureObj_GetReason: [["number", "number", "number"], "number"],\n FPDFSignatureObj_GetSubFilter: [["number", "number", "number"], "number"],\n FPDFSignatureObj_GetTime: [["number", "number", "number"], "number"],\n FPDFText_ClosePage: [["number"], null],\n FPDFText_CountChars: [["number"], "number"],\n FPDFText_CountRects: [["number", "number", "number"], "number"],\n FPDFText_FindClose: [["number"], null],\n FPDFText_FindNext: [["number"], "boolean"],\n FPDFText_FindPrev: [["number"], "boolean"],\n FPDFText_FindStart: [["number", "number", "number", "number"], "number"],\n FPDFText_GetBoundedText: [\n ["number", "number", "number", "number", "number", "number", "number"],\n "number"\n ],\n FPDFText_GetCharAngle: [["number", "number"], "number"],\n FPDFText_GetCharBox: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFText_GetCharIndexAtPos: [\n ["number", "number", "number", "number", "number"],\n "number"\n ],\n FPDFText_GetCharIndexFromTextIndex: [["number", "number"], "number"],\n FPDFText_GetCharOrigin: [["number", "number", "number", "number"], "boolean"],\n FPDFText_GetFillColor: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFText_GetFontInfo: [\n ["number", "number", "number", "number", "number"],\n "number"\n ],\n FPDFText_GetFontSize: [["number", "number"], "number"],\n FPDFText_GetFontWeight: [["number", "number"], "number"],\n FPDFText_GetLooseCharBox: [["number", "number", "number"], "boolean"],\n FPDFText_GetMatrix: [["number", "number", "number"], "boolean"],\n FPDFText_GetRect: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFText_GetSchCount: [["number"], "number"],\n FPDFText_GetSchResultIndex: [["number"], "number"],\n FPDFText_GetStrokeColor: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFText_GetText: [["number", "number", "number", "number"], "number"],\n FPDFText_GetTextIndexFromCharIndex: [["number", "number"], "number"],\n FPDFText_GetTextObject: [["number", "number"], "number"],\n FPDFText_GetUnicode: [["number", "number"], "number"],\n FPDFText_HasUnicodeMapError: [["number", "number"], "number"],\n FPDFText_IsGenerated: [["number", "number"], "number"],\n FPDFText_IsHyphen: [["number", "number"], "number"],\n FPDFText_LoadCidType2Font: [\n ["number", "number", "number", "string", "number", "number"],\n "number"\n ],\n FPDFText_LoadFont: [\n ["number", "number", "number", "number", "boolean"],\n "number"\n ],\n FPDFText_LoadPage: [["number"], "number"],\n FPDFText_LoadStandardFont: [["number", "string"], "number"],\n FPDFText_SetCharcodes: [["number", "number", "number"], "boolean"],\n FPDFText_SetText: [["number", "number"], "boolean"],\n FPDFTextObj_GetFont: [["number"], "number"],\n FPDFTextObj_GetFontSize: [["number", "number"], "boolean"],\n FPDFTextObj_GetRenderedBitmap: [\n ["number", "number", "number", "number"],\n "number"\n ],\n FPDFTextObj_GetText: [["number", "number", "number", "number"], "number"],\n FPDFTextObj_GetTextRenderMode: [["number"], "number"],\n FPDFTextObj_SetTextRenderMode: [["number", "number"], "boolean"],\n PDFiumExt_CloseFileWriter: [["number"], null],\n PDFiumExt_CloseFormFillInfo: [["number"], null],\n PDFiumExt_ExitFormFillEnvironment: [["number"], null],\n PDFiumExt_GetFileWriterData: [["number", "number", "number"], "number"],\n PDFiumExt_GetFileWriterSize: [["number"], "number"],\n PDFiumExt_Init: [[], null],\n PDFiumExt_InitFormFillEnvironment: [["number", "number"], "number"],\n PDFiumExt_OpenFileWriter: [[], "number"],\n PDFiumExt_OpenFormFillInfo: [[], "number"],\n PDFiumExt_SaveAsCopy: [["number", "number"], "number"]\n};\nasync function createWrappedModule(pdfium) {\n const module = {\n pdfium\n };\n for (const key in functions) {\n const ident = key;\n const args = functions[ident][0];\n const ret = functions[ident][1];\n module[ident] = pdfium.cwrap(key, ret, args);\n }\n return module;\n}\nasync function init(moduleOverrides) {\n const pdfium = await createPdfium(moduleOverrides);\n return createWrappedModule(pdfium);\n}\nfunction readString(wasmModule, readChars, parseChars, defaultLength = 100) {\n let buffer = wasmModule.wasmExports.malloc(defaultLength);\n for (let i = 0; i < defaultLength; i++) {\n wasmModule.HEAP8[buffer + i] = 0;\n }\n const actualLength = readChars(buffer, defaultLength);\n let str;\n if (actualLength > defaultLength) {\n wasmModule.wasmExports.free(buffer);\n buffer = wasmModule.wasmExports.malloc(actualLength);\n for (let i = 0; i < actualLength; i++) {\n wasmModule.HEAP8[buffer + i] = 0;\n }\n readChars(buffer, actualLength);\n str = parseChars(buffer);\n } else {\n str = parseChars(buffer);\n }\n wasmModule.wasmExports.free(buffer);\n return str;\n}\nfunction readArrayBuffer(wasmModule, readChars) {\n const bufferSize = readChars(0, 0);\n const bufferPtr = wasmModule.wasmExports.malloc(bufferSize);\n readChars(bufferPtr, bufferSize);\n const arrayBuffer = new ArrayBuffer(bufferSize);\n const view = new DataView(arrayBuffer);\n for (let i = 0; i < bufferSize; i++) {\n view.setInt8(i, wasmModule.getValue(bufferPtr + i, "i8"));\n }\n wasmModule.wasmExports.free(bufferPtr);\n return arrayBuffer;\n}\nconst RESERVED_INFO_KEYS = /* @__PURE__ */ new Set([\n "Title",\n "Author",\n "Subject",\n "Keywords",\n "Producer",\n "Creator",\n "CreationDate",\n "ModDate",\n "Trapped"\n]);\nfunction isValidCustomKey(key) {\n if (!key || key.length > 127) return false;\n if (RESERVED_INFO_KEYS.has(key)) return false;\n if (key[0] === "/") return false;\n for (let i = 0; i < key.length; i++) {\n const c = key.charCodeAt(i);\n if (c < 32 || c > 126) return false;\n }\n return true;\n}\nfunction computeFormDrawParams(matrix, rect, pageSize, rotation) {\n const rectLeft = rect.origin.x;\n const rectBottom = rect.origin.y;\n const rectRight = rectLeft + rect.size.width;\n const rectTop = rectBottom + rect.size.height;\n const pageWidth = pageSize.width;\n const pageHeight = pageSize.height;\n const scaleX = Math.hypot(matrix.a, matrix.b);\n const scaleY = Math.hypot(matrix.c, matrix.d);\n const swap2 = (rotation & 1) === 1;\n const formsWidth = swap2 ? Math.max(1, Math.round(pageHeight * scaleX)) : Math.max(1, Math.round(pageWidth * scaleX));\n const formsHeight = swap2 ? Math.max(1, Math.round(pageWidth * scaleY)) : Math.max(1, Math.round(pageHeight * scaleY));\n let startX;\n let startY;\n switch (rotation) {\n case Rotation.Degree0:\n startX = -Math.round(rectLeft * scaleX);\n startY = -Math.round(rectBottom * scaleY);\n break;\n case Rotation.Degree90:\n startX = Math.round((rectTop - pageHeight) * scaleX);\n startY = -Math.round(rectLeft * scaleY);\n break;\n case Rotation.Degree180:\n startX = Math.round((rectRight - pageWidth) * scaleX);\n startY = Math.round((rectTop - pageHeight) * scaleY);\n break;\n case Rotation.Degree270:\n startX = -Math.round(rectBottom * scaleX);\n startY = Math.round((rectRight - pageWidth) * scaleY);\n break;\n default:\n startX = -Math.round(rectLeft * scaleX);\n startY = -Math.round(rectBottom * scaleY);\n break;\n }\n return { startX, startY, formsWidth, formsHeight, scaleX, scaleY };\n}\nconst WasmPointer = (ptr) => ptr;\nconst DEFAULT_CONFIG = {\n pageTtl: 5e3,\n // 5 seconds\n maxPagesPerDocument: 10,\n normalizeRotation: false\n};\nclass PdfCache {\n constructor(pdfium, memoryManager, config = {}) {\n this.pdfium = pdfium;\n this.memoryManager = memoryManager;\n this.docs = /* @__PURE__ */ new Map();\n this.config = { ...DEFAULT_CONFIG, ...config };\n }\n /** Open (or re-use) a document */\n setDocument(id, filePtr, docPtr, normalizeRotation = false) {\n let ctx = this.docs.get(id);\n if (!ctx) {\n const docConfig = { ...this.config, normalizeRotation };\n ctx = new DocumentContext(filePtr, docPtr, this.pdfium, this.memoryManager, docConfig);\n this.docs.set(id, ctx);\n }\n }\n /** Retrieve the DocumentContext for a given PdfDocumentObject */\n getContext(docId) {\n return this.docs.get(docId);\n }\n /** Close & fully release a document and all its pages */\n closeDocument(docId) {\n const ctx = this.docs.get(docId);\n if (!ctx) return false;\n ctx.dispose();\n this.docs.delete(docId);\n return true;\n }\n /** Close all documents */\n closeAllDocuments() {\n for (const ctx of this.docs.values()) {\n ctx.dispose();\n }\n this.docs.clear();\n }\n /** Update cache configuration for all existing documents */\n updateConfig(newConfig) {\n Object.assign(this.config, newConfig);\n for (const ctx of this.docs.values()) {\n ctx.updateConfig(this.config);\n }\n }\n /** Get current cache statistics */\n getCacheStats() {\n const pagesByDocument = {};\n let totalPages = 0;\n for (const [docId, ctx] of this.docs.entries()) {\n const pageCount = ctx.getCacheSize();\n pagesByDocument[docId] = pageCount;\n totalPages += pageCount;\n }\n return {\n documents: this.docs.size,\n totalPages,\n pagesByDocument\n };\n }\n}\nclass DocumentContext {\n constructor(filePtr, docPtr, pdfium, memoryManager, config) {\n this.filePtr = filePtr;\n this.docPtr = docPtr;\n this.memoryManager = memoryManager;\n this.normalizeRotation = config.normalizeRotation;\n this.pageCache = new PageCache(pdfium, docPtr, config);\n }\n /** Main accessor for pages */\n acquirePage(pageIdx) {\n return this.pageCache.acquire(pageIdx);\n }\n /** Scoped accessor for one-off / bulk operations */\n borrowPage(pageIdx, fn) {\n return this.pageCache.borrowPage(pageIdx, fn);\n }\n /** Update cache configuration */\n updateConfig(config) {\n this.pageCache.updateConfig(config);\n }\n /** Get number of pages currently in cache */\n getCacheSize() {\n return this.pageCache.size();\n }\n /** Tear down all pages + this document */\n dispose() {\n this.pageCache.forceReleaseAll();\n this.pageCache.pdf.FPDF_CloseDocument(this.docPtr);\n this.memoryManager.free(WasmPointer(this.filePtr));\n }\n}\nclass PageCache {\n constructor(pdf, docPtr, config) {\n this.pdf = pdf;\n this.docPtr = docPtr;\n this.cache = /* @__PURE__ */ new Map();\n this.accessOrder = [];\n this.config = config;\n }\n acquire(pageIdx) {\n let ctx = this.cache.get(pageIdx);\n if (!ctx) {\n this.evictIfNeeded();\n let pagePtr;\n if (this.config.normalizeRotation) {\n pagePtr = this.pdf.EPDF_LoadPageNormalized(this.docPtr, pageIdx, 0);\n } else {\n pagePtr = this.pdf.FPDF_LoadPage(this.docPtr, pageIdx);\n }\n ctx = new PageContext(this.pdf, this.docPtr, pageIdx, pagePtr, this.config.pageTtl, () => {\n this.cache.delete(pageIdx);\n this.removeFromAccessOrder(pageIdx);\n });\n this.cache.set(pageIdx, ctx);\n }\n this.updateAccessOrder(pageIdx);\n ctx.clearExpiryTimer();\n ctx.bumpRefCount();\n return ctx;\n }\n /** Helper: run a function "scoped" to a page.\n * – if the page was already cached → .release() (keeps TTL logic)\n * – if the page was loaded just now → .disposeImmediate() (free right away)\n */\n borrowPage(pageIdx, fn) {\n const existed = this.cache.has(pageIdx);\n const ctx = this.acquire(pageIdx);\n try {\n return fn(ctx);\n } finally {\n existed ? ctx.release() : ctx.disposeImmediate();\n }\n }\n forceReleaseAll() {\n for (const ctx of this.cache.values()) {\n ctx.disposeImmediate();\n }\n this.cache.clear();\n this.accessOrder.length = 0;\n }\n /** Update cache configuration */\n updateConfig(config) {\n this.config = config;\n for (const ctx of this.cache.values()) {\n ctx.updateTtl(config.pageTtl);\n }\n this.evictIfNeeded();\n }\n /** Get current cache size */\n size() {\n return this.cache.size;\n }\n /** Evict least recently used pages if cache exceeds max size */\n evictIfNeeded() {\n while (this.cache.size >= this.config.maxPagesPerDocument) {\n const lruPageIdx = this.accessOrder[0];\n if (lruPageIdx !== void 0) {\n const ctx = this.cache.get(lruPageIdx);\n if (ctx) {\n if (ctx.getRefCount() === 0) {\n ctx.disposeImmediate();\n } else {\n break;\n }\n } else {\n this.removeFromAccessOrder(lruPageIdx);\n }\n } else {\n break;\n }\n }\n }\n /** Update the access order for LRU tracking */\n updateAccessOrder(pageIdx) {\n this.removeFromAccessOrder(pageIdx);\n this.accessOrder.push(pageIdx);\n }\n /** Remove a page from the access order array */\n removeFromAccessOrder(pageIdx) {\n const index = this.accessOrder.indexOf(pageIdx);\n if (index > -1) {\n this.accessOrder.splice(index, 1);\n }\n }\n}\nclass PageContext {\n constructor(pdf, docPtr, pageIdx, pagePtr, ttl, onFinalDispose) {\n this.pdf = pdf;\n this.docPtr = docPtr;\n this.pageIdx = pageIdx;\n this.pagePtr = pagePtr;\n this.onFinalDispose = onFinalDispose;\n this.refCount = 0;\n this.disposed = false;\n this.ttl = ttl;\n }\n /** Called by PageCache.acquire() */\n bumpRefCount() {\n if (this.disposed) throw new Error("Context already disposed");\n this.refCount++;\n }\n /** Get current reference count */\n getRefCount() {\n return this.refCount;\n }\n /** Called by PageCache.acquire() */\n clearExpiryTimer() {\n if (this.expiryTimer) {\n clearTimeout(this.expiryTimer);\n this.expiryTimer = void 0;\n }\n }\n /** Update TTL configuration */\n updateTtl(newTtl) {\n this.ttl = newTtl;\n if (this.expiryTimer && this.refCount === 0) {\n this.clearExpiryTimer();\n this.expiryTimer = setTimeout(() => this.disposeImmediate(), this.ttl);\n }\n }\n /** Called by PageCache.release() internally */\n release() {\n if (this.disposed) return;\n this.refCount--;\n if (this.refCount === 0) {\n this.expiryTimer = setTimeout(() => this.disposeImmediate(), this.ttl);\n }\n }\n /** Tear down _all_ sub-pointers & the page. */\n disposeImmediate() {\n if (this.disposed) return;\n this.disposed = true;\n this.clearExpiryTimer();\n if (this.textPagePtr !== void 0) {\n this.pdf.FPDFText_ClosePage(this.textPagePtr);\n }\n if (this.formHandle !== void 0) {\n this.pdf.FORM_OnBeforeClosePage(this.pagePtr, this.formHandle);\n this.pdf.PDFiumExt_ExitFormFillEnvironment(this.formHandle);\n }\n if (this.formInfoPtr !== void 0) {\n this.pdf.PDFiumExt_CloseFormFillInfo(this.formInfoPtr);\n }\n this.pdf.FPDF_ClosePage(this.pagePtr);\n this.onFinalDispose();\n }\n // ── public helpers ──\n /** Always safe: opens (once) and returns the text-page ptr. */\n getTextPage() {\n this.ensureAlive();\n if (this.textPagePtr === void 0) {\n this.textPagePtr = this.pdf.FPDFText_LoadPage(this.pagePtr);\n }\n return this.textPagePtr;\n }\n /** Always safe: opens (once) and returns the form-fill handle. */\n getFormHandle() {\n this.ensureAlive();\n if (this.formHandle === void 0) {\n this.formInfoPtr = this.pdf.PDFiumExt_OpenFormFillInfo();\n this.formHandle = this.pdf.PDFiumExt_InitFormFillEnvironment(this.docPtr, this.formInfoPtr);\n this.pdf.FORM_OnAfterLoadPage(this.pagePtr, this.formHandle);\n }\n return this.formHandle;\n }\n /**\n * Safely execute `fn` with an annotation pointer.\n * Pointer is ALWAYS closed afterwards.\n */\n withAnnotation(annotIdx, fn) {\n this.ensureAlive();\n const annotPtr = this.pdf.FPDFPage_GetAnnot(this.pagePtr, annotIdx);\n try {\n return fn(annotPtr);\n } finally {\n this.pdf.FPDFPage_CloseAnnot(annotPtr);\n }\n }\n ensureAlive() {\n if (this.disposed) throw new Error("PageContext already disposed");\n }\n}\nconst MEMORY_LIMITS = {\n /** Maximum total memory that can be allocated (2GB) */\n MAX_TOTAL_MEMORY: 2 * 1024 * 1024 * 1024\n};\nconst LIMITS = {\n MEMORY: MEMORY_LIMITS\n};\nconst LOG_SOURCE$3 = "PDFiumEngine";\nconst LOG_CATEGORY$3 = "MemoryManager";\nclass MemoryManager {\n constructor(pdfiumModule, logger) {\n this.pdfiumModule = pdfiumModule;\n this.logger = logger;\n this.allocations = /* @__PURE__ */ new Map();\n this.totalAllocated = 0;\n }\n /**\n * Allocate memory with tracking and validation\n */\n malloc(size) {\n if (this.totalAllocated + size > LIMITS.MEMORY.MAX_TOTAL_MEMORY) {\n throw new Error(\n `Total memory usage would exceed limit: ${this.totalAllocated + size} > ${LIMITS.MEMORY.MAX_TOTAL_MEMORY}`\n );\n }\n const ptr = this.pdfiumModule.pdfium.wasmExports.malloc(size);\n if (!ptr) {\n throw new Error(`Failed to allocate ${size} bytes`);\n }\n const allocation = {\n ptr: WasmPointer(ptr),\n size,\n timestamp: Date.now(),\n stack: this.logger.isEnabled("debug") ? new Error().stack : void 0\n };\n this.allocations.set(ptr, allocation);\n this.totalAllocated += size;\n return WasmPointer(ptr);\n }\n /**\n * Free memory with validation\n */\n free(ptr) {\n const allocation = this.allocations.get(ptr);\n if (!allocation) {\n this.logger.warn(LOG_SOURCE$3, LOG_CATEGORY$3, `Freeing untracked pointer: ${ptr}`);\n } else {\n this.totalAllocated -= allocation.size;\n this.allocations.delete(ptr);\n }\n this.pdfiumModule.pdfium.wasmExports.free(ptr);\n }\n /**\n * Get memory statistics\n */\n getStats() {\n return {\n totalAllocated: this.totalAllocated,\n allocationCount: this.allocations.size,\n allocations: this.logger.isEnabled("debug") ? Array.from(this.allocations.values()) : []\n };\n }\n /**\n * Check for memory leaks\n */\n checkLeaks() {\n if (this.allocations.size > 0) {\n this.logger.warn(\n LOG_SOURCE$3,\n LOG_CATEGORY$3,\n `Potential memory leak: ${this.allocations.size} unfreed allocations`\n );\n for (const [ptr, alloc] of this.allocations) {\n this.logger.warn(LOG_SOURCE$3, LOG_CATEGORY$3, ` - ${ptr}: ${alloc.size} bytes`, alloc.stack);\n }\n }\n }\n}\nconst SYSFONTINFO_SIZE = 36;\nconst OFFSET_VERSION = 0;\nconst OFFSET_RELEASE = 4;\nconst OFFSET_ENUMFONTS = 8;\nconst OFFSET_MAPFONT = 12;\nconst OFFSET_GETFONT = 16;\nconst OFFSET_GETFONTDATA = 20;\nconst OFFSET_GETFACENAME = 24;\nconst OFFSET_GETFONTCHARSET = 28;\nconst OFFSET_DELETEFONT = 32;\nconst LOG_SOURCE$2 = "pdfium";\nconst LOG_CATEGORY$2 = "font-fallback";\nclass FontFallbackManager {\n constructor(config, logger = new NoopLogger()) {\n this.fontHandles = /* @__PURE__ */ new Map();\n this.fontCache = /* @__PURE__ */ new Map();\n this.nextHandleId = 1;\n this.module = null;\n this.enabled = false;\n this.structPtr = 0;\n this.releaseFnPtr = 0;\n this.enumFontsFnPtr = 0;\n this.mapFontFnPtr = 0;\n this.getFontFnPtr = 0;\n this.getFontDataFnPtr = 0;\n this.getFaceNameFnPtr = 0;\n this.getFontCharsetFnPtr = 0;\n this.deleteFontFnPtr = 0;\n this.fontConfig = config;\n this.logger = logger;\n }\n /**\n * Initialize the font fallback system and attach to PDFium module\n */\n initialize(module) {\n if (this.enabled) {\n this.logger.warn(LOG_SOURCE$2, LOG_CATEGORY$2, "Font fallback already initialized");\n return;\n }\n this.module = module;\n const pdfium = module.pdfium;\n if (typeof pdfium.addFunction !== "function") {\n this.logger.error(\n LOG_SOURCE$2,\n LOG_CATEGORY$2,\n "addFunction not available. Make sure WASM is compiled with -sALLOW_TABLE_GROWTH"\n );\n return;\n }\n try {\n this.structPtr = pdfium.wasmExports.malloc(SYSFONTINFO_SIZE);\n if (!this.structPtr) {\n throw new Error("Failed to allocate FPDF_SYSFONTINFO struct");\n }\n for (let i = 0; i < SYSFONTINFO_SIZE; i++) {\n pdfium.setValue(this.structPtr + i, 0, "i8");\n }\n this.releaseFnPtr = pdfium.addFunction((_pThis) => {\n }, "vi");\n this.enumFontsFnPtr = pdfium.addFunction((_pThis, _pMapper) => {\n }, "vii");\n this.mapFontFnPtr = pdfium.addFunction(\n (_pThis, weight, bItalic, charset, pitchFamily, facePtr, bExactPtr) => {\n const face = facePtr ? pdfium.UTF8ToString(facePtr) : "";\n const handle = this.mapFont(weight, bItalic, charset, pitchFamily, face);\n if (bExactPtr) {\n pdfium.setValue(bExactPtr, 0, "i32");\n }\n return handle;\n },\n "iiiiiiii"\n );\n this.getFontFnPtr = pdfium.addFunction((_pThis, facePtr) => {\n const face = facePtr ? pdfium.UTF8ToString(facePtr) : "";\n return this.mapFont(400, 0, 0, 0, face);\n }, "iii");\n this.getFontDataFnPtr = pdfium.addFunction(\n (_pThis, hFont, table, buffer, bufSize) => {\n return this.getFontData(hFont, table, buffer, bufSize);\n },\n "iiiiii"\n );\n this.getFaceNameFnPtr = pdfium.addFunction(\n (_pThis, _hFont, _buffer, _bufSize) => {\n return 0;\n },\n "iiiii"\n );\n this.getFontCharsetFnPtr = pdfium.addFunction((_pThis, hFont) => {\n const handle = this.fontHandles.get(hFont);\n return (handle == null ? void 0 : handle.charset) ?? 0;\n }, "iii");\n this.deleteFontFnPtr = pdfium.addFunction((_pThis, hFont) => {\n this.deleteFont(hFont);\n }, "vii");\n pdfium.setValue(this.structPtr + OFFSET_VERSION, 1, "i32");\n pdfium.setValue(this.structPtr + OFFSET_RELEASE, this.releaseFnPtr, "i32");\n pdfium.setValue(this.structPtr + OFFSET_ENUMFONTS, this.enumFontsFnPtr, "i32");\n pdfium.setValue(this.structPtr + OFFSET_MAPFONT, this.mapFontFnPtr, "i32");\n pdfium.setValue(this.structPtr + OFFSET_GETFONT, this.getFontFnPtr, "i32");\n pdfium.setValue(this.structPtr + OFFSET_GETFONTDATA, this.getFontDataFnPtr, "i32");\n pdfium.setValue(this.structPtr + OFFSET_GETFACENAME, this.getFaceNameFnPtr, "i32");\n pdfium.setValue(this.structPtr + OFFSET_GETFONTCHARSET, this.getFontCharsetFnPtr, "i32");\n pdfium.setValue(this.structPtr + OFFSET_DELETEFONT, this.deleteFontFnPtr, "i32");\n module.FPDF_SetSystemFontInfo(this.structPtr);\n this.enabled = true;\n this.logger.info(\n LOG_SOURCE$2,\n LOG_CATEGORY$2,\n "Font fallback system initialized (pure TypeScript)",\n Object.keys(this.fontConfig.fonts)\n );\n } catch (error) {\n this.logger.error(LOG_SOURCE$2, LOG_CATEGORY$2, "Failed to initialize font fallback", error);\n this.cleanup();\n throw error;\n }\n }\n /**\n * Disable the font fallback system and clean up resources\n */\n disable() {\n if (!this.enabled || !this.module) {\n return;\n }\n this.module.FPDF_SetSystemFontInfo(0);\n this.cleanup();\n this.enabled = false;\n this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, "Font fallback system disabled");\n }\n /**\n * Clean up allocated resources\n */\n cleanup() {\n if (!this.module) return;\n const pdfium = this.module.pdfium;\n if (this.structPtr) {\n pdfium.wasmExports.free(this.structPtr);\n this.structPtr = 0;\n }\n const removeIfExists = (ptr) => {\n if (ptr && typeof pdfium.removeFunction === "function") {\n try {\n pdfium.removeFunction(ptr);\n } catch {\n }\n }\n };\n removeIfExists(this.releaseFnPtr);\n removeIfExists(this.enumFontsFnPtr);\n removeIfExists(this.mapFontFnPtr);\n removeIfExists(this.getFontFnPtr);\n removeIfExists(this.getFontDataFnPtr);\n removeIfExists(this.getFaceNameFnPtr);\n removeIfExists(this.getFontCharsetFnPtr);\n removeIfExists(this.deleteFontFnPtr);\n this.releaseFnPtr = 0;\n this.enumFontsFnPtr = 0;\n this.mapFontFnPtr = 0;\n this.getFontFnPtr = 0;\n this.getFontDataFnPtr = 0;\n this.getFaceNameFnPtr = 0;\n this.getFontCharsetFnPtr = 0;\n this.deleteFontFnPtr = 0;\n }\n /**\n * Check if font fallback is enabled\n */\n isEnabled() {\n return this.enabled;\n }\n /**\n * Get statistics about font loading\n */\n getStats() {\n return {\n handleCount: this.fontHandles.size,\n cacheSize: this.fontCache.size,\n cachedUrls: Array.from(this.fontCache.keys())\n };\n }\n /**\n * Pre-load fonts for specific charsets (optional optimization)\n * This can be called to warm the cache before rendering\n */\n async preloadFonts(charsets) {\n const urls = charsets.map((charset) => this.getFontUrlForCharset(charset)).filter((url) => url !== null);\n const uniqueUrls = [...new Set(urls)];\n await Promise.all(\n uniqueUrls.map(async (url) => {\n if (!this.fontCache.has(url)) {\n try {\n const data = await this.fetchFontAsync(url);\n if (data) {\n this.fontCache.set(url, data);\n this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, `Pre-loaded font: ${url}`);\n }\n } catch (error) {\n this.logger.warn(LOG_SOURCE$2, LOG_CATEGORY$2, `Failed to pre-load font: ${url}`, error);\n }\n }\n })\n );\n }\n // ============================================================================\n // PDFium Callback Implementations\n // ============================================================================\n /**\n * MapFont - called by PDFium when it needs a font\n */\n mapFont(weight, bItalic, charset, pitchFamily, face) {\n const italic = bItalic !== 0;\n this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, "MapFont called", {\n weight,\n italic,\n charset,\n pitchFamily,\n face\n });\n const result = this.findBestFontMatch(charset, weight, italic);\n if (!result) {\n this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, `No font configured for charset ${charset}`);\n return 0;\n }\n const handle = {\n id: this.nextHandleId++,\n charset,\n weight,\n italic,\n url: result.url,\n data: null\n };\n this.fontHandles.set(handle.id, handle);\n this.logger.debug(\n LOG_SOURCE$2,\n LOG_CATEGORY$2,\n `Created font handle ${handle.id} for ${result.url} (requested: weight=${weight}, italic=${italic}, matched: weight=${result.matchedWeight}, italic=${result.matchedItalic})`\n );\n return handle.id;\n }\n /**\n * GetFontData - called by PDFium to get font bytes\n */\n getFontData(fontHandle, table, bufferPtr, bufSize) {\n const handle = this.fontHandles.get(fontHandle);\n if (!handle) {\n this.logger.warn(LOG_SOURCE$2, LOG_CATEGORY$2, `Unknown font handle: ${fontHandle}`);\n return 0;\n }\n if (!handle.data) {\n if (this.fontCache.has(handle.url)) {\n handle.data = this.fontCache.get(handle.url);\n } else {\n handle.data = this.fetchFontSync(handle.url);\n if (handle.data) {\n this.fontCache.set(handle.url, handle.data);\n }\n }\n }\n if (!handle.data) {\n this.logger.warn(LOG_SOURCE$2, LOG_CATEGORY$2, `Failed to load font: ${handle.url}`);\n return 0;\n }\n const fontData = handle.data;\n if (table !== 0) {\n this.logger.debug(\n LOG_SOURCE$2,\n LOG_CATEGORY$2,\n `Table ${table} requested - returning 0 to request whole file`\n );\n return 0;\n }\n if (bufferPtr === 0 || bufSize < fontData.length) {\n return fontData.length;\n }\n if (this.module) {\n const heap = this.module.pdfium.HEAPU8;\n heap.set(fontData, bufferPtr);\n this.logger.debug(\n LOG_SOURCE$2,\n LOG_CATEGORY$2,\n `Copied ${fontData.length} bytes to buffer for handle ${fontHandle}`\n );\n }\n return fontData.length;\n }\n /**\n * DeleteFont - called by PDFium when done with a font\n */\n deleteFont(fontHandle) {\n const handle = this.fontHandles.get(fontHandle);\n if (handle) {\n this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, `Deleting font handle ${fontHandle}`);\n this.fontHandles.delete(fontHandle);\n }\n }\n // ============================================================================\n // Helper Methods\n // ============================================================================\n /**\n * Find the best matching font variant for the given parameters\n */\n findBestFontMatch(charset, requestedWeight, requestedItalic) {\n const { fonts: fonts2, defaultFont, baseUrl } = this.fontConfig;\n const entry = fonts2[charset] ?? defaultFont;\n if (!entry) {\n return null;\n }\n const variants = this.normalizeToVariants(entry);\n if (variants.length === 0) {\n return null;\n }\n const best = this.selectBestVariant(variants, requestedWeight, requestedItalic);\n let url = best.url;\n if (baseUrl && !url.startsWith("http://") && !url.startsWith("https://") && !url.startsWith("/")) {\n url = `${baseUrl}/${url}`;\n }\n return {\n url,\n matchedWeight: best.weight ?? 400,\n matchedItalic: best.italic ?? false\n };\n }\n /**\n * Normalize a FontEntry to an array of FontVariants\n */\n normalizeToVariants(entry) {\n if (typeof entry === "string") {\n return [{ url: entry, weight: 400, italic: false }];\n }\n if (Array.isArray(entry)) {\n return entry.map((v) => ({\n url: v.url,\n weight: v.weight ?? 400,\n italic: v.italic ?? false\n }));\n }\n return [{ url: entry.url, weight: entry.weight ?? 400, italic: entry.italic ?? false }];\n }\n /**\n * Select the best matching variant based on weight and italic\n * Uses CSS font matching algorithm principles:\n * 1. Exact italic match preferred\n * 2. Closest weight (with bias toward bolder for weights >= 400)\n */\n selectBestVariant(variants, requestedWeight, requestedItalic) {\n if (variants.length === 1) {\n return variants[0];\n }\n const italicMatches = variants.filter((v) => (v.italic ?? false) === requestedItalic);\n const candidates = italicMatches.length > 0 ? italicMatches : variants;\n let bestMatch = candidates[0];\n let bestDistance = Math.abs((bestMatch.weight ?? 400) - requestedWeight);\n for (const variant of candidates) {\n const variantWeight = variant.weight ?? 400;\n const distance = Math.abs(variantWeight - requestedWeight);\n if (distance < bestDistance) {\n bestMatch = variant;\n bestDistance = distance;\n } else if (distance === bestDistance) {\n const currentWeight = bestMatch.weight ?? 400;\n if (requestedWeight >= 500) {\n if (variantWeight > currentWeight) {\n bestMatch = variant;\n }\n } else {\n if (variantWeight < currentWeight) {\n bestMatch = variant;\n }\n }\n }\n }\n return bestMatch;\n }\n /**\n * Get font URL for a charset (backward compatible helper)\n */\n getFontUrlForCharset(charset) {\n const result = this.findBestFontMatch(charset, 400, false);\n return (result == null ? void 0 : result.url) ?? null;\n }\n /**\n * Fetch font data synchronously\n * Uses custom fontLoader if provided, otherwise falls back to XMLHttpRequest (browser)\n */\n fetchFontSync(pathOrUrl) {\n this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, `Fetching font synchronously: ${pathOrUrl}`);\n if (this.fontConfig.fontLoader) {\n try {\n const data = this.fontConfig.fontLoader(pathOrUrl);\n if (data) {\n this.logger.info(\n LOG_SOURCE$2,\n LOG_CATEGORY$2,\n `Loaded font via custom loader: ${pathOrUrl} (${data.length} bytes)`\n );\n } else {\n this.logger.warn(\n LOG_SOURCE$2,\n LOG_CATEGORY$2,\n `Custom font loader returned null for: ${pathOrUrl}`\n );\n }\n return data;\n } catch (error) {\n this.logger.error(\n LOG_SOURCE$2,\n LOG_CATEGORY$2,\n `Error in custom font loader: ${pathOrUrl}`,\n error\n );\n return null;\n }\n }\n try {\n const xhr = new XMLHttpRequest();\n xhr.open("GET", pathOrUrl, false);\n xhr.responseType = "arraybuffer";\n xhr.send();\n if (xhr.status === 200) {\n const data = new Uint8Array(xhr.response);\n this.logger.info(\n LOG_SOURCE$2,\n LOG_CATEGORY$2,\n `Loaded font: ${pathOrUrl} (${data.length} bytes)`\n );\n return data;\n } else {\n this.logger.error(\n LOG_SOURCE$2,\n LOG_CATEGORY$2,\n `Failed to load font: ${pathOrUrl} (HTTP ${xhr.status})`\n );\n return null;\n }\n } catch (error) {\n this.logger.error(LOG_SOURCE$2, LOG_CATEGORY$2, `Error fetching font: ${pathOrUrl}`, error);\n return null;\n }\n }\n /**\n * Fetch font data asynchronously (for preloading)\n * Uses custom fontLoader if provided, otherwise falls back to fetch API\n */\n async fetchFontAsync(pathOrUrl) {\n if (this.fontConfig.fontLoader) {\n try {\n return this.fontConfig.fontLoader(pathOrUrl);\n } catch {\n return null;\n }\n }\n try {\n const response = await fetch(pathOrUrl);\n if (response.ok) {\n const buffer = await response.arrayBuffer();\n return new Uint8Array(buffer);\n }\n return null;\n } catch {\n return null;\n }\n }\n}\nconst LOG_SOURCE$1 = "PDFiumEngine";\nconst LOG_CATEGORY$1 = "Engine";\nclass PdfiumNative {\n /**\n * Create an instance of PdfiumNative and initialize PDFium\n * @param wasmModule - pdfium wasm module\n * @param options - configuration options\n */\n constructor(pdfiumModule, options = {}) {\n this.pdfiumModule = pdfiumModule;\n this.memoryLeakCheckInterval = null;\n this.fontFallbackManager = null;\n const { logger = new NoopLogger(), fontFallback } = options;\n this.logger = logger;\n this.memoryManager = new MemoryManager(this.pdfiumModule, this.logger);\n this.cache = new PdfCache(this.pdfiumModule, this.memoryManager);\n if (this.logger.isEnabled("debug")) {\n this.memoryLeakCheckInterval = setInterval(() => {\n this.memoryManager.checkLeaks();\n }, 1e4);\n }\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "initialize");\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `Initialize`, "Begin", "General");\n this.pdfiumModule.PDFiumExt_Init();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `Initialize`, "End", "General");\n if (fontFallback) {\n this.fontFallbackManager = new FontFallbackManager(fontFallback, this.logger);\n this.fontFallbackManager.initialize(this.pdfiumModule);\n this.logger.info(LOG_SOURCE$1, LOG_CATEGORY$1, "Font fallback system enabled");\n }\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.destroy}\n *\n * @public\n */\n destroy() {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "destroy");\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `Destroy`, "Begin", "General");\n if (this.fontFallbackManager) {\n this.fontFallbackManager.disable();\n this.fontFallbackManager = null;\n }\n this.pdfiumModule.FPDF_DestroyLibrary();\n if (this.memoryLeakCheckInterval) {\n clearInterval(this.memoryLeakCheckInterval);\n this.memoryLeakCheckInterval = null;\n }\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `Destroy`, "End", "General");\n return PdfTaskHelper.resolve(true);\n }\n /**\n * Get the font fallback manager instance\n * Useful for pre-loading fonts or checking stats\n */\n getFontFallbackManager() {\n return this.fontFallbackManager;\n }\n /** Write a UTF-16LE (WIDESTRING) to wasm, call `fn(ptr)`, then free. */\n withWString(value, fn) {\n const length = (value.length + 1) * 2;\n const ptr = this.memoryManager.malloc(length);\n try {\n this.pdfiumModule.pdfium.stringToUTF16(value, ptr, length);\n return fn(ptr);\n } finally {\n this.memoryManager.free(ptr);\n }\n }\n /** Write a float[] to wasm, call `fn(ptr, count)`, then free. */\n withFloatArray(values, fn) {\n const arr = values ?? [];\n const bytes = arr.length * 4;\n const ptr = bytes ? this.memoryManager.malloc(bytes) : WasmPointer(0);\n try {\n if (bytes) {\n for (let i = 0; i < arr.length; i++) {\n this.pdfiumModule.pdfium.setValue(ptr + i * 4, arr[i], "float");\n }\n }\n return fn(ptr, arr.length);\n } finally {\n if (bytes) this.memoryManager.free(ptr);\n }\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.openDocument}\n *\n * @public\n */\n openDocumentBuffer(file, options) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "openDocumentBuffer", file, options);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `OpenDocumentBuffer`, "Begin", file.id);\n const normalizeRotation = (options == null ? void 0 : options.normalizeRotation) ?? false;\n const array = new Uint8Array(file.content);\n const length = array.length;\n const filePtr = this.memoryManager.malloc(length);\n this.pdfiumModule.pdfium.HEAPU8.set(array, filePtr);\n const docPtr = this.pdfiumModule.FPDF_LoadMemDocument(filePtr, length, (options == null ? void 0 : options.password) ?? "");\n if (!docPtr) {\n const lastError = this.pdfiumModule.FPDF_GetLastError();\n this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, `FPDF_LoadMemDocument failed with ${lastError}`);\n this.memoryManager.free(filePtr);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `OpenDocumentBuffer`, "End", file.id);\n return PdfTaskHelper.reject({\n code: lastError,\n message: `FPDF_LoadMemDocument failed`\n });\n }\n const pageCount = this.pdfiumModule.FPDF_GetPageCount(docPtr);\n const pages = [];\n const sizePtr = this.memoryManager.malloc(8);\n for (let index = 0; index < pageCount; index++) {\n const result = normalizeRotation ? this.pdfiumModule.EPDF_GetPageSizeByIndexNormalized(docPtr, index, sizePtr) : this.pdfiumModule.FPDF_GetPageSizeByIndexF(docPtr, index, sizePtr);\n if (!result) {\n const lastError = this.pdfiumModule.FPDF_GetLastError();\n this.logger.error(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `${normalizeRotation ? "EPDF_GetPageSizeByIndexNormalized" : "FPDF_GetPageSizeByIndexF"} failed with ${lastError}`\n );\n this.memoryManager.free(sizePtr);\n this.pdfiumModule.FPDF_CloseDocument(docPtr);\n this.memoryManager.free(filePtr);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `OpenDocumentBuffer`, "End", file.id);\n return PdfTaskHelper.reject({\n code: lastError,\n message: `${normalizeRotation ? "EPDF_GetPageSizeByIndexNormalized" : "FPDF_GetPageSizeByIndexF"} failed`\n });\n }\n const rotation = this.pdfiumModule.EPDF_GetPageRotationByIndex(docPtr, index);\n const page = {\n index,\n size: {\n width: this.pdfiumModule.pdfium.getValue(sizePtr, "float"),\n height: this.pdfiumModule.pdfium.getValue(sizePtr + 4, "float")\n },\n rotation\n };\n pages.push(page);\n }\n this.memoryManager.free(sizePtr);\n const isEncrypted = this.pdfiumModule.EPDF_IsEncrypted(docPtr);\n const isOwnerUnlocked = this.pdfiumModule.EPDF_IsOwnerUnlocked(docPtr);\n const permissions = this.pdfiumModule.FPDF_GetDocPermissions(docPtr);\n const pdfDoc = {\n id: file.id,\n pageCount,\n pages,\n isEncrypted,\n isOwnerUnlocked,\n permissions,\n normalizedRotation: normalizeRotation\n };\n this.cache.setDocument(file.id, filePtr, docPtr, normalizeRotation);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `OpenDocumentBuffer`, "End", file.id);\n return PdfTaskHelper.resolve(pdfDoc);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.getMetadata}\n *\n * @public\n */\n getMetadata(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getMetadata", doc);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `GetMetadata`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `GetMetadata`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const creationRaw = this.readMetaText(ctx.docPtr, "CreationDate");\n const modRaw = this.readMetaText(ctx.docPtr, "ModDate");\n const metadata = {\n title: this.readMetaText(ctx.docPtr, "Title"),\n author: this.readMetaText(ctx.docPtr, "Author"),\n subject: this.readMetaText(ctx.docPtr, "Subject"),\n keywords: this.readMetaText(ctx.docPtr, "Keywords"),\n producer: this.readMetaText(ctx.docPtr, "Producer"),\n creator: this.readMetaText(ctx.docPtr, "Creator"),\n creationDate: creationRaw ? pdfDateToDate(creationRaw) ?? null : null,\n modificationDate: modRaw ? pdfDateToDate(modRaw) ?? null : null,\n trapped: this.getMetaTrapped(ctx.docPtr),\n custom: this.readAllMeta(ctx.docPtr, true)\n };\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `GetMetadata`, "End", doc.id);\n return PdfTaskHelper.resolve(metadata);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.setMetadata}\n *\n * @public\n */\n setMetadata(doc, meta) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "setMetadata", doc, meta);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "SetMetadata", "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "SetMetadata", "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const strMap = [\n ["title", "Title"],\n ["author", "Author"],\n ["subject", "Subject"],\n ["keywords", "Keywords"],\n ["producer", "Producer"],\n ["creator", "Creator"]\n ];\n let ok = true;\n for (const [field, key] of strMap) {\n const v = meta[field];\n if (v === void 0) continue;\n const s = v === null ? null : v;\n if (!this.setMetaText(ctx.docPtr, key, s)) ok = false;\n }\n const writeDate = (field, key) => {\n const v = meta[field];\n if (v === void 0) return;\n if (v === null) {\n if (!this.setMetaText(ctx.docPtr, key, null)) ok = false;\n return;\n }\n const d = v;\n const raw = dateToPdfDate(d);\n if (!this.setMetaText(ctx.docPtr, key, raw)) ok = false;\n };\n writeDate("creationDate", "CreationDate");\n writeDate("modificationDate", "ModDate");\n if (meta.trapped !== void 0) {\n if (!this.setMetaTrapped(ctx.docPtr, meta.trapped ?? null)) ok = false;\n }\n if (meta.custom !== void 0) {\n for (const [key, value] of Object.entries(meta.custom)) {\n if (!isValidCustomKey(key)) {\n this.logger.warn(LOG_SOURCE$1, LOG_CATEGORY$1, "Invalid custom metadata key skipped", key);\n continue;\n }\n if (!this.setMetaText(ctx.docPtr, key, value ?? null)) ok = false;\n }\n }\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "SetMetadata", "End", doc.id);\n return ok ? PdfTaskHelper.resolve(true) : PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: "one or more metadata fields could not be written"\n });\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.getDocPermissions}\n *\n * @public\n */\n getDocPermissions(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getDocPermissions", doc);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `getDocPermissions`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `getDocPermissions`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const permissions = this.pdfiumModule.FPDF_GetDocPermissions(ctx.docPtr);\n return PdfTaskHelper.resolve(permissions);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.getDocUserPermissions}\n *\n * @public\n */\n getDocUserPermissions(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getDocUserPermissions", doc);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `getDocUserPermissions`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `getDocUserPermissions`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const permissions = this.pdfiumModule.FPDF_GetDocUserPermissions(ctx.docPtr);\n return PdfTaskHelper.resolve(permissions);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.getSignatures}\n *\n * @public\n */\n getSignatures(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getSignatures", doc);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `GetSignatures`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `GetSignatures`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const signatures = [];\n const count = this.pdfiumModule.FPDF_GetSignatureCount(ctx.docPtr);\n for (let i = 0; i < count; i++) {\n const signatureObjPtr = this.pdfiumModule.FPDF_GetSignatureObject(ctx.docPtr, i);\n const contents = readArrayBuffer(this.pdfiumModule.pdfium, (buffer, bufferSize) => {\n return this.pdfiumModule.FPDFSignatureObj_GetContents(signatureObjPtr, buffer, bufferSize);\n });\n const byteRange = readArrayBuffer(this.pdfiumModule.pdfium, (buffer, bufferSize) => {\n return this.pdfiumModule.FPDFSignatureObj_GetByteRange(signatureObjPtr, buffer, bufferSize) * 4;\n });\n const subFilter = readArrayBuffer(this.pdfiumModule.pdfium, (buffer, bufferSize) => {\n return this.pdfiumModule.FPDFSignatureObj_GetSubFilter(signatureObjPtr, buffer, bufferSize);\n });\n const reason = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFSignatureObj_GetReason(\n signatureObjPtr,\n buffer,\n bufferLength\n );\n },\n this.pdfiumModule.pdfium.UTF16ToString\n );\n const time = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFSignatureObj_GetTime(signatureObjPtr, buffer, bufferLength);\n },\n this.pdfiumModule.pdfium.UTF8ToString\n );\n const docMDP = this.pdfiumModule.FPDFSignatureObj_GetDocMDPPermission(signatureObjPtr);\n signatures.push({\n contents,\n byteRange,\n subFilter,\n reason,\n time,\n docMDP\n });\n }\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `GetSignatures`, "End", doc.id);\n return PdfTaskHelper.resolve(signatures);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.getBookmarks}\n *\n * @public\n */\n getBookmarks(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getBookmarks", doc);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `GetBookmarks`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `getBookmarks`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const bookmarks = this.readPdfBookmarks(ctx.docPtr, 0);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `GetBookmarks`, "End", doc.id);\n return PdfTaskHelper.resolve({\n bookmarks\n });\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.setBookmarks}\n *\n * @public\n */\n setBookmarks(doc, list) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "setBookmarks", doc, list);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `SetBookmarks`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `SetBookmarks`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n if (!this.pdfiumModule.EPDFBookmark_Clear(ctx.docPtr)) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `SetBookmarks`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: "failed to clear existing bookmarks"\n });\n }\n const build = (parentPtr, items) => {\n var _a;\n for (const item of items) {\n const bmPtr = this.withWString(\n item.title ?? "",\n (wptr) => this.pdfiumModule.EPDFBookmark_AppendChild(ctx.docPtr, parentPtr, wptr)\n );\n if (!bmPtr) return false;\n if (item.target) {\n const ok2 = this.applyBookmarkTarget(ctx.docPtr, bmPtr, item.target);\n if (!ok2) return false;\n }\n if ((_a = item.children) == null ? void 0 : _a.length) {\n const ok2 = build(bmPtr, item.children);\n if (!ok2) return false;\n }\n }\n return true;\n };\n const ok = build(\n /*top-level*/\n 0,\n list\n );\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `SetBookmarks`, "End", doc.id);\n if (!ok) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: "failed to build bookmark tree"\n });\n }\n return PdfTaskHelper.resolve(true);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.deleteBookmarks}\n *\n * @public\n */\n deleteBookmarks(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "deleteBookmarks", doc);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `DeleteBookmarks`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `DeleteBookmarks`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const ok = this.pdfiumModule.EPDFBookmark_Clear(ctx.docPtr);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `DeleteBookmarks`, "End", doc.id);\n return ok ? PdfTaskHelper.resolve(true) : PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: "failed to clear bookmarks"\n });\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.renderPage}\n *\n * @public\n */\n renderPageRaw(doc, page, options) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "renderPage", doc, page, options);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `RenderPage`, "Begin", `${doc.id}-${page.index}`);\n const rect = { origin: { x: 0, y: 0 }, size: page.size };\n const task = this.renderRectEncoded(doc, page, rect, options);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `RenderPage`, "End", `${doc.id}-${page.index}`);\n return task;\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.renderPageRect}\n *\n * @public\n */\n renderPageRect(doc, page, rect, options) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "renderPageRect", doc, page, rect, options);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RenderPageRect`,\n "Begin",\n `${doc.id}-${page.index}`\n );\n const task = this.renderRectEncoded(doc, page, rect, options);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `RenderPageRect`, "End", `${doc.id}-${page.index}`);\n return task;\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.getPageAnnotations}\n *\n * @public\n */\n getPageAnnotations(doc, page) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageAnnotations", doc, page);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `GetPageAnnotations`,\n "Begin",\n `${doc.id}-${page.index}`\n );\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `GetPageAnnotations`,\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const annotations = this.readPageAnnotations(doc, ctx, page);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `GetPageAnnotations`,\n "End",\n `${doc.id}-${page.index}`\n );\n this.logger.debug(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `GetPageAnnotations`,\n `${doc.id}-${page.index}`,\n annotations\n );\n return PdfTaskHelper.resolve(annotations);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.createPageAnnotation}\n *\n * @public\n */\n createPageAnnotation(doc, page, annotation, context) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "createPageAnnotation", doc, page, annotation);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `CreatePageAnnotation`,\n "Begin",\n `${doc.id}-${page.index}`\n );\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `CreatePageAnnotation`,\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const annotationPtr = this.pdfiumModule.EPDFPage_CreateAnnot(pageCtx.pagePtr, annotation.type);\n if (!annotationPtr) {\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `CreatePageAnnotation`,\n "End",\n `${doc.id}-${page.index}`\n );\n pageCtx.release();\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantCreateAnnot,\n message: "can not create annotation with specified type"\n });\n }\n if (!isUuidV4(annotation.id)) {\n annotation.id = uuidV4();\n }\n if (!this.setAnnotString(annotationPtr, "NM", annotation.id)) {\n this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);\n pageCtx.release();\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantSetAnnotString,\n message: "can not set the name of the annotation"\n });\n }\n if (!this.setPageAnnoRect(doc, page, annotationPtr, annotation.rect)) {\n this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);\n pageCtx.release();\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `CreatePageAnnotation`,\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantSetAnnotRect,\n message: "can not set the rect of the annotation"\n });\n }\n const saveAnnotation = this.prepareAnnotationForSave(annotation);\n let isSucceed = false;\n switch (saveAnnotation.type) {\n case PdfAnnotationSubtype.INK:\n isSucceed = this.addInkStroke(\n doc,\n page,\n pageCtx.pagePtr,\n annotationPtr,\n saveAnnotation\n );\n break;\n case PdfAnnotationSubtype.STAMP:\n isSucceed = this.addStampContent(\n doc,\n ctx.docPtr,\n page,\n pageCtx.pagePtr,\n annotationPtr,\n saveAnnotation,\n context == null ? void 0 : context.imageData\n );\n break;\n case PdfAnnotationSubtype.TEXT:\n isSucceed = this.addTextContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotationPtr,\n saveAnnotation\n );\n break;\n case PdfAnnotationSubtype.FREETEXT:\n isSucceed = this.addFreeTextContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotationPtr,\n saveAnnotation\n );\n break;\n case PdfAnnotationSubtype.LINE:\n isSucceed = this.addLineContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotationPtr,\n saveAnnotation\n );\n break;\n case PdfAnnotationSubtype.POLYLINE:\n case PdfAnnotationSubtype.POLYGON:\n isSucceed = this.addPolyContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotationPtr,\n saveAnnotation\n );\n break;\n case PdfAnnotationSubtype.CIRCLE:\n case PdfAnnotationSubtype.SQUARE:\n isSucceed = this.addShapeContent(doc, page, pageCtx.pagePtr, annotationPtr, saveAnnotation);\n break;\n case PdfAnnotationSubtype.UNDERLINE:\n case PdfAnnotationSubtype.STRIKEOUT:\n case PdfAnnotationSubtype.SQUIGGLY:\n case PdfAnnotationSubtype.HIGHLIGHT:\n isSucceed = this.addTextMarkupContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotationPtr,\n saveAnnotation\n );\n break;\n case PdfAnnotationSubtype.LINK:\n isSucceed = this.addLinkContent(\n doc,\n page,\n ctx.docPtr,\n pageCtx.pagePtr,\n annotationPtr,\n saveAnnotation\n );\n break;\n case PdfAnnotationSubtype.CARET:\n isSucceed = this.addCaretContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotationPtr,\n saveAnnotation\n );\n break;\n case PdfAnnotationSubtype.REDACT:\n isSucceed = this.addRedactContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotationPtr,\n saveAnnotation\n );\n break;\n }\n if (!isSucceed) {\n this.pdfiumModule.FPDFPage_RemoveAnnot(pageCtx.pagePtr, annotationPtr);\n pageCtx.release();\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `CreatePageAnnotation`,\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantSetAnnotContent,\n message: "can not add content of the annotation"\n });\n }\n if (annotation.blendMode !== void 0) {\n this.pdfiumModule.EPDFAnnot_GenerateAppearanceWithBlend(annotationPtr, annotation.blendMode);\n } else {\n this.pdfiumModule.EPDFAnnot_GenerateAppearance(annotationPtr);\n }\n this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);\n this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);\n pageCtx.release();\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `CreatePageAnnotation`,\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.resolve(annotation.id);\n }\n /**\n * Update an existing page annotation in-place\n *\n * • Locates the annot by page-local index (`annotation.id`)\n * • Re-writes its /Rect and type-specific payload\n * • Calls FPDFPage_GenerateContent so the new appearance is rendered\n *\n * @returns PdfTask – true on success\n */\n updatePageAnnotation(doc, page, annotation, options) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "updatePageAnnotation", doc, page, annotation);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "UpdatePageAnnotation",\n "Begin",\n `${doc.id}-${page.index}`\n );\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "UpdatePageAnnotation",\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const annotPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);\n if (!annotPtr) {\n pageCtx.release();\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "UpdatePageAnnotation",\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({ code: PdfErrorCode.NotFound, message: "annotation not found" });\n }\n if (!this.setPageAnnoRect(doc, page, annotPtr, annotation.rect)) {\n this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);\n pageCtx.release();\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "UpdatePageAnnotation",\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantSetAnnotRect,\n message: "failed to move annotation"\n });\n }\n const saveAnnotation = this.prepareAnnotationForSave(annotation);\n let ok = false;\n switch (saveAnnotation.type) {\n /* ── Ink ─────────────────────────────────────────────────────────────── */\n case PdfAnnotationSubtype.INK: {\n if (!this.pdfiumModule.FPDFAnnot_RemoveInkList(annotPtr)) break;\n ok = this.addInkStroke(\n doc,\n page,\n pageCtx.pagePtr,\n annotPtr,\n saveAnnotation\n );\n break;\n }\n /* ── Stamp ───────────────────────────────────────────────────────────── */\n case PdfAnnotationSubtype.STAMP: {\n ok = this.addStampContent(\n doc,\n ctx.docPtr,\n page,\n pageCtx.pagePtr,\n annotPtr,\n saveAnnotation\n );\n break;\n }\n case PdfAnnotationSubtype.TEXT: {\n ok = this.addTextContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotPtr,\n saveAnnotation\n );\n break;\n }\n /* ── Free text ────────────────────────────────────────────────────────── */\n case PdfAnnotationSubtype.FREETEXT: {\n ok = this.addFreeTextContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotPtr,\n saveAnnotation\n );\n break;\n }\n /* ── Shape ───────────────────────────────────────────────────────────── */\n case PdfAnnotationSubtype.CIRCLE:\n case PdfAnnotationSubtype.SQUARE: {\n ok = this.addShapeContent(doc, page, pageCtx.pagePtr, annotPtr, saveAnnotation);\n break;\n }\n /* ── Line ─────────────────────────────────────────────────────────────── */\n case PdfAnnotationSubtype.LINE: {\n ok = this.addLineContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotPtr,\n saveAnnotation\n );\n break;\n }\n /* ── Polygon / Polyline ───────────────────────────────────────────────── */\n case PdfAnnotationSubtype.POLYGON:\n case PdfAnnotationSubtype.POLYLINE: {\n ok = this.addPolyContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotPtr,\n saveAnnotation\n );\n break;\n }\n /* ── Text-markup family ──────────────────────────────────────────────── */\n case PdfAnnotationSubtype.HIGHLIGHT:\n case PdfAnnotationSubtype.UNDERLINE:\n case PdfAnnotationSubtype.STRIKEOUT:\n case PdfAnnotationSubtype.SQUIGGLY: {\n ok = this.addTextMarkupContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotPtr,\n saveAnnotation\n );\n break;\n }\n /* ── Link ─────────────────────────────────────────────────────────────── */\n case PdfAnnotationSubtype.LINK: {\n ok = this.addLinkContent(\n doc,\n page,\n ctx.docPtr,\n pageCtx.pagePtr,\n annotPtr,\n saveAnnotation\n );\n break;\n }\n /* ── Caret ────────────────────────────────────────────────────────────── */\n case PdfAnnotationSubtype.CARET: {\n ok = this.addCaretContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotPtr,\n saveAnnotation\n );\n break;\n }\n /* ── Redact ───────────────────────────────────────────────────────────── */\n case PdfAnnotationSubtype.REDACT: {\n ok = this.addRedactContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotPtr,\n saveAnnotation\n );\n break;\n }\n /* ── Unsupported edits – fall through to error ───────────────────────── */\n default:\n ok = false;\n }\n if (ok && (options == null ? void 0 : options.regenerateAppearance) !== false) {\n if (annotation.blendMode !== void 0) {\n this.pdfiumModule.EPDFAnnot_GenerateAppearanceWithBlend(annotPtr, annotation.blendMode);\n } else {\n this.pdfiumModule.EPDFAnnot_GenerateAppearance(annotPtr);\n }\n this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);\n }\n this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);\n pageCtx.release();\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "UpdatePageAnnotation",\n "End",\n `${doc.id}-${page.index}`\n );\n return ok ? PdfTaskHelper.resolve(true) : PdfTaskHelper.reject({\n code: PdfErrorCode.CantSetAnnotContent,\n message: "failed to update annotation"\n });\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.removePageAnnotation}\n *\n * @public\n */\n removePageAnnotation(doc, page, annotation) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "removePageAnnotation", doc, page, annotation);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RemovePageAnnotation`,\n "Begin",\n `${doc.id}-${page.index}`\n );\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RemovePageAnnotation`,\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n let result = false;\n result = this.removeAnnotationByName(pageCtx.pagePtr, annotation.id);\n if (!result) {\n this.logger.error(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `FPDFPage_RemoveAnnot Failed`,\n `${doc.id}-${page.index}`\n );\n } else {\n result = this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);\n if (!result) {\n this.logger.error(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `FPDFPage_GenerateContent Failed`,\n `${doc.id}-${page.index}`\n );\n }\n }\n pageCtx.release();\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RemovePageAnnotation`,\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.resolve(result);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.getPageTextRects}\n *\n * @public\n */\n getPageTextRects(doc, page) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageTextRects", doc, page);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `GetPageTextRects`,\n "Begin",\n `${doc.id}-${page.index}`\n );\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `GetPageTextRects`,\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const textPagePtr = this.pdfiumModule.FPDFText_LoadPage(pageCtx.pagePtr);\n const textRects = this.readPageTextRects(page, pageCtx.docPtr, pageCtx.pagePtr, textPagePtr);\n this.pdfiumModule.FPDFText_ClosePage(textPagePtr);\n pageCtx.release();\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `GetPageTextRects`,\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.resolve(textRects);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.renderThumbnail}\n *\n * @public\n */\n renderThumbnailRaw(doc, page, options) {\n const { scaleFactor = 1, ...rest } = options ?? {};\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "renderThumbnail", doc, page, options);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RenderThumbnail`,\n "Begin",\n `${doc.id}-${page.index}`\n );\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RenderThumbnail`,\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const result = this.renderPageRaw(doc, page, {\n scaleFactor: Math.max(scaleFactor, 0.5),\n ...rest\n });\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `RenderThumbnail`, "End", `${doc.id}-${page.index}`);\n return result;\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.getAttachments}\n *\n * @public\n */\n getAttachments(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getAttachments", doc);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `GetAttachments`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `GetAttachments`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const attachments = [];\n const count = this.pdfiumModule.FPDFDoc_GetAttachmentCount(ctx.docPtr);\n for (let i = 0; i < count; i++) {\n const attachment = this.readPdfAttachment(ctx.docPtr, i);\n attachments.push(attachment);\n }\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `GetAttachments`, "End", doc.id);\n return PdfTaskHelper.resolve(attachments);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.addAttachment}\n *\n * @public\n */\n addAttachment(doc, params) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "addAttachment", doc, params == null ? void 0 : params.name);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `AddAttachment`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `AddAttachment`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const { name, description, mimeType, data } = params ?? {};\n if (!name) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `AddAttachment`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.NotFound,\n message: "attachment name is required"\n });\n }\n if (!data || (data instanceof Uint8Array ? data.byteLength === 0 : data.byteLength === 0)) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `AddAttachment`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.NotFound,\n message: "attachment data is empty"\n });\n }\n const attachmentPtr = this.withWString(\n name,\n (wNamePtr) => this.pdfiumModule.FPDFDoc_AddAttachment(ctx.docPtr, wNamePtr)\n );\n if (!attachmentPtr) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `AddAttachment`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: `An attachment named "${name}" already exists`\n });\n }\n this.withWString(\n description,\n (wDescriptionPtr) => this.pdfiumModule.EPDFAttachment_SetDescription(attachmentPtr, wDescriptionPtr)\n );\n this.pdfiumModule.EPDFAttachment_SetSubtype(attachmentPtr, mimeType);\n const u8 = data instanceof Uint8Array ? data : new Uint8Array(data);\n const len = u8.byteLength;\n const contentPtr = this.memoryManager.malloc(len);\n try {\n this.pdfiumModule.pdfium.HEAPU8.set(u8, contentPtr);\n const ok = this.pdfiumModule.FPDFAttachment_SetFile(\n attachmentPtr,\n ctx.docPtr,\n contentPtr,\n len\n );\n if (!ok) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `AddAttachment`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: "failed to write attachment bytes"\n });\n }\n } finally {\n this.memoryManager.free(contentPtr);\n }\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `AddAttachment`, "End", doc.id);\n return PdfTaskHelper.resolve(true);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.removeAttachment}\n *\n * @public\n */\n removeAttachment(doc, attachment) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "deleteAttachment", doc, attachment);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `DeleteAttachment`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `DeleteAttachment`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const count = this.pdfiumModule.FPDFDoc_GetAttachmentCount(ctx.docPtr);\n if (attachment.index < 0 || attachment.index >= count) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `DeleteAttachment`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: `attachment index ${attachment.index} out of range`\n });\n }\n const ok = this.pdfiumModule.FPDFDoc_DeleteAttachment(ctx.docPtr, attachment.index);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `DeleteAttachment`, "End", doc.id);\n if (!ok) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: "failed to delete attachment"\n });\n }\n return PdfTaskHelper.resolve(true);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.readAttachmentContent}\n *\n * @public\n */\n readAttachmentContent(doc, attachment) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "readAttachmentContent", doc, attachment);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ReadAttachmentContent`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ReadAttachmentContent`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const attachmentPtr = this.pdfiumModule.FPDFDoc_GetAttachment(ctx.docPtr, attachment.index);\n const sizePtr = this.memoryManager.malloc(4);\n if (!this.pdfiumModule.FPDFAttachment_GetFile(attachmentPtr, 0, 0, sizePtr)) {\n this.memoryManager.free(sizePtr);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ReadAttachmentContent`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantReadAttachmentSize,\n message: "can not read attachment size"\n });\n }\n const size = this.pdfiumModule.pdfium.getValue(sizePtr, "i32") >>> 0;\n const contentPtr = this.memoryManager.malloc(size);\n if (!this.pdfiumModule.FPDFAttachment_GetFile(attachmentPtr, contentPtr, size, sizePtr)) {\n this.memoryManager.free(sizePtr);\n this.memoryManager.free(contentPtr);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ReadAttachmentContent`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantReadAttachmentContent,\n message: "can not read attachment content"\n });\n }\n const buffer = new ArrayBuffer(size);\n const view = new DataView(buffer);\n for (let i = 0; i < size; i++) {\n view.setInt8(i, this.pdfiumModule.pdfium.getValue(contentPtr + i, "i8"));\n }\n this.memoryManager.free(sizePtr);\n this.memoryManager.free(contentPtr);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ReadAttachmentContent`, "End", doc.id);\n return PdfTaskHelper.resolve(buffer);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.setFormFieldValue}\n *\n * @public\n */\n setFormFieldValue(doc, page, annotation, value) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "SetFormFieldValue", doc, annotation, value);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `SetFormFieldValue`,\n "Begin",\n `${doc.id}-${annotation.id}`\n );\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "SetFormFieldValue", "document is not opened");\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `SetFormFieldValue`,\n "End",\n `${doc.id}-${annotation.id}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const formFillInfoPtr = this.pdfiumModule.PDFiumExt_OpenFormFillInfo();\n const formHandle = this.pdfiumModule.PDFiumExt_InitFormFillEnvironment(\n ctx.docPtr,\n formFillInfoPtr\n );\n const pageCtx = ctx.acquirePage(page.index);\n this.pdfiumModule.FORM_OnAfterLoadPage(pageCtx.pagePtr, formHandle);\n const annotationPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);\n if (!annotationPtr) {\n pageCtx.release();\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "SetFormFieldValue",\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({ code: PdfErrorCode.NotFound, message: "annotation not found" });\n }\n if (!this.pdfiumModule.FORM_SetFocusedAnnot(formHandle, annotationPtr)) {\n this.logger.debug(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "SetFormFieldValue",\n "failed to set focused annotation"\n );\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `SetFormFieldValue`,\n "End",\n `${doc.id}-${annotation.id}`\n );\n this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);\n this.pdfiumModule.FORM_OnBeforeClosePage(pageCtx.pagePtr, formHandle);\n pageCtx.release();\n this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(formHandle);\n this.pdfiumModule.PDFiumExt_CloseFormFillInfo(formFillInfoPtr);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantFocusAnnot,\n message: "failed to set focused annotation"\n });\n }\n switch (value.kind) {\n case "text":\n {\n if (!this.pdfiumModule.FORM_SelectAllText(formHandle, pageCtx.pagePtr)) {\n this.logger.debug(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "SetFormFieldValue",\n "failed to select all text"\n );\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `SetFormFieldValue`,\n "End",\n `${doc.id}-${annotation.id}`\n );\n this.pdfiumModule.FORM_ForceToKillFocus(formHandle);\n this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);\n this.pdfiumModule.FORM_OnBeforeClosePage(pageCtx.pagePtr, formHandle);\n pageCtx.release();\n this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(formHandle);\n this.pdfiumModule.PDFiumExt_CloseFormFillInfo(formFillInfoPtr);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantSelectText,\n message: "failed to select all text"\n });\n }\n const length = 2 * (value.text.length + 1);\n const textPtr = this.memoryManager.malloc(length);\n this.pdfiumModule.pdfium.stringToUTF16(value.text, textPtr, length);\n this.pdfiumModule.FORM_ReplaceSelection(formHandle, pageCtx.pagePtr, textPtr);\n this.memoryManager.free(textPtr);\n }\n break;\n case "selection":\n {\n if (!this.pdfiumModule.FORM_SetIndexSelected(\n formHandle,\n pageCtx.pagePtr,\n value.index,\n value.isSelected\n )) {\n this.logger.debug(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "SetFormFieldValue",\n "failed to set index selected"\n );\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `SetFormFieldValue`,\n "End",\n `${doc.id}-${annotation.id}`\n );\n this.pdfiumModule.FORM_ForceToKillFocus(formHandle);\n this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);\n this.pdfiumModule.FORM_OnBeforeClosePage(pageCtx.pagePtr, formHandle);\n pageCtx.release();\n this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(formHandle);\n this.pdfiumModule.PDFiumExt_CloseFormFillInfo(formFillInfoPtr);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantSelectOption,\n message: "failed to set index selected"\n });\n }\n }\n break;\n case "checked":\n {\n const kReturn = 13;\n if (!this.pdfiumModule.FORM_OnChar(formHandle, pageCtx.pagePtr, kReturn, 0)) {\n this.logger.debug(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "SetFormFieldValue",\n "failed to set field checked"\n );\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `SetFormFieldValue`,\n "End",\n `${doc.id}-${annotation.id}`\n );\n this.pdfiumModule.FORM_ForceToKillFocus(formHandle);\n this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);\n this.pdfiumModule.FORM_OnBeforeClosePage(pageCtx.pagePtr, formHandle);\n pageCtx.release();\n this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(formHandle);\n this.pdfiumModule.PDFiumExt_CloseFormFillInfo(formFillInfoPtr);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantCheckField,\n message: "failed to set field checked"\n });\n }\n }\n break;\n }\n this.pdfiumModule.FORM_ForceToKillFocus(formHandle);\n this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);\n this.pdfiumModule.FORM_OnBeforeClosePage(pageCtx.pagePtr, formHandle);\n pageCtx.release();\n this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(formHandle);\n this.pdfiumModule.PDFiumExt_CloseFormFillInfo(formFillInfoPtr);\n return PdfTaskHelper.resolve(true);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.flattenPage}\n *\n * @public\n */\n flattenPage(doc, page, options) {\n const { flag = PdfPageFlattenFlag.Display } = options ?? {};\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "flattenPage", doc, page, flag);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `flattenPage`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `flattenPage`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const result = this.pdfiumModule.FPDFPage_Flatten(pageCtx.pagePtr, flag);\n pageCtx.release();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `flattenPage`, "End", doc.id);\n return PdfTaskHelper.resolve(result);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.extractPages}\n *\n * @public\n */\n extractPages(doc, pageIndexes) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "extractPages", doc, pageIndexes);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ExtractPages`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ExtractPages`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const newDocPtr = this.pdfiumModule.FPDF_CreateNewDocument();\n if (!newDocPtr) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ExtractPages`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantCreateNewDoc,\n message: "can not create new document"\n });\n }\n const pageIndexesPtr = this.memoryManager.malloc(pageIndexes.length * 4);\n for (let i = 0; i < pageIndexes.length; i++) {\n this.pdfiumModule.pdfium.setValue(pageIndexesPtr + i * 4, pageIndexes[i], "i32");\n }\n if (!this.pdfiumModule.FPDF_ImportPagesByIndex(\n newDocPtr,\n ctx.docPtr,\n pageIndexesPtr,\n pageIndexes.length,\n 0\n )) {\n this.pdfiumModule.FPDF_CloseDocument(newDocPtr);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ExtractPages`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantImportPages,\n message: "can not import pages to new document"\n });\n }\n const buffer = this.saveDocument(newDocPtr);\n this.pdfiumModule.FPDF_CloseDocument(newDocPtr);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ExtractPages`, "End", doc.id);\n return PdfTaskHelper.resolve(buffer);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.extractText}\n *\n * @public\n */\n extractText(doc, pageIndexes) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "extractText", doc, pageIndexes);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ExtractText`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ExtractText`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const strings = [];\n for (let i = 0; i < pageIndexes.length; i++) {\n const pageCtx = ctx.acquirePage(pageIndexes[i]);\n const textPagePtr = this.pdfiumModule.FPDFText_LoadPage(pageCtx.pagePtr);\n const charCount = this.pdfiumModule.FPDFText_CountChars(textPagePtr);\n const bufferPtr = this.memoryManager.malloc((charCount + 1) * 2);\n this.pdfiumModule.FPDFText_GetText(textPagePtr, 0, charCount, bufferPtr);\n const text2 = this.pdfiumModule.pdfium.UTF16ToString(bufferPtr);\n this.memoryManager.free(bufferPtr);\n strings.push(text2);\n this.pdfiumModule.FPDFText_ClosePage(textPagePtr);\n pageCtx.release();\n }\n const text = strings.join("\\n\\n");\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ExtractText`, "End", doc.id);\n return PdfTaskHelper.resolve(text);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.getTextSlices}\n *\n * @public\n */\n getTextSlices(doc, slices) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getTextSlices", doc, slices);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetTextSlices", "Begin", doc.id);\n if (slices.length === 0) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetTextSlices", "End", doc.id);\n return PdfTaskHelper.resolve([]);\n }\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetTextSlices", "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n try {\n const out = new Array(slices.length);\n const byPage = /* @__PURE__ */ new Map();\n slices.forEach((s, i) => {\n (byPage.get(s.pageIndex) ?? byPage.set(s.pageIndex, []).get(s.pageIndex)).push({\n slice: s,\n pos: i\n });\n });\n for (const [pageIdx, list] of byPage) {\n const pageCtx = ctx.acquirePage(pageIdx);\n const textPagePtr = pageCtx.getTextPage();\n for (const { slice, pos } of list) {\n const bufPtr = this.memoryManager.malloc(2 * (slice.charCount + 1));\n this.pdfiumModule.FPDFText_GetText(textPagePtr, slice.charIndex, slice.charCount, bufPtr);\n out[pos] = stripPdfUnwantedMarkers(this.pdfiumModule.pdfium.UTF16ToString(bufPtr));\n this.memoryManager.free(bufPtr);\n }\n pageCtx.release();\n }\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetTextSlices", "End", doc.id);\n return PdfTaskHelper.resolve(out);\n } catch (e) {\n this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, "getTextSlices error", e);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetTextSlices", "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: String(e)\n });\n }\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.merge}\n *\n * @public\n */\n merge(files) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "merge", files);\n const fileIds = files.map((file2) => file2.id).join(".");\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `Merge`, "Begin", fileIds);\n const newDocPtr = this.pdfiumModule.FPDF_CreateNewDocument();\n if (!newDocPtr) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `Merge`, "End", fileIds);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantCreateNewDoc,\n message: "can not create new document"\n });\n }\n const ptrs = [];\n for (const file2 of files.reverse()) {\n const array = new Uint8Array(file2.content);\n const length = array.length;\n const filePtr = this.memoryManager.malloc(length);\n this.pdfiumModule.pdfium.HEAPU8.set(array, filePtr);\n const docPtr = this.pdfiumModule.FPDF_LoadMemDocument(filePtr, length, "");\n if (!docPtr) {\n const lastError = this.pdfiumModule.FPDF_GetLastError();\n this.logger.error(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `FPDF_LoadMemDocument failed with ${lastError}`\n );\n this.memoryManager.free(filePtr);\n for (const ptr of ptrs) {\n this.pdfiumModule.FPDF_CloseDocument(ptr.docPtr);\n this.memoryManager.free(ptr.filePtr);\n }\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `Merge`, "End", fileIds);\n return PdfTaskHelper.reject({\n code: lastError,\n message: `FPDF_LoadMemDocument failed`\n });\n }\n ptrs.push({ filePtr, docPtr });\n if (!this.pdfiumModule.FPDF_ImportPages(newDocPtr, docPtr, "", 0)) {\n this.pdfiumModule.FPDF_CloseDocument(newDocPtr);\n for (const ptr of ptrs) {\n this.pdfiumModule.FPDF_CloseDocument(ptr.docPtr);\n this.memoryManager.free(ptr.filePtr);\n }\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `Merge`, "End", fileIds);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantImportPages,\n message: "can not import pages to new document"\n });\n }\n }\n const buffer = this.saveDocument(newDocPtr);\n this.pdfiumModule.FPDF_CloseDocument(newDocPtr);\n for (const ptr of ptrs) {\n this.pdfiumModule.FPDF_CloseDocument(ptr.docPtr);\n this.memoryManager.free(ptr.filePtr);\n }\n const file = {\n id: `${Math.random()}`,\n content: buffer\n };\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `Merge`, "End", fileIds);\n return PdfTaskHelper.resolve(file);\n }\n /**\n * Merges specific pages from multiple PDF documents in a custom order\n *\n * @param mergeConfigs Array of configurations specifying which pages to merge from which documents\n * @returns A PdfTask that resolves with the merged PDF file\n * @public\n */\n mergePages(mergeConfigs) {\n const configIds = mergeConfigs.map((config) => `${config.docId}:${config.pageIndices.join(",")}`).join("|");\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "mergePages", mergeConfigs);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `MergePages`, "Begin", configIds);\n const newDocPtr = this.pdfiumModule.FPDF_CreateNewDocument();\n if (!newDocPtr) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `MergePages`, "End", configIds);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantCreateNewDoc,\n message: "Cannot create new document"\n });\n }\n try {\n for (const config of [...mergeConfigs].reverse()) {\n const ctx = this.cache.getContext(config.docId);\n if (!ctx) {\n this.logger.warn(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `Document ${config.docId} is not open, skipping`\n );\n continue;\n }\n const pageCount = this.pdfiumModule.FPDF_GetPageCount(ctx.docPtr);\n const validPageIndices = config.pageIndices.filter(\n (index) => index >= 0 && index < pageCount\n );\n if (validPageIndices.length === 0) {\n continue;\n }\n const pageString = validPageIndices.map((index) => index + 1).join(",");\n try {\n if (!this.pdfiumModule.FPDF_ImportPages(\n newDocPtr,\n ctx.docPtr,\n pageString,\n 0\n // Insert at the beginning\n )) {\n throw new Error(`Failed to import pages ${pageString} from document ${config.docId}`);\n }\n } finally {\n }\n }\n const buffer = this.saveDocument(newDocPtr);\n const file = {\n id: `${Math.random()}`,\n content: buffer\n };\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `MergePages`, "End", configIds);\n return PdfTaskHelper.resolve(file);\n } catch (error) {\n this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, "mergePages failed", error);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `MergePages`, "End", configIds);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantImportPages,\n message: error instanceof Error ? error.message : "Failed to merge pages"\n });\n } finally {\n if (newDocPtr) {\n this.pdfiumModule.FPDF_CloseDocument(newDocPtr);\n }\n }\n }\n /**\n * Sets AES-256 encryption on a document.\n * Must be called before saveAsCopy() for encryption to take effect.\n *\n * @param doc - Document to encrypt\n * @param userPassword - Password to open document (empty = no open password)\n * @param ownerPassword - Password to change permissions (required)\n * @param allowedFlags - OR\'d PdfPermissionFlag values indicating allowed actions\n * @returns true on success, false if already encrypted or invalid params\n *\n * @public\n */\n setDocumentEncryption(doc, userPassword, ownerPassword, allowedFlags) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "setDocumentEncryption", doc, allowedFlags);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const result = this.pdfiumModule.EPDF_SetEncryption(\n ctx.docPtr,\n userPassword,\n ownerPassword,\n allowedFlags\n );\n return PdfTaskHelper.resolve(result);\n }\n /**\n * Marks document for encryption removal on save.\n * When saveAsCopy is called, the document will be saved without encryption.\n *\n * @param doc - Document to remove encryption from\n * @returns true on success\n *\n * @public\n */\n removeEncryption(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "removeEncryption", doc);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const result = this.pdfiumModule.EPDF_RemoveEncryption(ctx.docPtr);\n return PdfTaskHelper.resolve(result);\n }\n /**\n * Attempts to unlock owner permissions for an already-opened encrypted document.\n *\n * @param doc - Document to unlock\n * @param ownerPassword - The owner password\n * @returns true on success, false on failure\n *\n * @public\n */\n unlockOwnerPermissions(doc, ownerPassword) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "unlockOwnerPermissions", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const success = this.pdfiumModule.EPDF_UnlockOwnerPermissions(ctx.docPtr, ownerPassword);\n return PdfTaskHelper.resolve(success);\n }\n /**\n * Check if a document is encrypted.\n *\n * @param doc - Document to check\n * @returns true if the document is encrypted\n *\n * @public\n */\n isEncrypted(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "isEncrypted", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const result = this.pdfiumModule.EPDF_IsEncrypted(ctx.docPtr);\n return PdfTaskHelper.resolve(result);\n }\n /**\n * Check if owner permissions are currently unlocked.\n *\n * @param doc - Document to check\n * @returns true if owner permissions are unlocked\n *\n * @public\n */\n isOwnerUnlocked(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "isOwnerUnlocked", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const result = this.pdfiumModule.EPDF_IsOwnerUnlocked(ctx.docPtr);\n return PdfTaskHelper.resolve(result);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.saveAsCopy}\n *\n * @public\n */\n saveAsCopy(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "saveAsCopy", doc);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `SaveAsCopy`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `SaveAsCopy`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const buffer = this.saveDocument(ctx.docPtr);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `SaveAsCopy`, "End", doc.id);\n return PdfTaskHelper.resolve(buffer);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.closeDocument}\n *\n * @public\n */\n closeDocument(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "closeDocument", doc);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `CloseDocument`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) return PdfTaskHelper.resolve(true);\n ctx.dispose();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `CloseDocument`, "End", doc.id);\n return PdfTaskHelper.resolve(true);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.closeAllDocuments}\n *\n * @public\n */\n closeAllDocuments() {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "closeAllDocuments");\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `CloseAllDocuments`, "Begin");\n this.cache.closeAllDocuments();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `CloseAllDocuments`, "End");\n return PdfTaskHelper.resolve(true);\n }\n /**\n * Add text content to annotation\n * @param page - page info\n * @param pagePtr - pointer to page object\n * @param annotationPtr - pointer to text annotation\n * @param annotation - text annotation\n * @returns whether text content is added to annotation\n *\n * @private\n */\n addTextContent(doc, page, pagePtr, annotationPtr, annotation) {\n if (!this.setAnnotationIcon(annotationPtr, annotation.icon || PdfAnnotationIcon.Comment)) {\n return false;\n }\n if (annotation.state && !this.setAnnotString(annotationPtr, "State", annotation.state)) {\n return false;\n }\n if (annotation.stateModel && !this.setAnnotString(annotationPtr, "StateModel", annotation.stateModel)) {\n return false;\n }\n if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {\n return false;\n }\n const strokeColor = annotation.strokeColor ?? annotation.color ?? "#FFFF00";\n if (!this.setAnnotationColor(annotationPtr, strokeColor, PdfAnnotationColorType.Color)) {\n return false;\n }\n if (!annotation.flags) {\n if (!this.setAnnotationFlags(annotationPtr, ["print", "noZoom", "noRotate"])) {\n return false;\n }\n }\n return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);\n }\n /**\n * Add caret content to annotation\n * @param doc - document object\n * @param page - page info\n * @param pagePtr - pointer to page object\n * @param annotationPtr - pointer to caret annotation\n * @param annotation - caret annotation\n * @returns whether caret content is added to annotation\n *\n * @private\n */\n addCaretContent(doc, page, pagePtr, annotationPtr, annotation) {\n if (annotation.strokeColor) {\n this.setAnnotationColor(annotationPtr, annotation.strokeColor, PdfAnnotationColorType.Color);\n }\n if (annotation.opacity !== void 0) {\n this.setAnnotationOpacity(annotationPtr, annotation.opacity);\n }\n if (annotation.intent) {\n this.setAnnotIntent(annotationPtr, annotation.intent);\n }\n this.setRectangleDifferences(annotationPtr, annotation.rectangleDifferences);\n return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);\n }\n /**\n * Add free text content to annotation\n * @param page - page info\n * @param pagePtr - pointer to page object\n * @param annotationPtr - pointer to free text annotation\n * @param annotation - free text annotation\n * @returns whether free text content is added to annotation\n *\n * @private\n */\n addFreeTextContent(doc, page, pagePtr, annotationPtr, annotation) {\n if (!this.setBorderStyle(annotationPtr, PdfAnnotationBorderStyle.SOLID, 0)) {\n return false;\n }\n if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {\n return false;\n }\n if (!this.setAnnotationTextAlignment(annotationPtr, annotation.textAlign)) {\n return false;\n }\n if (!this.setAnnotationVerticalAlignment(annotationPtr, annotation.verticalAlign)) {\n return false;\n }\n if (!this.setAnnotationDefaultAppearance(\n annotationPtr,\n annotation.fontFamily,\n annotation.fontSize,\n annotation.fontColor\n )) {\n return false;\n }\n if (annotation.intent && !this.setAnnotIntent(annotationPtr, annotation.intent)) {\n return false;\n }\n const bgColor = annotation.color ?? annotation.backgroundColor;\n if (!bgColor || bgColor === "transparent") {\n if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.Color)) {\n return false;\n }\n } else if (!this.setAnnotationColor(annotationPtr, bgColor ?? "#FFFFFF", PdfAnnotationColorType.Color)) {\n return false;\n }\n this.setRectangleDifferences(annotationPtr, annotation.rectangleDifferences);\n return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);\n }\n /**\n * Set the rect of specified annotation\n * @param page - page info that the annotation is belonged to\n * @param pagePtr - pointer of page object\n * @param annotationPtr - pointer to annotation object\n * @param inkList - ink lists that added to the annotation\n * @returns whether the ink lists is setted\n *\n * @private\n */\n addInkStroke(doc, page, pagePtr, annotationPtr, annotation) {\n if (!this.setBorderStyle(annotationPtr, PdfAnnotationBorderStyle.SOLID, annotation.strokeWidth)) {\n return false;\n }\n if (!this.setInkList(doc, page, annotationPtr, annotation.inkList)) {\n return false;\n }\n if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {\n return false;\n }\n const strokeColor = annotation.strokeColor ?? annotation.color ?? "#FFFF00";\n if (!this.setAnnotationColor(annotationPtr, strokeColor, PdfAnnotationColorType.Color)) {\n return false;\n }\n return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);\n }\n /**\n * Add line content to annotation\n * @param page - page info\n * @param pagePtr - pointer to page object\n * @param annotationPtr - pointer to line annotation\n * @param annotation - line annotation\n * @returns whether line content is added to annotation\n *\n * @private\n */\n addLineContent(doc, page, pagePtr, annotationPtr, annotation) {\n var _a, _b;\n if (!this.setLinePoints(\n doc,\n page,\n annotationPtr,\n annotation.linePoints.start,\n annotation.linePoints.end\n )) {\n return false;\n }\n if (!this.setLineEndings(\n annotationPtr,\n ((_a = annotation.lineEndings) == null ? void 0 : _a.start) ?? PdfAnnotationLineEnding.None,\n ((_b = annotation.lineEndings) == null ? void 0 : _b.end) ?? PdfAnnotationLineEnding.None\n )) {\n return false;\n }\n if (!this.setBorderStyle(annotationPtr, annotation.strokeStyle, annotation.strokeWidth)) {\n return false;\n }\n if (!this.setBorderDashPattern(annotationPtr, annotation.strokeDashArray ?? [])) {\n return false;\n }\n if (annotation.intent && !this.setAnnotIntent(annotationPtr, annotation.intent)) {\n return false;\n }\n if (!annotation.color || annotation.color === "transparent") {\n if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.InteriorColor)) {\n return false;\n }\n } else if (!this.setAnnotationColor(\n annotationPtr,\n annotation.color ?? "#FFFF00",\n PdfAnnotationColorType.InteriorColor\n )) {\n return false;\n }\n if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {\n return false;\n }\n if (!this.setAnnotationColor(\n annotationPtr,\n annotation.strokeColor ?? "#FFFF00",\n PdfAnnotationColorType.Color\n )) {\n return false;\n }\n return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);\n }\n /**\n * Add polygon or polyline content to annotation\n * @param page - page info\n * @param pagePtr - pointer to page object\n * @param annotationPtr - pointer to polygon or polyline annotation\n * @param annotation - polygon or polyline annotation\n * @returns whether polygon or polyline content is added to annotation\n *\n * @private\n */\n addPolyContent(doc, page, pagePtr, annotationPtr, annotation) {\n var _a, _b;\n if (annotation.type === PdfAnnotationSubtype.POLYLINE && !this.setLineEndings(\n annotationPtr,\n ((_a = annotation.lineEndings) == null ? void 0 : _a.start) ?? PdfAnnotationLineEnding.None,\n ((_b = annotation.lineEndings) == null ? void 0 : _b.end) ?? PdfAnnotationLineEnding.None\n )) {\n return false;\n }\n if (!this.setPdfAnnoVertices(doc, page, annotationPtr, annotation.vertices)) {\n return false;\n }\n if (!this.setBorderStyle(annotationPtr, annotation.strokeStyle, annotation.strokeWidth)) {\n return false;\n }\n if (!this.setBorderDashPattern(annotationPtr, annotation.strokeDashArray ?? [])) {\n return false;\n }\n if (annotation.intent && !this.setAnnotIntent(annotationPtr, annotation.intent)) {\n return false;\n }\n if (!annotation.color || annotation.color === "transparent") {\n if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.InteriorColor)) {\n return false;\n }\n } else if (!this.setAnnotationColor(\n annotationPtr,\n annotation.color ?? "#FFFF00",\n PdfAnnotationColorType.InteriorColor\n )) {\n return false;\n }\n if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {\n return false;\n }\n if (!this.setAnnotationColor(\n annotationPtr,\n annotation.strokeColor ?? "#FFFF00",\n PdfAnnotationColorType.Color\n )) {\n return false;\n }\n if (annotation.type === PdfAnnotationSubtype.POLYGON) {\n this.setRectangleDifferences(\n annotationPtr,\n annotation.rectangleDifferences\n );\n }\n return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);\n }\n /**\n * Add link content (action or destination) to a link annotation\n * @param docPtr - pointer to pdf document\n * @param pagePtr - pointer to the page\n * @param annotationPtr - pointer to pdf annotation\n * @param annotation - the link annotation object\n * @returns true if successful\n *\n * @private\n */\n addLinkContent(doc, page, docPtr, pagePtr, annotationPtr, annotation) {\n const style = annotation.strokeStyle ?? PdfAnnotationBorderStyle.UNDERLINE;\n const width = annotation.strokeWidth ?? 2;\n if (!this.setBorderStyle(annotationPtr, style, width)) {\n return false;\n }\n if (annotation.strokeDashArray && !this.setBorderDashPattern(annotationPtr, annotation.strokeDashArray)) {\n return false;\n }\n if (annotation.strokeColor) {\n if (!this.setAnnotationColor(\n annotationPtr,\n annotation.strokeColor,\n PdfAnnotationColorType.Color\n )) {\n return false;\n }\n }\n if (annotation.target) {\n if (!this.applyLinkTarget(docPtr, annotationPtr, annotation.target)) {\n return false;\n }\n }\n return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);\n }\n /**\n * Add shape content to annotation\n * @param page - page info\n * @param pagePtr - pointer to page object\n * @param annotationPtr - pointer to shape annotation\n * @param annotation - shape annotation\n * @returns whether shape content is added to annotation\n *\n * @private\n */\n addShapeContent(doc, page, pagePtr, annotationPtr, annotation) {\n if (!this.setBorderStyle(annotationPtr, annotation.strokeStyle, annotation.strokeWidth)) {\n return false;\n }\n if (!this.setBorderDashPattern(annotationPtr, annotation.strokeDashArray ?? [])) {\n return false;\n }\n if (!annotation.color || annotation.color === "transparent") {\n if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.InteriorColor)) {\n return false;\n }\n } else if (!this.setAnnotationColor(\n annotationPtr,\n annotation.color ?? "#FFFF00",\n PdfAnnotationColorType.InteriorColor\n )) {\n return false;\n }\n if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {\n return false;\n }\n if (!this.setAnnotationColor(\n annotationPtr,\n annotation.strokeColor ?? "#FFFF00",\n PdfAnnotationColorType.Color\n )) {\n return false;\n }\n this.setRectangleDifferences(annotationPtr, annotation.rectangleDifferences);\n return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);\n }\n /**\n * Add highlight content to annotation\n * @param page - page info\n * @param annotationPtr - pointer to highlight annotation\n * @param annotation - highlight annotation\n * @returns whether highlight content is added to annotation\n *\n * @private\n */\n addTextMarkupContent(doc, page, pagePtr, annotationPtr, annotation) {\n if (!this.syncQuadPointsAnno(doc, page, annotationPtr, annotation.segmentRects)) {\n return false;\n }\n if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {\n return false;\n }\n const strokeColor = annotation.strokeColor ?? annotation.color ?? "#FFFF00";\n if (!this.setAnnotationColor(annotationPtr, strokeColor, PdfAnnotationColorType.Color)) {\n return false;\n }\n return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);\n }\n /**\n * Add content to redact annotation\n * @param page - page info\n * @param pagePtr - pointer to page object\n * @param annotationPtr - pointer to redact annotation\n * @param annotation - redact annotation\n * @returns whether redact content is added to annotation\n *\n * @private\n */\n addRedactContent(doc, page, pagePtr, annotationPtr, annotation) {\n if (!this.syncQuadPointsAnno(doc, page, annotationPtr, annotation.segmentRects)) {\n return false;\n }\n if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {\n return false;\n }\n if (!annotation.color || annotation.color === "transparent") {\n if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.InteriorColor)) {\n return false;\n }\n } else if (!this.setAnnotationColor(\n annotationPtr,\n annotation.color,\n PdfAnnotationColorType.InteriorColor\n )) {\n return false;\n }\n if (!annotation.overlayColor || annotation.overlayColor === "transparent") {\n if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.OverlayColor)) {\n return false;\n }\n } else if (!this.setAnnotationColor(\n annotationPtr,\n annotation.overlayColor,\n PdfAnnotationColorType.OverlayColor\n )) {\n return false;\n }\n if (!annotation.strokeColor || annotation.strokeColor === "transparent") {\n if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.Color)) {\n return false;\n }\n } else if (!this.setAnnotationColor(annotationPtr, annotation.strokeColor, PdfAnnotationColorType.Color)) {\n return false;\n }\n if (!this.setOverlayText(annotationPtr, annotation.overlayText)) {\n return false;\n }\n if (annotation.overlayTextRepeat !== void 0 && !this.setOverlayTextRepeat(annotationPtr, annotation.overlayTextRepeat)) {\n return false;\n }\n if (annotation.fontFamily !== void 0 || annotation.fontSize !== void 0) {\n if (!this.setAnnotationDefaultAppearance(\n annotationPtr,\n annotation.fontFamily ?? PdfStandardFont.Helvetica,\n annotation.fontSize ?? 12,\n annotation.fontColor ?? "#000000"\n )) {\n return false;\n }\n }\n if (annotation.textAlign !== void 0 && !this.setAnnotationTextAlignment(annotationPtr, annotation.textAlign)) {\n return false;\n }\n return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);\n }\n /**\n * Add contents to stamp annotation\n * @param doc - pdf document object\n * @param docPtr - pointer to pdf document object\n * @param page - page info\n * @param pagePtr - pointer to page object\n * @param annotationPtr - pointer to stamp annotation\n * @param rect - rect of stamp annotation\n * @param contents - contents of stamp annotation\n * @returns whether contents is added to annotation\n *\n * @private\n */\n addStampContent(doc, docPtr, page, pagePtr, annotationPtr, annotation, imageData) {\n if (annotation.icon && !this.setAnnotationIcon(annotationPtr, annotation.icon)) {\n return false;\n }\n if (annotation.subject && !this.setAnnotString(annotationPtr, "Subj", annotation.subject)) {\n return false;\n }\n if (imageData) {\n for (let i = this.pdfiumModule.FPDFAnnot_GetObjectCount(annotationPtr) - 1; i >= 0; i--) {\n this.pdfiumModule.FPDFAnnot_RemoveObject(annotationPtr, i);\n }\n if (!this.addImageObject(doc, docPtr, page, pagePtr, annotationPtr, annotation.rect, imageData)) {\n return false;\n }\n }\n if (!this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation)) {\n return false;\n }\n return !!this.pdfiumModule.EPDFAnnot_UpdateAppearanceToRect(annotationPtr, PdfStampFit.Cover);\n }\n /**\n * Add image object to annotation\n * @param doc - pdf document object\n * @param docPtr - pointer to pdf document object\n * @param page - page info\n * @param pagePtr - pointer to page object\n * @param annotationPtr - pointer to stamp annotation\n * @param position - position of image\n * @param imageData - data of image\n * @returns whether image is added to annotation\n *\n * @private\n */\n addImageObject(doc, docPtr, page, pagePtr, annotationPtr, rect, imageData) {\n const bytesPerPixel = 4;\n const pixelCount = imageData.width * imageData.height;\n const bitmapBufferPtr = this.memoryManager.malloc(bytesPerPixel * pixelCount);\n if (!bitmapBufferPtr) {\n return false;\n }\n for (let i = 0; i < pixelCount; i++) {\n const red = imageData.data[i * bytesPerPixel];\n const green = imageData.data[i * bytesPerPixel + 1];\n const blue = imageData.data[i * bytesPerPixel + 2];\n const alpha = imageData.data[i * bytesPerPixel + 3];\n this.pdfiumModule.pdfium.setValue(bitmapBufferPtr + i * bytesPerPixel, blue, "i8");\n this.pdfiumModule.pdfium.setValue(bitmapBufferPtr + i * bytesPerPixel + 1, green, "i8");\n this.pdfiumModule.pdfium.setValue(bitmapBufferPtr + i * bytesPerPixel + 2, red, "i8");\n this.pdfiumModule.pdfium.setValue(bitmapBufferPtr + i * bytesPerPixel + 3, alpha, "i8");\n }\n const format = 4;\n const bitmapPtr = this.pdfiumModule.FPDFBitmap_CreateEx(\n imageData.width,\n imageData.height,\n format,\n bitmapBufferPtr,\n 0\n );\n if (!bitmapPtr) {\n this.memoryManager.free(bitmapBufferPtr);\n return false;\n }\n const imageObjectPtr = this.pdfiumModule.FPDFPageObj_NewImageObj(docPtr);\n if (!imageObjectPtr) {\n this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);\n this.memoryManager.free(bitmapBufferPtr);\n return false;\n }\n if (!this.pdfiumModule.FPDFImageObj_SetBitmap(pagePtr, 0, imageObjectPtr, bitmapPtr)) {\n this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);\n this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);\n this.memoryManager.free(bitmapBufferPtr);\n return false;\n }\n const matrixPtr = this.memoryManager.malloc(6 * 4);\n this.pdfiumModule.pdfium.setValue(matrixPtr, imageData.width, "float");\n this.pdfiumModule.pdfium.setValue(matrixPtr + 4, 0, "float");\n this.pdfiumModule.pdfium.setValue(matrixPtr + 8, 0, "float");\n this.pdfiumModule.pdfium.setValue(matrixPtr + 12, imageData.height, "float");\n this.pdfiumModule.pdfium.setValue(matrixPtr + 16, 0, "float");\n this.pdfiumModule.pdfium.setValue(matrixPtr + 20, 0, "float");\n if (!this.pdfiumModule.FPDFPageObj_SetMatrix(imageObjectPtr, matrixPtr)) {\n this.memoryManager.free(matrixPtr);\n this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);\n this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);\n this.memoryManager.free(bitmapBufferPtr);\n return false;\n }\n this.memoryManager.free(matrixPtr);\n const pagePos = this.convertDevicePointToPagePoint(doc, page, {\n x: rect.origin.x,\n y: rect.origin.y + imageData.height\n // shift down by the image height\n });\n this.pdfiumModule.FPDFPageObj_Transform(imageObjectPtr, 1, 0, 0, 1, pagePos.x, pagePos.y);\n if (!this.pdfiumModule.FPDFAnnot_AppendObject(annotationPtr, imageObjectPtr)) {\n this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);\n this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);\n this.memoryManager.free(bitmapBufferPtr);\n return false;\n }\n this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);\n this.memoryManager.free(bitmapBufferPtr);\n return true;\n }\n /**\n * Save document to array buffer\n * @param docPtr - pointer to pdf document\n * @returns array buffer contains the pdf content\n *\n * @private\n */\n saveDocument(docPtr) {\n const writerPtr = this.pdfiumModule.PDFiumExt_OpenFileWriter();\n this.pdfiumModule.PDFiumExt_SaveAsCopy(docPtr, writerPtr);\n const size = this.pdfiumModule.PDFiumExt_GetFileWriterSize(writerPtr);\n const dataPtr = this.memoryManager.malloc(size);\n this.pdfiumModule.PDFiumExt_GetFileWriterData(writerPtr, dataPtr, size);\n const buffer = new ArrayBuffer(size);\n const view = new DataView(buffer);\n for (let i = 0; i < size; i++) {\n view.setInt8(i, this.pdfiumModule.pdfium.getValue(dataPtr + i, "i8"));\n }\n this.memoryManager.free(dataPtr);\n this.pdfiumModule.PDFiumExt_CloseFileWriter(writerPtr);\n return buffer;\n }\n /**\n * Read Catalog /Lang via EPDFCatalog_GetLanguage (UTF-16LE → JS string).\n * Returns:\n * null -> /Lang not present (getter returned 0) OR doc not open,\n * \'\' -> /Lang exists but is explicitly empty,\n * \'en\', \'en-US\', ... -> normal tag.\n *\n * Note: EPDFCatalog_GetLanguage lengths are BYTES (incl. trailing NUL).\n *\n * @private\n */\n readCatalogLanguage(docPtr) {\n const byteLen = this.pdfiumModule.EPDFCatalog_GetLanguage(docPtr, 0, 0) >>> 0;\n if (byteLen === 0) return null;\n if (byteLen === 2) return "";\n return readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => this.pdfiumModule.EPDFCatalog_GetLanguage(docPtr, buffer, bufferLength),\n this.pdfiumModule.pdfium.UTF16ToString,\n byteLen\n );\n }\n /**\n * Read metadata from pdf document\n * @param docPtr - pointer to pdf document\n * @param key - key of metadata field\n * @returns metadata value\n *\n * @private\n */\n readMetaText(docPtr, key) {\n const exists = !!this.pdfiumModule.EPDF_HasMetaText(docPtr, key);\n if (!exists) return null;\n const len = this.pdfiumModule.FPDF_GetMetaText(docPtr, key, 0, 0);\n if (len === 2) return "";\n return readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => this.pdfiumModule.FPDF_GetMetaText(docPtr, key, buffer, bufferLength),\n this.pdfiumModule.pdfium.UTF16ToString,\n len\n );\n }\n /**\n * Write metadata into the PDF\'s Info dictionary.\n * If `value` is null or empty string, the key is removed.\n * @param docPtr - pointer to pdf document\n * @param key - key of metadata field\n * @param value - value of metadata field\n * @returns whether metadata is written to the pdf document\n *\n * @private\n */\n setMetaText(docPtr, key, value) {\n if (value == null || value.length === 0) {\n const ok = this.pdfiumModule.EPDF_SetMetaText(docPtr, key, 0);\n return !!ok;\n }\n const bytes = 2 * (value.length + 1);\n const ptr = this.memoryManager.malloc(bytes);\n try {\n this.pdfiumModule.pdfium.stringToUTF16(value, ptr, bytes);\n const ok = this.pdfiumModule.EPDF_SetMetaText(docPtr, key, ptr);\n return !!ok;\n } finally {\n this.memoryManager.free(ptr);\n }\n }\n /**\n * Read the document\'s trapped status via PDFium.\n * Falls back to `Unknown` on unexpected values.\n *\n * @private\n */\n getMetaTrapped(docPtr) {\n const raw = Number(this.pdfiumModule.EPDF_GetMetaTrapped(docPtr));\n switch (raw) {\n case PdfTrappedStatus.NotSet:\n case PdfTrappedStatus.True:\n case PdfTrappedStatus.False:\n case PdfTrappedStatus.Unknown:\n return raw;\n default:\n return PdfTrappedStatus.Unknown;\n }\n }\n /**\n * Write (or clear) the document\'s trapped status via PDFium.\n * Pass `null`/`undefined` to remove the `/Trapped` key.\n *\n * @private\n */\n setMetaTrapped(docPtr, status) {\n const toSet = status == null || status === void 0 ? PdfTrappedStatus.NotSet : status;\n const valid = toSet === PdfTrappedStatus.NotSet || toSet === PdfTrappedStatus.True || toSet === PdfTrappedStatus.False || toSet === PdfTrappedStatus.Unknown;\n if (!valid) return false;\n return !!this.pdfiumModule.EPDF_SetMetaTrapped(docPtr, toSet);\n }\n /**\n * Get the number of keys in the document\'s Info dictionary.\n * @param docPtr - pointer to pdf document\n * @param customOnly - if true, only count non-reserved (custom) keys; if false, count all keys.\n * @returns the number of keys (possibly 0). On error, returns 0.\n *\n * @private\n */\n getMetaKeyCount(docPtr, customOnly) {\n return Number(this.pdfiumModule.EPDF_GetMetaKeyCount(docPtr, customOnly)) | 0;\n }\n /**\n * Get the name of the Info dictionary key at |index|.\n * @param docPtr - pointer to pdf document\n * @param index - 0-based key index in the order returned by PDFium.\n * @param customOnly - if true, indexes only over non-reserved (custom) keys; if false, indexes over all keys.\n * @returns the name of the key, or null if the key is not found.\n *\n * @private\n */\n getMetaKeyName(docPtr, index, customOnly) {\n const len = this.pdfiumModule.EPDF_GetMetaKeyName(docPtr, index, customOnly, 0, 0);\n if (!len) return null;\n return readString(\n this.pdfiumModule.pdfium,\n (buffer, buflen) => this.pdfiumModule.EPDF_GetMetaKeyName(docPtr, index, customOnly, buffer, buflen),\n this.pdfiumModule.pdfium.UTF8ToString,\n len\n );\n }\n /**\n * Read all metadata from the document\'s Info dictionary.\n * @param docPtr - pointer to pdf document\n * @param customOnly - if true, only read non-reserved (custom) keys; if false, read all keys.\n * @returns all metadata\n *\n * @private\n */\n readAllMeta(docPtr, customOnly = true) {\n const n = this.getMetaKeyCount(docPtr, customOnly);\n const out = {};\n for (let i = 0; i < n; i++) {\n const key = this.getMetaKeyName(docPtr, i, customOnly);\n if (!key) continue;\n out[key] = this.readMetaText(docPtr, key);\n }\n return out;\n }\n /**\n * Read bookmarks in the pdf document\n * @param docPtr - pointer to pdf document\n * @param rootBookmarkPtr - pointer to root bookmark\n * @returns bookmarks in the pdf document\n *\n * @private\n */\n readPdfBookmarks(docPtr, rootBookmarkPtr = 0) {\n let bookmarkPtr = this.pdfiumModule.FPDFBookmark_GetFirstChild(docPtr, rootBookmarkPtr);\n const bookmarks = [];\n while (bookmarkPtr) {\n const bookmark = this.readPdfBookmark(docPtr, bookmarkPtr);\n bookmarks.push(bookmark);\n const nextBookmarkPtr = this.pdfiumModule.FPDFBookmark_GetNextSibling(docPtr, bookmarkPtr);\n bookmarkPtr = nextBookmarkPtr;\n }\n return bookmarks;\n }\n /**\n * Read bookmark in the pdf document\n * @param docPtr - pointer to pdf document\n * @param bookmarkPtr - pointer to bookmark object\n * @returns pdf bookmark object\n *\n * @private\n */\n readPdfBookmark(docPtr, bookmarkPtr) {\n const title = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFBookmark_GetTitle(bookmarkPtr, buffer, bufferLength);\n },\n this.pdfiumModule.pdfium.UTF16ToString\n );\n const bookmarks = this.readPdfBookmarks(docPtr, bookmarkPtr);\n const target = this.readPdfBookmarkTarget(\n docPtr,\n () => {\n return this.pdfiumModule.FPDFBookmark_GetAction(bookmarkPtr);\n },\n () => {\n return this.pdfiumModule.FPDFBookmark_GetDest(docPtr, bookmarkPtr);\n }\n );\n return {\n title,\n target,\n children: bookmarks\n };\n }\n /**\n * Read text rects in pdf page\n * @param page - pdf page info\n * @param docPtr - pointer to pdf document\n * @param pagePtr - pointer to pdf page\n * @param textPagePtr - pointer to pdf text page\n * @returns text rects in the pdf page\n *\n * @public\n */\n readPageTextRects(page, docPtr, pagePtr, textPagePtr) {\n const rectsCount = this.pdfiumModule.FPDFText_CountRects(textPagePtr, 0, -1);\n const textRects = [];\n for (let i = 0; i < rectsCount; i++) {\n const topPtr = this.memoryManager.malloc(8);\n const leftPtr = this.memoryManager.malloc(8);\n const rightPtr = this.memoryManager.malloc(8);\n const bottomPtr = this.memoryManager.malloc(8);\n const isSucceed = this.pdfiumModule.FPDFText_GetRect(\n textPagePtr,\n i,\n leftPtr,\n topPtr,\n rightPtr,\n bottomPtr\n );\n if (!isSucceed) {\n this.memoryManager.free(leftPtr);\n this.memoryManager.free(topPtr);\n this.memoryManager.free(rightPtr);\n this.memoryManager.free(bottomPtr);\n continue;\n }\n const left = this.pdfiumModule.pdfium.getValue(leftPtr, "double");\n const top = this.pdfiumModule.pdfium.getValue(topPtr, "double");\n const right = this.pdfiumModule.pdfium.getValue(rightPtr, "double");\n const bottom = this.pdfiumModule.pdfium.getValue(bottomPtr, "double");\n this.memoryManager.free(leftPtr);\n this.memoryManager.free(topPtr);\n this.memoryManager.free(rightPtr);\n this.memoryManager.free(bottomPtr);\n const deviceXPtr = this.memoryManager.malloc(4);\n const deviceYPtr = this.memoryManager.malloc(4);\n this.pdfiumModule.FPDF_PageToDevice(\n pagePtr,\n 0,\n 0,\n page.size.width,\n page.size.height,\n 0,\n left,\n top,\n deviceXPtr,\n deviceYPtr\n );\n const x = this.pdfiumModule.pdfium.getValue(deviceXPtr, "i32");\n const y = this.pdfiumModule.pdfium.getValue(deviceYPtr, "i32");\n this.memoryManager.free(deviceXPtr);\n this.memoryManager.free(deviceYPtr);\n const rect = {\n origin: {\n x,\n y\n },\n size: {\n width: Math.ceil(Math.abs(right - left)),\n height: Math.ceil(Math.abs(top - bottom))\n }\n };\n const utf16Length = this.pdfiumModule.FPDFText_GetBoundedText(\n textPagePtr,\n left,\n top,\n right,\n bottom,\n 0,\n 0\n );\n const bytesCount = (utf16Length + 1) * 2;\n const textBuffer = this.memoryManager.malloc(bytesCount);\n this.pdfiumModule.FPDFText_GetBoundedText(\n textPagePtr,\n left,\n top,\n right,\n bottom,\n textBuffer,\n utf16Length\n );\n const content = this.pdfiumModule.pdfium.UTF16ToString(textBuffer);\n this.memoryManager.free(textBuffer);\n const charIndex = this.pdfiumModule.FPDFText_GetCharIndexAtPos(textPagePtr, left, top, 2, 2);\n let fontFamily = "";\n let fontSize = rect.size.height;\n if (charIndex >= 0) {\n fontSize = this.pdfiumModule.FPDFText_GetFontSize(textPagePtr, charIndex);\n const fontNameLength = this.pdfiumModule.FPDFText_GetFontInfo(\n textPagePtr,\n charIndex,\n 0,\n 0,\n 0\n );\n const bytesCount2 = fontNameLength + 1;\n const textBufferPtr = this.memoryManager.malloc(bytesCount2);\n const flagsPtr = this.memoryManager.malloc(4);\n this.pdfiumModule.FPDFText_GetFontInfo(\n textPagePtr,\n charIndex,\n textBufferPtr,\n bytesCount2,\n flagsPtr\n );\n fontFamily = this.pdfiumModule.pdfium.UTF8ToString(textBufferPtr);\n this.memoryManager.free(textBufferPtr);\n this.memoryManager.free(flagsPtr);\n }\n const textRect = {\n content,\n rect,\n font: {\n family: fontFamily,\n size: fontSize\n }\n };\n textRects.push(textRect);\n }\n return textRects;\n }\n /**\n * Return geometric + logical text layout for one page\n * (glyph-only implementation, no FPDFText_GetRect).\n *\n * @public\n */\n getPageGeometry(doc, page) {\n const label = "getPageGeometry";\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const textPagePtr = pageCtx.getTextPage();\n const glyphCount = this.pdfiumModule.FPDFText_CountChars(textPagePtr);\n const glyphs = [];\n for (let i = 0; i < glyphCount; i++) {\n const g = this.readGlyphInfo(page, pageCtx.pagePtr, textPagePtr, i);\n glyphs.push(g);\n }\n const runs = this.buildRunsFromGlyphs(glyphs, textPagePtr);\n pageCtx.release();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", doc.id);\n return PdfTaskHelper.resolve({ runs });\n }\n /**\n * Group consecutive glyphs that belong to the same CPDF_TextObject\n * using FPDFText_GetTextObject(), and calculate rotation from glyph positions.\n */\n buildRunsFromGlyphs(glyphs, textPagePtr) {\n const runs = [];\n let current = null;\n let curObjPtr = null;\n let bounds = null;\n for (let i = 0; i < glyphs.length; i++) {\n const g = glyphs[i];\n const objPtr = this.pdfiumModule.FPDFText_GetTextObject(textPagePtr, i);\n if (objPtr !== curObjPtr) {\n curObjPtr = objPtr;\n current = {\n rect: {\n x: g.origin.x,\n y: g.origin.y,\n width: g.size.width,\n height: g.size.height\n },\n charStart: i,\n glyphs: [],\n fontSize: this.pdfiumModule.FPDFText_GetFontSize(textPagePtr, i)\n };\n bounds = {\n minX: g.origin.x,\n minY: g.origin.y,\n maxX: g.origin.x + g.size.width,\n maxY: g.origin.y + g.size.height\n };\n runs.push(current);\n }\n current.glyphs.push({\n x: g.origin.x,\n y: g.origin.y,\n width: g.size.width,\n height: g.size.height,\n flags: g.isEmpty ? 2 : g.isSpace ? 1 : 0,\n ...g.tightOrigin && { tightX: g.tightOrigin.x, tightY: g.tightOrigin.y },\n ...g.tightSize && { tightWidth: g.tightSize.width, tightHeight: g.tightSize.height }\n });\n if (g.isEmpty) {\n continue;\n }\n const right = g.origin.x + g.size.width;\n const bottom = g.origin.y + g.size.height;\n bounds.minX = Math.min(bounds.minX, g.origin.x);\n bounds.minY = Math.min(bounds.minY, g.origin.y);\n bounds.maxX = Math.max(bounds.maxX, right);\n bounds.maxY = Math.max(bounds.maxY, bottom);\n current.rect.x = bounds.minX;\n current.rect.y = bounds.minY;\n current.rect.width = bounds.maxX - bounds.minX;\n current.rect.height = bounds.maxY - bounds.minY;\n }\n return runs;\n }\n /**\n * Rich text runs: groups consecutive characters sharing the same\n * text object, font, size, and fill color into structured segments\n * with full font metadata and bounding boxes in PDF page coordinates.\n *\n * @public\n */\n getPageTextRuns(doc, page) {\n const label = "getPageTextRuns";\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const textPagePtr = pageCtx.getTextPage();\n const charCount = this.pdfiumModule.FPDFText_CountChars(textPagePtr);\n const runs = [];\n let runStart = 0;\n let curObjPtr = null;\n let curFont = null;\n let curFontSize = 0;\n let curColor = null;\n let bounds = null;\n const flushRun = (end) => {\n if (curObjPtr === null || curFont === null || curColor === null || bounds === null) return;\n const count = end - runStart;\n if (count <= 0) return;\n const bufPtr = this.memoryManager.malloc(2 * (count + 1));\n this.pdfiumModule.FPDFText_GetText(textPagePtr, runStart, count, bufPtr);\n const text = stripPdfUnwantedMarkers(this.pdfiumModule.pdfium.UTF16ToString(bufPtr));\n this.memoryManager.free(bufPtr);\n runs.push({\n text,\n rect: {\n origin: { x: bounds.minX, y: bounds.minY },\n size: {\n width: Math.max(1, bounds.maxX - bounds.minX),\n height: Math.max(1, bounds.maxY - bounds.minY)\n }\n },\n font: curFont,\n fontSize: curFontSize,\n color: curColor,\n charIndex: runStart,\n charCount: count\n });\n };\n const rPtr = this.memoryManager.malloc(4);\n const gPtr = this.memoryManager.malloc(4);\n const bPtr = this.memoryManager.malloc(4);\n const aPtr = this.memoryManager.malloc(4);\n const rectPtr = this.memoryManager.malloc(16);\n const dx1Ptr = this.memoryManager.malloc(4);\n const dy1Ptr = this.memoryManager.malloc(4);\n const dx2Ptr = this.memoryManager.malloc(4);\n const dy2Ptr = this.memoryManager.malloc(4);\n const italicAnglePtr = this.memoryManager.malloc(4);\n for (let i = 0; i < charCount; i++) {\n const uc = this.pdfiumModule.FPDFText_GetUnicode(textPagePtr, i);\n if (uc === 65534 || uc === 65533) continue;\n const objPtr = this.pdfiumModule.FPDFText_GetTextObject(textPagePtr, i);\n if (objPtr === 0) continue;\n const fontSize = this.pdfiumModule.FPDFText_GetFontSize(textPagePtr, i);\n this.pdfiumModule.FPDFText_GetFillColor(textPagePtr, i, rPtr, gPtr, bPtr, aPtr);\n const red = this.pdfiumModule.pdfium.getValue(rPtr, "i32") & 255;\n const green = this.pdfiumModule.pdfium.getValue(gPtr, "i32") & 255;\n const blue = this.pdfiumModule.pdfium.getValue(bPtr, "i32") & 255;\n const alpha = this.pdfiumModule.pdfium.getValue(aPtr, "i32") & 255;\n const fontInfo = this.readFontInfoFromTextObject(objPtr, italicAnglePtr);\n const needNewRun = curObjPtr === null || objPtr !== curObjPtr || fontInfo.name !== curFont.name || Math.abs(fontSize - curFontSize) > 0.01 || red !== curColor.red || green !== curColor.green || blue !== curColor.blue;\n if (needNewRun) {\n flushRun(i);\n curObjPtr = objPtr;\n curFont = fontInfo;\n curFontSize = fontSize;\n curColor = { red, green, blue, alpha };\n runStart = i;\n bounds = null;\n }\n if (this.pdfiumModule.FPDFText_GetLooseCharBox(textPagePtr, i, rectPtr)) {\n const left = this.pdfiumModule.pdfium.getValue(rectPtr, "float");\n const top = this.pdfiumModule.pdfium.getValue(rectPtr + 4, "float");\n const right = this.pdfiumModule.pdfium.getValue(rectPtr + 8, "float");\n const bottom = this.pdfiumModule.pdfium.getValue(rectPtr + 12, "float");\n if (left !== right && top !== bottom) {\n this.pdfiumModule.FPDF_PageToDevice(\n pageCtx.pagePtr,\n 0,\n 0,\n page.size.width,\n page.size.height,\n 0,\n left,\n top,\n dx1Ptr,\n dy1Ptr\n );\n this.pdfiumModule.FPDF_PageToDevice(\n pageCtx.pagePtr,\n 0,\n 0,\n page.size.width,\n page.size.height,\n 0,\n right,\n bottom,\n dx2Ptr,\n dy2Ptr\n );\n const x1 = this.pdfiumModule.pdfium.getValue(dx1Ptr, "i32");\n const y1 = this.pdfiumModule.pdfium.getValue(dy1Ptr, "i32");\n const x2 = this.pdfiumModule.pdfium.getValue(dx2Ptr, "i32");\n const y2 = this.pdfiumModule.pdfium.getValue(dy2Ptr, "i32");\n const cx = Math.min(x1, x2);\n const cy = Math.min(y1, y2);\n const cw = Math.abs(x2 - x1);\n const ch = Math.abs(y2 - y1);\n if (bounds === null) {\n bounds = { minX: cx, minY: cy, maxX: cx + cw, maxY: cy + ch };\n } else {\n bounds.minX = Math.min(bounds.minX, cx);\n bounds.minY = Math.min(bounds.minY, cy);\n bounds.maxX = Math.max(bounds.maxX, cx + cw);\n bounds.maxY = Math.max(bounds.maxY, cy + ch);\n }\n }\n }\n }\n flushRun(charCount);\n [rPtr, gPtr, bPtr, aPtr, rectPtr, dx1Ptr, dy1Ptr, dx2Ptr, dy2Ptr, italicAnglePtr].forEach(\n (p) => this.memoryManager.free(p)\n );\n pageCtx.release();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", doc.id);\n return PdfTaskHelper.resolve({ runs });\n }\n /**\n * Read font metadata from a text object handle via FPDFFont_* APIs.\n */\n readFontInfoFromTextObject(textObjPtr, italicAnglePtr) {\n const fontPtr = this.pdfiumModule.FPDFTextObj_GetFont(textObjPtr);\n let name = "";\n let familyName = "";\n let weight = 400;\n let italic = false;\n let monospaced = false;\n let embedded = false;\n if (fontPtr) {\n const nameLen = this.pdfiumModule.FPDFFont_GetBaseFontName(fontPtr, 0, 0);\n if (nameLen > 0) {\n const nameBuf = this.memoryManager.malloc(nameLen + 1);\n this.pdfiumModule.FPDFFont_GetBaseFontName(fontPtr, nameBuf, nameLen + 1);\n name = this.pdfiumModule.pdfium.UTF8ToString(nameBuf);\n this.memoryManager.free(nameBuf);\n }\n const famLen = this.pdfiumModule.FPDFFont_GetFamilyName(fontPtr, 0, 0);\n if (famLen > 0) {\n const famBuf = this.memoryManager.malloc(famLen + 1);\n this.pdfiumModule.FPDFFont_GetFamilyName(fontPtr, famBuf, famLen + 1);\n familyName = this.pdfiumModule.pdfium.UTF8ToString(famBuf);\n this.memoryManager.free(famBuf);\n }\n weight = this.pdfiumModule.FPDFFont_GetWeight(fontPtr);\n embedded = this.pdfiumModule.FPDFFont_GetIsEmbedded(fontPtr) !== 0;\n if (this.pdfiumModule.FPDFFont_GetItalicAngle(fontPtr, italicAnglePtr)) {\n const angle = this.pdfiumModule.pdfium.getValue(italicAnglePtr, "i32");\n italic = angle !== 0;\n }\n const flags = this.pdfiumModule.FPDFFont_GetFlags(fontPtr);\n monospaced = (flags & 1) !== 0;\n }\n return { name, familyName, weight, italic, monospaced, embedded };\n }\n /**\n * Extract glyph geometry + metadata for `charIndex`\n *\n * Returns device–space coordinates:\n * x,y → **top-left** corner (integer-pixels)\n * w,h → width / height (integer-pixels, ≥ 1)\n *\n * And two flags:\n * isSpace → true if the glyph\'s Unicode code-point is U+0020\n */\n readGlyphInfo(page, pagePtr, textPagePtr, charIndex) {\n const dx1Ptr = this.memoryManager.malloc(4);\n const dy1Ptr = this.memoryManager.malloc(4);\n const dx2Ptr = this.memoryManager.malloc(4);\n const dy2Ptr = this.memoryManager.malloc(4);\n const rectPtr = this.memoryManager.malloc(16);\n const tLeftPtr = this.memoryManager.malloc(8);\n const tRightPtr = this.memoryManager.malloc(8);\n const tBottomPtr = this.memoryManager.malloc(8);\n const tTopPtr = this.memoryManager.malloc(8);\n const allPtrs = [\n rectPtr,\n dx1Ptr,\n dy1Ptr,\n dx2Ptr,\n dy2Ptr,\n tLeftPtr,\n tRightPtr,\n tBottomPtr,\n tTopPtr\n ];\n let x = 0, y = 0, width = 0, height = 0, isSpace = false;\n let tightOrigin;\n let tightSize;\n if (this.pdfiumModule.FPDFText_GetLooseCharBox(textPagePtr, charIndex, rectPtr)) {\n const left = this.pdfiumModule.pdfium.getValue(rectPtr, "float");\n const top = this.pdfiumModule.pdfium.getValue(rectPtr + 4, "float");\n const right = this.pdfiumModule.pdfium.getValue(rectPtr + 8, "float");\n const bottom = this.pdfiumModule.pdfium.getValue(rectPtr + 12, "float");\n if (left === right || top === bottom) {\n allPtrs.forEach((p) => this.memoryManager.free(p));\n return {\n origin: { x: 0, y: 0 },\n size: { width: 0, height: 0 },\n isEmpty: true\n };\n }\n this.pdfiumModule.FPDF_PageToDevice(\n pagePtr,\n 0,\n 0,\n page.size.width,\n page.size.height,\n 0,\n left,\n top,\n dx1Ptr,\n dy1Ptr\n );\n this.pdfiumModule.FPDF_PageToDevice(\n pagePtr,\n 0,\n 0,\n page.size.width,\n page.size.height,\n 0,\n right,\n bottom,\n dx2Ptr,\n dy2Ptr\n );\n const x1 = this.pdfiumModule.pdfium.getValue(dx1Ptr, "i32");\n const y1 = this.pdfiumModule.pdfium.getValue(dy1Ptr, "i32");\n const x2 = this.pdfiumModule.pdfium.getValue(dx2Ptr, "i32");\n const y2 = this.pdfiumModule.pdfium.getValue(dy2Ptr, "i32");\n x = Math.min(x1, x2);\n y = Math.min(y1, y2);\n width = Math.max(1, Math.abs(x2 - x1));\n height = Math.max(1, Math.abs(y2 - y1));\n if (this.pdfiumModule.FPDFText_GetCharBox(\n textPagePtr,\n charIndex,\n tLeftPtr,\n tRightPtr,\n tBottomPtr,\n tTopPtr\n )) {\n const tLeft = this.pdfiumModule.pdfium.getValue(tLeftPtr, "double");\n const tRight = this.pdfiumModule.pdfium.getValue(tRightPtr, "double");\n const tBottom = this.pdfiumModule.pdfium.getValue(tBottomPtr, "double");\n const tTop = this.pdfiumModule.pdfium.getValue(tTopPtr, "double");\n this.pdfiumModule.FPDF_PageToDevice(\n pagePtr,\n 0,\n 0,\n page.size.width,\n page.size.height,\n 0,\n tLeft,\n tTop,\n dx1Ptr,\n dy1Ptr\n );\n this.pdfiumModule.FPDF_PageToDevice(\n pagePtr,\n 0,\n 0,\n page.size.width,\n page.size.height,\n 0,\n tRight,\n tBottom,\n dx2Ptr,\n dy2Ptr\n );\n const tx1 = this.pdfiumModule.pdfium.getValue(dx1Ptr, "i32");\n const ty1 = this.pdfiumModule.pdfium.getValue(dy1Ptr, "i32");\n const tx2 = this.pdfiumModule.pdfium.getValue(dx2Ptr, "i32");\n const ty2 = this.pdfiumModule.pdfium.getValue(dy2Ptr, "i32");\n tightOrigin = { x: Math.min(tx1, tx2), y: Math.min(ty1, ty2) };\n tightSize = {\n width: Math.max(1, Math.abs(tx2 - tx1)),\n height: Math.max(1, Math.abs(ty2 - ty1))\n };\n }\n const uc = this.pdfiumModule.FPDFText_GetUnicode(textPagePtr, charIndex);\n isSpace = uc === 32;\n }\n allPtrs.forEach((p) => this.memoryManager.free(p));\n return {\n origin: { x, y },\n size: { width, height },\n ...tightOrigin && { tightOrigin },\n ...tightSize && { tightSize },\n ...isSpace && { isSpace }\n };\n }\n /**\n * Geometry-only text extraction\n * ------------------------------------------\n * Returns every glyph on the requested page\n * in the logical order delivered by PDFium.\n *\n * The promise resolves to an array of objects:\n * {\n * idx: number; // glyph index on the page (0…n-1)\n * origin: { x: number; y: number };\n * size: { width: number; height: number };\n * angle: number; // degrees, counter-clock-wise\n * isSpace: boolean; // true → U+0020\n * }\n *\n * No Unicode is included; front-end decides whether to hydrate it.\n */\n getPageGlyphs(doc, page) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageGlyphs", doc, page);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageGlyphs", "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageGlyphs", "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const textPagePtr = pageCtx.getTextPage();\n const total = this.pdfiumModule.FPDFText_CountChars(textPagePtr);\n const glyphs = new Array(total);\n for (let i = 0; i < total; i++) {\n const g = this.readGlyphInfo(page, pageCtx.pagePtr, textPagePtr, i);\n if (g.isEmpty) {\n continue;\n }\n glyphs[i] = { ...g };\n }\n pageCtx.release();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageGlyphs", "End", doc.id);\n return PdfTaskHelper.resolve(glyphs);\n }\n readCharBox(page, pagePtr, textPagePtr, charIndex) {\n const topPtr = this.memoryManager.malloc(8);\n const leftPtr = this.memoryManager.malloc(8);\n const bottomPtr = this.memoryManager.malloc(8);\n const rightPtr = this.memoryManager.malloc(8);\n let x = 0;\n let y = 0;\n let width = 0;\n let height = 0;\n if (this.pdfiumModule.FPDFText_GetCharBox(\n textPagePtr,\n charIndex,\n leftPtr,\n rightPtr,\n bottomPtr,\n topPtr\n )) {\n const top = this.pdfiumModule.pdfium.getValue(topPtr, "double");\n const left = this.pdfiumModule.pdfium.getValue(leftPtr, "double");\n const bottom = this.pdfiumModule.pdfium.getValue(bottomPtr, "double");\n const right = this.pdfiumModule.pdfium.getValue(rightPtr, "double");\n const deviceXPtr = this.memoryManager.malloc(4);\n const deviceYPtr = this.memoryManager.malloc(4);\n this.pdfiumModule.FPDF_PageToDevice(\n pagePtr,\n 0,\n 0,\n page.size.width,\n page.size.height,\n 0,\n left,\n top,\n deviceXPtr,\n deviceYPtr\n );\n x = this.pdfiumModule.pdfium.getValue(deviceXPtr, "i32");\n y = this.pdfiumModule.pdfium.getValue(deviceYPtr, "i32");\n this.memoryManager.free(deviceXPtr);\n this.memoryManager.free(deviceYPtr);\n width = Math.ceil(Math.abs(right - left));\n height = Math.ceil(Math.abs(top - bottom));\n }\n this.memoryManager.free(topPtr);\n this.memoryManager.free(leftPtr);\n this.memoryManager.free(bottomPtr);\n this.memoryManager.free(rightPtr);\n return {\n origin: {\n x,\n y\n },\n size: {\n width,\n height\n }\n };\n }\n /**\n * Read page annotations\n *\n * @param doc - pdf document object\n * @param ctx - document context\n * @param page - page info\n * @returns annotations on the pdf page\n *\n * @private\n */\n readPageAnnotations(doc, ctx, page) {\n return ctx.borrowPage(page.index, (pageCtx) => {\n const annotationCount = this.pdfiumModule.FPDFPage_GetAnnotCount(pageCtx.pagePtr);\n const annotations = [];\n for (let i = 0; i < annotationCount; i++) {\n pageCtx.withAnnotation(i, (annotPtr) => {\n const anno = this.readPageAnnotation(doc, ctx.docPtr, page, annotPtr, pageCtx);\n if (anno) annotations.push(anno);\n });\n }\n return annotations;\n });\n }\n /**\n * Read page annotations without loading the page (raw approach)\n *\n * @param doc - pdf document object\n * @param ctx - document context\n * @param page - page info\n * @returns annotations on the pdf page\n *\n * @private\n */\n readPageAnnotationsRaw(doc, ctx, page) {\n const count = this.pdfiumModule.EPDFPage_GetAnnotCountRaw(ctx.docPtr, page.index);\n if (count <= 0) return [];\n const out = [];\n for (let i = 0; i < count; ++i) {\n const annotPtr = this.pdfiumModule.EPDFPage_GetAnnotRaw(ctx.docPtr, page.index, i);\n if (!annotPtr) continue;\n try {\n const anno = this.readPageAnnotation(doc, ctx.docPtr, page, annotPtr);\n if (anno) out.push(anno);\n } finally {\n this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);\n }\n }\n return out;\n }\n /**\n * Get page annotations (public API, returns Task)\n *\n * @param doc - pdf document\n * @param page - page info\n * @returns task with annotations on the pdf page\n *\n * @public\n */\n getPageAnnotationsRaw(doc, page) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageAnnotationsRaw", doc, page);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `GetPageAnnotationsRaw`,\n "Begin",\n `${doc.id}-${page.index}`\n );\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const out = this.readPageAnnotationsRaw(doc, ctx, page);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `GetPageAnnotationsRaw`,\n "End",\n `${doc.id}-${page.index}`\n );\n this.logger.debug(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "getPageAnnotationsRaw",\n `${doc.id}-${page.index}`,\n out\n );\n return PdfTaskHelper.resolve(out);\n }\n /**\n * Read pdf annotation from pdf document\n *\n * @param doc - pdf document object\n * @param docPtr - pointer to pdf document\n * @param page - page info\n * @param annotationPtr - pointer to pdf annotation\n * @param pageCtx - page context\n * @returns pdf annotation\n *\n * @private\n */\n readPageAnnotation(doc, docPtr, page, annotationPtr, pageCtx) {\n let index = this.getAnnotString(annotationPtr, "NM");\n if (!index || !isUuidV4(index)) {\n index = uuidV4();\n this.setAnnotString(annotationPtr, "NM", index);\n }\n const subType = this.pdfiumModule.FPDFAnnot_GetSubtype(\n annotationPtr\n );\n let annotation;\n switch (subType) {\n case PdfAnnotationSubtype.TEXT:\n {\n annotation = this.readPdfTextAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.FREETEXT:\n {\n annotation = this.readPdfFreeTextAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.LINK:\n {\n annotation = this.readPdfLinkAnno(doc, page, docPtr, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.WIDGET:\n if (pageCtx) {\n return this.readPdfWidgetAnno(doc, page, annotationPtr, pageCtx.getFormHandle(), index);\n }\n case PdfAnnotationSubtype.FILEATTACHMENT:\n {\n annotation = this.readPdfFileAttachmentAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.INK:\n {\n annotation = this.readPdfInkAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.POLYGON:\n {\n annotation = this.readPdfPolygonAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.POLYLINE:\n {\n annotation = this.readPdfPolylineAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.LINE:\n {\n annotation = this.readPdfLineAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.HIGHLIGHT:\n annotation = this.readPdfHighlightAnno(doc, page, annotationPtr, index);\n break;\n case PdfAnnotationSubtype.STAMP:\n {\n annotation = this.readPdfStampAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.SQUARE:\n {\n annotation = this.readPdfSquareAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.CIRCLE:\n {\n annotation = this.readPdfCircleAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.UNDERLINE:\n {\n annotation = this.readPdfUnderlineAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.SQUIGGLY:\n {\n annotation = this.readPdfSquigglyAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.STRIKEOUT:\n {\n annotation = this.readPdfStrikeOutAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.CARET:\n {\n annotation = this.readPdfCaretAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.REDACT:\n {\n annotation = this.readPdfRedactAnno(doc, page, annotationPtr, index);\n }\n break;\n default:\n {\n annotation = this.readPdfAnno(doc, page, subType, annotationPtr, index);\n }\n break;\n }\n if (annotation) {\n annotation = this.reverseRotateAnnotationOnLoad(annotation);\n const apModes = this.pdfiumModule.EPDFAnnot_GetAvailableAppearanceModes(annotationPtr);\n if (apModes) {\n annotation.appearanceModes = apModes;\n }\n }\n return annotation;\n }\n /**\n * On load, if a vertex-type annotation has rotation metadata in EPDFCustom,\n * reverse-rotate the PDF\'s physically rotated vertices by -rotation to recover\n * the unrotated vertices for runtime editing.\n */\n reverseRotateAnnotationOnLoad(annotation) {\n const rotation = annotation.rotation;\n const unrotatedRect = annotation.unrotatedRect;\n if (!rotation || rotation === 0 || !unrotatedRect) {\n return annotation;\n }\n const center = {\n x: unrotatedRect.origin.x + unrotatedRect.size.width / 2,\n y: unrotatedRect.origin.y + unrotatedRect.size.height / 2\n };\n switch (annotation.type) {\n case PdfAnnotationSubtype.INK: {\n const ink = annotation;\n const unrotatedInkList = ink.inkList.map((stroke) => ({\n points: stroke.points.map((p) => this.rotatePointForSave(p, center, -rotation))\n }));\n return { ...ink, inkList: unrotatedInkList };\n }\n case PdfAnnotationSubtype.LINE: {\n const line = annotation;\n return {\n ...line,\n linePoints: {\n start: this.rotatePointForSave(line.linePoints.start, center, -rotation),\n end: this.rotatePointForSave(line.linePoints.end, center, -rotation)\n }\n };\n }\n case PdfAnnotationSubtype.POLYGON: {\n const poly = annotation;\n return {\n ...poly,\n vertices: poly.vertices.map((v) => this.rotatePointForSave(v, center, -rotation))\n };\n }\n case PdfAnnotationSubtype.POLYLINE: {\n const polyline = annotation;\n return {\n ...polyline,\n vertices: polyline.vertices.map((v) => this.rotatePointForSave(v, center, -rotation))\n };\n }\n default:\n return annotation;\n }\n }\n /**\n * Return the colour stored directly in the annotation dictionary\'s `/C` entry.\n *\n * Most PDFs created by Acrobat, Microsoft Office, LaTeX, etc. include this entry.\n * When the key is absent (common in macOS Preview, Chrome, Drawboard) the call\n * fails and the function returns `undefined`.\n *\n * @param annotationPtr - pointer to an `FPDF_ANNOTATION`\n * @returns An RGBA tuple (0-255 channels) or `undefined` if no `/C` entry exists\n *\n * @private\n */\n readAnnotationColor(annotationPtr, colorType = PdfAnnotationColorType.Color) {\n const rPtr = this.memoryManager.malloc(4);\n const gPtr = this.memoryManager.malloc(4);\n const bPtr = this.memoryManager.malloc(4);\n const ok = this.pdfiumModule.EPDFAnnot_GetColor(annotationPtr, colorType, rPtr, gPtr, bPtr);\n let colour;\n if (ok) {\n colour = {\n red: this.pdfiumModule.pdfium.getValue(rPtr, "i32") & 255,\n green: this.pdfiumModule.pdfium.getValue(gPtr, "i32") & 255,\n blue: this.pdfiumModule.pdfium.getValue(bPtr, "i32") & 255\n };\n }\n this.memoryManager.free(rPtr);\n this.memoryManager.free(gPtr);\n this.memoryManager.free(bPtr);\n return colour;\n }\n /**\n * Get the fill/stroke colour annotation.\n *\n * @param annotationPtr - pointer to the annotation whose colour is being set\n * @param colorType - which colour to get (0 = fill, 1 = stroke)\n * @returns WebColor with hex color\n *\n * @private\n */\n getAnnotationColor(annotationPtr, colorType = PdfAnnotationColorType.Color) {\n const annotationColor = this.readAnnotationColor(annotationPtr, colorType);\n return annotationColor ? pdfColorToWebColor(annotationColor) : void 0;\n }\n /**\n * Set the fill/stroke colour for a **Highlight / Underline / StrikeOut / Squiggly** markup annotation.\n *\n * @param annotationPtr - pointer to the annotation whose colour is being set\n * @param webAlphaColor - WebAlphaColor with hex color and opacity (0-1)\n * @param shouldClearAP - whether to clear the /AP entry\n * @param which - which colour to set (0 = fill, 1 = stroke)\n * @returns `true` if the operation was successful\n *\n * @private\n */\n setAnnotationColor(annotationPtr, webColor, colorType = PdfAnnotationColorType.Color) {\n const pdfColor = webColorToPdfColor(webColor);\n return this.pdfiumModule.EPDFAnnot_SetColor(\n annotationPtr,\n colorType,\n pdfColor.red & 255,\n pdfColor.green & 255,\n pdfColor.blue & 255\n );\n }\n /**\n * Get the opacity of the annotation.\n *\n * @param annotationPtr - pointer to the annotation whose opacity is being set\n * @returns opacity (0-1)\n *\n * @private\n */\n getAnnotationOpacity(annotationPtr) {\n const opacityPtr = this.memoryManager.malloc(4);\n const ok = this.pdfiumModule.EPDFAnnot_GetOpacity(annotationPtr, opacityPtr);\n const opacity = ok ? this.pdfiumModule.pdfium.getValue(opacityPtr, "i32") : 255;\n this.memoryManager.free(opacityPtr);\n return pdfAlphaToWebOpacity(opacity);\n }\n /**\n * Set the opacity of the annotation.\n *\n * @param annotationPtr - pointer to the annotation whose opacity is being set\n * @param opacity - opacity (0-1)\n * @returns true on success\n *\n * @private\n */\n setAnnotationOpacity(annotationPtr, opacity) {\n const pdfOpacity = webOpacityToPdfAlpha(opacity);\n return this.pdfiumModule.EPDFAnnot_SetOpacity(annotationPtr, pdfOpacity & 255);\n }\n /**\n * Get the rotation angle (in degrees) from the annotation\'s /Rotate entry.\n * Returns 0 if no rotation is set or on error.\n *\n * @param annotationPtr - pointer to the annotation\n * @returns rotation in degrees (0 if not set)\n */\n getAnnotationRotation(annotationPtr) {\n const rotationPtr = this.memoryManager.malloc(4);\n const ok = this.pdfiumModule.EPDFAnnot_GetRotate(annotationPtr, rotationPtr);\n if (!ok) {\n this.memoryManager.free(rotationPtr);\n return 0;\n }\n const rotation = this.pdfiumModule.pdfium.getValue(rotationPtr, "float");\n this.memoryManager.free(rotationPtr);\n return rotation;\n }\n /**\n * Set the rotation angle (in degrees) on the annotation\'s /Rotate entry.\n * A value of 0 removes the /Rotate key.\n *\n * @param annotationPtr - pointer to the annotation\n * @param rotation - rotation in degrees (clockwise)\n * @returns true on success\n */\n setAnnotationRotation(annotationPtr, rotation) {\n return !!this.pdfiumModule.EPDFAnnot_SetRotate(annotationPtr, rotation);\n }\n /**\n * Get the EmbedPDF extended rotation (in degrees) from the annotation\'s\n * /EPDFRotate entry. Returns 0 if not set or on error.\n *\n * @param annotationPtr - pointer to the annotation\n * @returns rotation in degrees (0 if not set)\n */\n getAnnotExtendedRotation(annotationPtr) {\n const rotationPtr = this.memoryManager.malloc(4);\n const ok = this.pdfiumModule.EPDFAnnot_GetExtendedRotation(annotationPtr, rotationPtr);\n if (!ok) {\n this.memoryManager.free(rotationPtr);\n return 0;\n }\n const rotation = this.pdfiumModule.pdfium.getValue(rotationPtr, "float");\n this.memoryManager.free(rotationPtr);\n return rotation;\n }\n /**\n * Set the EmbedPDF extended rotation (in degrees) on the annotation\'s\n * /EPDFRotate entry. A value of 0 removes the key.\n *\n * @param annotationPtr - pointer to the annotation\n * @param rotation - rotation in degrees\n * @returns true on success\n */\n setAnnotExtendedRotation(annotationPtr, rotation) {\n return !!this.pdfiumModule.EPDFAnnot_SetExtendedRotation(annotationPtr, rotation);\n }\n /**\n * Read the EmbedPDF unrotated rect from the annotation\'s /EPDFUnrotatedRect\n * entry. Returns the raw page-space rect (same format as `readPageAnnoRect`)\n * or null if not set.\n *\n * @param annotationPtr - pointer to the annotation\n * @returns raw `{ left, top, right, bottom }` in page coords, or null\n */\n readAnnotUnrotatedRect(annotationPtr) {\n const rectPtr = this.memoryManager.malloc(4 * 4);\n const ok = this.pdfiumModule.EPDFAnnot_GetUnrotatedRect(annotationPtr, rectPtr);\n if (!ok) {\n this.memoryManager.free(rectPtr);\n return null;\n }\n const left = this.pdfiumModule.pdfium.getValue(rectPtr, "float");\n const top = this.pdfiumModule.pdfium.getValue(rectPtr + 4, "float");\n const right = this.pdfiumModule.pdfium.getValue(rectPtr + 8, "float");\n const bottom = this.pdfiumModule.pdfium.getValue(rectPtr + 12, "float");\n this.memoryManager.free(rectPtr);\n if (left === 0 && top === 0 && right === 0 && bottom === 0) {\n return null;\n }\n return { left, top, right, bottom };\n }\n /**\n * Write the EmbedPDF unrotated rect (/EPDFUnrotatedRect) for an annotation.\n * Accepts a device-space `Rect` and converts to page coordinates internally,\n * following the same pattern as `setPageAnnoRect`.\n *\n * @param doc - pdf document object\n * @param page - pdf page object\n * @param annotPtr - pointer to the annotation\n * @param rect - device-space rect to store as the unrotated rect\n * @returns true on success\n */\n setAnnotUnrotatedRect(doc, page, annotPtr, rect) {\n const x0d = Math.floor(rect.origin.x);\n const y0d = Math.floor(rect.origin.y);\n const x1d = Math.floor(rect.origin.x + rect.size.width);\n const y1d = Math.floor(rect.origin.y + rect.size.height);\n const TL = this.convertDevicePointToPagePoint(doc, page, { x: x0d, y: y0d });\n const TR = this.convertDevicePointToPagePoint(doc, page, { x: x1d, y: y0d });\n const BR = this.convertDevicePointToPagePoint(doc, page, { x: x1d, y: y1d });\n const BL = this.convertDevicePointToPagePoint(doc, page, { x: x0d, y: y1d });\n let left = Math.min(TL.x, TR.x, BR.x, BL.x);\n let right = Math.max(TL.x, TR.x, BR.x, BL.x);\n let bottom = Math.min(TL.y, TR.y, BR.y, BL.y);\n let top = Math.max(TL.y, TR.y, BR.y, BL.y);\n if (left > right) [left, right] = [right, left];\n if (bottom > top) [bottom, top] = [top, bottom];\n const ptr = this.memoryManager.malloc(16);\n const pdf = this.pdfiumModule.pdfium;\n pdf.setValue(ptr + 0, left, "float");\n pdf.setValue(ptr + 4, top, "float");\n pdf.setValue(ptr + 8, right, "float");\n pdf.setValue(ptr + 12, bottom, "float");\n const ok = this.pdfiumModule.EPDFAnnot_SetUnrotatedRect(annotPtr, ptr);\n this.memoryManager.free(ptr);\n return !!ok;\n }\n /**\n * Fetch the `/Q` text-alignment value from a **FreeText** annotation.\n *\n * @param annotationPtr pointer returned by `FPDFPage_GetAnnot`\n * @returns `PdfTextAlignment`\n */\n getAnnotationTextAlignment(annotationPtr) {\n return this.pdfiumModule.EPDFAnnot_GetTextAlignment(annotationPtr);\n }\n /**\n * Write the `/Q` text-alignment value into a **FreeText** annotation\n * and clear the existing appearance stream so it can be regenerated.\n *\n * @param annotationPtr pointer returned by `FPDFPage_GetAnnot`\n * @param alignment `PdfTextAlignment`\n * @returns `true` on success\n */\n setAnnotationTextAlignment(annotationPtr, alignment) {\n return !!this.pdfiumModule.EPDFAnnot_SetTextAlignment(annotationPtr, alignment);\n }\n /**\n * Fetch the `/EPDF:VerticalAlignment` vertical-alignment value from a **FreeText** annotation.\n *\n * @param annotationPtr pointer returned by `FPDFPage_GetAnnot`\n * @returns `PdfVerticalAlignment`\n */\n getAnnotationVerticalAlignment(annotationPtr) {\n return this.pdfiumModule.EPDFAnnot_GetVerticalAlignment(annotationPtr);\n }\n /**\n * Write the `/EPDF:VerticalAlignment` vertical-alignment value into a **FreeText** annotation\n * and clear the existing appearance stream so it can be regenerated.\n *\n * @param annotationPtr pointer returned by `FPDFPage_GetAnnot`\n * @param alignment `PdfVerticalAlignment`\n * @returns `true` on success\n */\n setAnnotationVerticalAlignment(annotationPtr, alignment) {\n return !!this.pdfiumModule.EPDFAnnot_SetVerticalAlignment(annotationPtr, alignment);\n }\n /**\n * Get the overlay text from a Redact annotation.\n *\n * @param annotationPtr pointer returned by `FPDFPage_GetAnnot`\n * @returns overlay text string or `undefined` if not set\n *\n * @private\n */\n getOverlayText(annotationPtr) {\n const len = this.pdfiumModule.EPDFAnnot_GetOverlayText(annotationPtr, 0, 0);\n if (len === 0) return void 0;\n const bytes = (len + 1) * 2;\n const ptr = this.memoryManager.malloc(bytes);\n this.pdfiumModule.EPDFAnnot_GetOverlayText(annotationPtr, ptr, bytes);\n const value = this.pdfiumModule.pdfium.UTF16ToString(ptr);\n this.memoryManager.free(ptr);\n return value || void 0;\n }\n /**\n * Set the overlay text on a Redact annotation.\n *\n * @param annotationPtr pointer returned by `FPDFPage_GetAnnot`\n * @param text overlay text to set, or undefined/empty to clear\n * @returns `true` on success\n *\n * @private\n */\n setOverlayText(annotationPtr, text) {\n if (!text) {\n return this.pdfiumModule.EPDFAnnot_SetOverlayText(annotationPtr, 0);\n }\n return this.withWString(text, (wPtr) => {\n return this.pdfiumModule.EPDFAnnot_SetOverlayText(annotationPtr, wPtr);\n });\n }\n /**\n * Get whether overlay text repeats in a Redact annotation.\n *\n * @param annotationPtr pointer returned by `FPDFPage_GetAnnot`\n * @returns `true` if overlay text repeats\n *\n * @private\n */\n getOverlayTextRepeat(annotationPtr) {\n return this.pdfiumModule.EPDFAnnot_GetOverlayTextRepeat(annotationPtr);\n }\n /**\n * Set whether overlay text repeats in a Redact annotation.\n *\n * @param annotationPtr pointer returned by `FPDFPage_GetAnnot`\n * @param repeat whether overlay text should repeat\n * @returns `true` on success\n *\n * @private\n */\n setOverlayTextRepeat(annotationPtr, repeat) {\n return this.pdfiumModule.EPDFAnnot_SetOverlayTextRepeat(annotationPtr, repeat);\n }\n /**\n * Return the **default appearance** (font, size, colour) declared in the\n * `/DA` string of a **FreeText** annotation.\n *\n * @param annotationPtr pointer to `FPDF_ANNOTATION`\n * @returns `{ font, fontSize, color }` or `undefined` when PDFium returns false\n *\n * NOTE – `font` is the raw `FPDF_STANDARD_FONT` enum value that PDFium uses\n * (same range as the C API: 0 = Courier, 12 = ZapfDingbats, …).\n */\n getAnnotationDefaultAppearance(annotationPtr) {\n const fontPtr = this.memoryManager.malloc(4);\n const sizePtr = this.memoryManager.malloc(4);\n const rPtr = this.memoryManager.malloc(4);\n const gPtr = this.memoryManager.malloc(4);\n const bPtr = this.memoryManager.malloc(4);\n const ok = !!this.pdfiumModule.EPDFAnnot_GetDefaultAppearance(\n annotationPtr,\n fontPtr,\n sizePtr,\n rPtr,\n gPtr,\n bPtr\n );\n if (!ok) {\n [fontPtr, sizePtr, rPtr, gPtr, bPtr].forEach((p) => this.memoryManager.free(p));\n return;\n }\n const pdf = this.pdfiumModule.pdfium;\n const font = pdf.getValue(fontPtr, "i32");\n const fontSize = pdf.getValue(sizePtr, "float");\n const red = pdf.getValue(rPtr, "i32") & 255;\n const green = pdf.getValue(gPtr, "i32") & 255;\n const blue = pdf.getValue(bPtr, "i32") & 255;\n [fontPtr, sizePtr, rPtr, gPtr, bPtr].forEach((p) => this.memoryManager.free(p));\n return {\n fontFamily: font,\n fontSize,\n fontColor: pdfColorToWebColor({ red, green, blue })\n };\n }\n /**\n * Write a **default appearance** (`/DA`) into a FreeText annotation.\n *\n * @param annotationPtr pointer to `FPDF_ANNOTATION`\n * @param font `FPDF_STANDARD_FONT` enum value\n * @param fontSize size in points (≥ 0)\n * @param color CSS-style `#rrggbb` string (alpha ignored)\n * @returns `true` on success\n */\n setAnnotationDefaultAppearance(annotationPtr, font, fontSize, color) {\n const resolvedFont = font === PdfStandardFont.Unknown ? PdfStandardFont.Helvetica : font;\n const { red, green, blue } = webColorToPdfColor(color);\n return !!this.pdfiumModule.EPDFAnnot_SetDefaultAppearance(\n annotationPtr,\n resolvedFont,\n fontSize,\n red & 255,\n green & 255,\n blue & 255\n );\n }\n /**\n * Border‐style + width helper\n *\n * Tries the new PDFium helper `EPDFAnnot_GetBorderStyle()` (patch series\n * 9 July 2025).\n *\n * @param annotationPtr pointer to an `FPDF_ANNOTATION`\n * @returns `{ ok, style, width }`\n * • `ok` – `true` when the call succeeded\n * • `style` – `PdfAnnotationBorderStyle` enum\n * • `width` – stroke-width in points (defaults to 0 pt)\n */\n getBorderStyle(annotationPtr) {\n const widthPtr = this.memoryManager.malloc(4);\n let width = 0;\n let style = PdfAnnotationBorderStyle.UNKNOWN;\n let ok = false;\n style = this.pdfiumModule.EPDFAnnot_GetBorderStyle(annotationPtr, widthPtr);\n width = this.pdfiumModule.pdfium.getValue(widthPtr, "float");\n ok = style !== PdfAnnotationBorderStyle.UNKNOWN;\n this.memoryManager.free(widthPtr);\n return { ok, style, width };\n }\n setBorderStyle(annotationPtr, style, width) {\n return this.pdfiumModule.EPDFAnnot_SetBorderStyle(annotationPtr, style, width);\n }\n /**\n * Get the icon of the annotation\n *\n * @param annotationPtr - pointer to an `FPDF_ANNOTATION`\n * @returns `PdfAnnotationIcon`\n */\n getAnnotationIcon(annotationPtr) {\n return this.pdfiumModule.EPDFAnnot_GetIcon(annotationPtr);\n }\n /**\n * Set the icon of the annotation\n *\n * @param annotationPtr - pointer to an `FPDF_ANNOTATION`\n * @param icon - `PdfAnnotationIcon`\n * @returns `true` on success\n */\n setAnnotationIcon(annotationPtr, icon) {\n return this.pdfiumModule.EPDFAnnot_SetIcon(annotationPtr, icon);\n }\n /**\n * Get the reply type of the annotation (RT property per ISO 32000-2)\n *\n * @param annotationPtr - pointer to an `FPDF_ANNOTATION`\n * @returns `PdfAnnotationReplyType`\n */\n getReplyType(annotationPtr) {\n return this.pdfiumModule.EPDFAnnot_GetReplyType(annotationPtr);\n }\n /**\n * Set the reply type of the annotation (RT property per ISO 32000-2)\n *\n * @param annotationPtr - pointer to an `FPDF_ANNOTATION`\n * @param replyType - `PdfAnnotationReplyType`\n * @returns `true` on success\n */\n setReplyType(annotationPtr, replyType) {\n return this.pdfiumModule.EPDFAnnot_SetReplyType(\n annotationPtr,\n replyType ?? PdfAnnotationReplyType.Unknown\n );\n }\n /**\n * Border-effect (“cloudy”) helper\n *\n * Calls the new PDFium function `EPDFAnnot_GetBorderEffect()` (July 2025).\n *\n * @param annotationPtr pointer to an `FPDF_ANNOTATION`\n * @returns `{ ok, intensity }`\n * • `ok` – `true` when the annotation *does* have a\n * valid cloudy-border effect\n * • `intensity` – radius/intensity value (0 when `ok` is false)\n */\n getBorderEffect(annotationPtr) {\n const intensityPtr = this.memoryManager.malloc(4);\n const ok = !!this.pdfiumModule.EPDFAnnot_GetBorderEffect(annotationPtr, intensityPtr);\n const intensity = ok ? this.pdfiumModule.pdfium.getValue(intensityPtr, "float") : 0;\n this.memoryManager.free(intensityPtr);\n return { ok, intensity };\n }\n /**\n * Rectangle-differences helper ( /RD array on Square / Circle annots )\n *\n * Calls `EPDFAnnot_GetRectangleDifferences()` introduced in July 2025.\n *\n * @param annotationPtr pointer to an `FPDF_ANNOTATION`\n * @returns `{ ok, left, top, right, bottom }`\n * • `ok` – `true` when the annotation *has* an /RD entry\n * • the four floats are 0 when `ok` is false\n */\n getRectangleDifferences(annotationPtr) {\n const lPtr = this.memoryManager.malloc(4);\n const tPtr = this.memoryManager.malloc(4);\n const rPtr = this.memoryManager.malloc(4);\n const bPtr = this.memoryManager.malloc(4);\n const ok = !!this.pdfiumModule.EPDFAnnot_GetRectangleDifferences(\n annotationPtr,\n lPtr,\n tPtr,\n rPtr,\n bPtr\n );\n const pdf = this.pdfiumModule.pdfium;\n const left = pdf.getValue(lPtr, "float");\n const top = pdf.getValue(tPtr, "float");\n const right = pdf.getValue(rPtr, "float");\n const bottom = pdf.getValue(bPtr, "float");\n this.memoryManager.free(lPtr);\n this.memoryManager.free(tPtr);\n this.memoryManager.free(rPtr);\n this.memoryManager.free(bPtr);\n return { ok, left, top, right, bottom };\n }\n /**\n * Sets the /RD array on an annotation.\n *\n * @param annotationPtr pointer to an `FPDF_ANNOTATION`\n * @param rd the four inset values, or `undefined` to clear\n * @returns `true` on success\n */\n setRectangleDifferences(annotationPtr, rd) {\n if (!rd) {\n return this.pdfiumModule.EPDFAnnot_ClearRectangleDifferences(annotationPtr);\n }\n return this.pdfiumModule.EPDFAnnot_SetRectangleDifferences(\n annotationPtr,\n rd.left,\n rd.top,\n rd.right,\n rd.bottom\n );\n }\n /**\n * Get the date of the annotation\n *\n * @param annotationPtr - pointer to an `FPDF_ANNOTATION`\n * @param key - \'M\' for modified date, \'CreationDate\' for creation date\n * @returns `Date` or `undefined` when PDFium can\'t read the date\n */\n getAnnotationDate(annotationPtr, key) {\n const raw = this.getAnnotString(annotationPtr, key);\n return raw ? pdfDateToDate(raw) : void 0;\n }\n /**\n * Set the date of the annotation\n *\n * @param annotationPtr - pointer to an `FPDF_ANNOTATION`\n * @param key - \'M\' for modified date, \'CreationDate\' for creation date\n * @param date - `Date` to set\n * @returns `true` on success\n */\n setAnnotationDate(annotationPtr, key, date) {\n const raw = dateToPdfDate(date);\n return this.setAnnotString(annotationPtr, key, raw);\n }\n /**\n * Get the date of the attachment\n *\n * @param attachmentPtr - pointer to an `FPDF_ATTACHMENT`\n * @param key - \'ModDate\' for modified date, \'CreationDate\' for creation date\n * @returns `Date` or `undefined` when PDFium can\'t read the date\n */\n getAttachmentDate(attachmentPtr, key) {\n const raw = this.getAttachmentString(attachmentPtr, key);\n return raw ? pdfDateToDate(raw) : void 0;\n }\n /**\n * Set the date of the attachment\n *\n * @param attachmentPtr - pointer to an `FPDF_ATTACHMENT`\n * @param key - \'ModDate\' for modified date, \'CreationDate\' for creation date\n * @param date - `Date` to set\n * @returns `true` on success\n */\n setAttachmentDate(attachmentPtr, key, date) {\n const raw = dateToPdfDate(date);\n return this.setAttachmentString(attachmentPtr, key, raw);\n }\n /**\n * Dash-pattern helper ( /BS → /D array, dashed borders only )\n *\n * Uses the two new PDFium helpers:\n * • `EPDFAnnot_GetBorderDashPatternCount`\n * • `EPDFAnnot_GetBorderDashPattern`\n *\n * @param annotationPtr pointer to an `FPDF_ANNOTATION`\n * @returns `{ ok, pattern }`\n * • `ok` – `true` when the annot is dashed *and* the array\n * was retrieved successfully\n * • `pattern` – numeric array of dash/space lengths (empty when `ok` is false)\n */\n getBorderDashPattern(annotationPtr) {\n const count = this.pdfiumModule.EPDFAnnot_GetBorderDashPatternCount(annotationPtr);\n if (count === 0) {\n return { ok: false, pattern: [] };\n }\n const arrPtr = this.memoryManager.malloc(4 * count);\n const okNative = !!this.pdfiumModule.EPDFAnnot_GetBorderDashPattern(\n annotationPtr,\n arrPtr,\n count\n );\n const pattern = [];\n if (okNative) {\n const pdf = this.pdfiumModule.pdfium;\n for (let i = 0; i < count; i++) {\n pattern.push(pdf.getValue(arrPtr + 4 * i, "float"));\n }\n }\n this.memoryManager.free(arrPtr);\n return { ok: okNative, pattern };\n }\n /**\n * Write the /BS /D dash pattern array for an annotation border.\n *\n * @param annotationPtr Pointer to FPDF_ANNOTATION\n * @param pattern Array of dash/space lengths in *points* (e.g. [3, 2])\n * Empty array clears the pattern (solid line).\n * @returns true on success\n *\n * @private\n */\n setBorderDashPattern(annotationPtr, pattern) {\n if (!pattern || pattern.length === 0) {\n return this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(annotationPtr, 0, 0);\n }\n const clean = pattern.map((n) => Number.isFinite(n) && n > 0 ? n : 0).filter((n) => n > 0);\n if (clean.length === 0) {\n return this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(annotationPtr, 0, 0);\n }\n const bytes = 4 * clean.length;\n const bufPtr = this.memoryManager.malloc(bytes);\n for (let i = 0; i < clean.length; i++) {\n this.pdfiumModule.pdfium.setValue(bufPtr + 4 * i, clean[i], "float");\n }\n const ok = !!this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(\n annotationPtr,\n bufPtr,\n clean.length\n );\n this.memoryManager.free(bufPtr);\n return ok;\n }\n /**\n * Return the `/LE` array (start/end line-ending styles) for a LINE / POLYLINE annot.\n *\n * @param annotationPtr - pointer to an `FPDF_ANNOTATION`\n * @returns `{ start, end }` or `undefined` when PDFium can\'t read them\n *\n * @private\n */\n getLineEndings(annotationPtr) {\n const startPtr = this.memoryManager.malloc(4);\n const endPtr = this.memoryManager.malloc(4);\n const ok = !!this.pdfiumModule.EPDFAnnot_GetLineEndings(annotationPtr, startPtr, endPtr);\n if (!ok) {\n this.memoryManager.free(startPtr);\n this.memoryManager.free(endPtr);\n return void 0;\n }\n const start = this.pdfiumModule.pdfium.getValue(startPtr, "i32");\n const end = this.pdfiumModule.pdfium.getValue(endPtr, "i32");\n this.memoryManager.free(startPtr);\n this.memoryManager.free(endPtr);\n return { start, end };\n }\n /**\n * Write the `/LE` array (start/end line-ending styles) for a LINE / POLYLINE annot.\n * @param annotationPtr - pointer to an `FPDF_ANNOTATION`\n * @param start - start line ending style\n * @param end - end line ending style\n * @returns `true` on success\n */\n setLineEndings(annotationPtr, start, end) {\n return !!this.pdfiumModule.EPDFAnnot_SetLineEndings(annotationPtr, start, end);\n }\n /**\n * Get the start and end points of a LINE / POLYLINE annot.\n * @param doc - pdf document object\n * @param annotationPtr - pointer to an `FPDF_ANNOTATION`\n * @param page - logical page info object (`PdfPageObject`)\n * @returns `{ start, end }` or `undefined` when PDFium can\'t read them\n */\n getLinePoints(doc, page, annotationPtr) {\n const startPtr = this.memoryManager.malloc(8);\n const endPtr = this.memoryManager.malloc(8);\n const ok = this.pdfiumModule.FPDFAnnot_GetLine(annotationPtr, startPtr, endPtr);\n if (!ok) {\n this.memoryManager.free(startPtr);\n this.memoryManager.free(endPtr);\n return void 0;\n }\n const pdf = this.pdfiumModule.pdfium;\n const sx = pdf.getValue(startPtr + 0, "float");\n const sy = pdf.getValue(startPtr + 4, "float");\n const ex = pdf.getValue(endPtr + 0, "float");\n const ey = pdf.getValue(endPtr + 4, "float");\n this.memoryManager.free(startPtr);\n this.memoryManager.free(endPtr);\n const start = this.convertPagePointToDevicePoint(doc, page, { x: sx, y: sy });\n const end = this.convertPagePointToDevicePoint(doc, page, { x: ex, y: ey });\n return { start, end };\n }\n /**\n * Set the two end‑points of a **Line** annotation\n * by writing a new /L array `[ x1 y1 x2 y2 ]`.\n * @param doc - pdf document object\n * @param page - logical page info object (`PdfPageObject`)\n * @param annotPtr - pointer to the annotation whose line points are needed\n * @param start - start point\n * @param end - end point\n * @returns true on success\n */\n setLinePoints(doc, page, annotPtr, start, end) {\n const p1 = this.convertDevicePointToPagePoint(doc, page, start);\n const p2 = this.convertDevicePointToPagePoint(doc, page, end);\n if (!p1 || !p2) return false;\n const buf = this.memoryManager.malloc(16);\n const pdf = this.pdfiumModule.pdfium;\n pdf.setValue(buf + 0, p1.x, "float");\n pdf.setValue(buf + 4, p1.y, "float");\n pdf.setValue(buf + 8, p2.x, "float");\n pdf.setValue(buf + 12, p2.y, "float");\n const ok = this.pdfiumModule.EPDFAnnot_SetLine(annotPtr, buf, buf + 8);\n this.memoryManager.free(buf);\n return !!ok;\n }\n /**\n * Read `/QuadPoints` from any annotation and convert each quadrilateral to\n * device-space coordinates.\n *\n * The four points are returned in natural reading order:\n * `p1 → p2` (top edge) and `p4 → p3` (bottom edge).\n * This preserves the true shape for rotated / skewed text, whereas callers\n * that only need axis-aligned boxes can collapse each quad themselves.\n *\n * @param doc - pdf document object\n * @param page - logical page info object (`PdfPageObject`)\n * @param annotationPtr - pointer to the annotation whose quads are needed\n * @returns Array of `Rect` objects (`[]` if the annotation has no quads)\n *\n * @private\n */\n getQuadPointsAnno(doc, page, annotationPtr) {\n const quadCount = this.pdfiumModule.FPDFAnnot_CountAttachmentPoints(annotationPtr);\n if (quadCount === 0) return [];\n const FS_QUADPOINTSF_SIZE = 8 * 4;\n const quads = [];\n for (let qi = 0; qi < quadCount; qi++) {\n const quadPtr = this.memoryManager.malloc(FS_QUADPOINTSF_SIZE);\n const ok = this.pdfiumModule.FPDFAnnot_GetAttachmentPoints(annotationPtr, qi, quadPtr);\n if (ok) {\n const xs = [];\n const ys = [];\n for (let i = 0; i < 4; i++) {\n const base = quadPtr + i * 8;\n xs.push(this.pdfiumModule.pdfium.getValue(base, "float"));\n ys.push(this.pdfiumModule.pdfium.getValue(base + 4, "float"));\n }\n const p1 = this.convertPagePointToDevicePoint(doc, page, { x: xs[0], y: ys[0] });\n const p2 = this.convertPagePointToDevicePoint(doc, page, { x: xs[1], y: ys[1] });\n const p3 = this.convertPagePointToDevicePoint(doc, page, { x: xs[2], y: ys[2] });\n const p4 = this.convertPagePointToDevicePoint(doc, page, { x: xs[3], y: ys[3] });\n quads.push({ p1, p2, p3, p4 });\n }\n this.memoryManager.free(quadPtr);\n }\n return quads.map(quadToRect);\n }\n /**\n * Set the quadrilaterals for a **Highlight / Underline / StrikeOut / Squiggly** markup annotation.\n *\n * @param doc - pdf document object\n * @param page - logical page info object (`PdfPageObject`)\n * @param annotationPtr - pointer to the annotation whose quads are needed\n * @param rects - array of `Rect` objects (`[]` if the annotation has no quads)\n * @returns `true` if the operation was successful\n *\n * @private\n */\n syncQuadPointsAnno(doc, page, annotPtr, rects) {\n const FS_QUADPOINTSF_SIZE = 8 * 4;\n const pdf = this.pdfiumModule.pdfium;\n const count = this.pdfiumModule.FPDFAnnot_CountAttachmentPoints(annotPtr);\n const buf = this.memoryManager.malloc(FS_QUADPOINTSF_SIZE);\n const writeQuad = (r) => {\n const q = rectToQuad(r);\n const p1 = this.convertDevicePointToPagePoint(doc, page, q.p1);\n const p2 = this.convertDevicePointToPagePoint(doc, page, q.p2);\n const p3 = this.convertDevicePointToPagePoint(doc, page, q.p3);\n const p4 = this.convertDevicePointToPagePoint(doc, page, q.p4);\n pdf.setValue(buf + 0, p1.x, "float");\n pdf.setValue(buf + 4, p1.y, "float");\n pdf.setValue(buf + 8, p2.x, "float");\n pdf.setValue(buf + 12, p2.y, "float");\n pdf.setValue(buf + 16, p4.x, "float");\n pdf.setValue(buf + 20, p4.y, "float");\n pdf.setValue(buf + 24, p3.x, "float");\n pdf.setValue(buf + 28, p3.y, "float");\n };\n const min = Math.min(count, rects.length);\n for (let i = 0; i < min; i++) {\n writeQuad(rects[i]);\n if (!this.pdfiumModule.FPDFAnnot_SetAttachmentPoints(annotPtr, i, buf)) {\n this.memoryManager.free(buf);\n return false;\n }\n }\n for (let i = count; i < rects.length; i++) {\n writeQuad(rects[i]);\n if (!this.pdfiumModule.FPDFAnnot_AppendAttachmentPoints(annotPtr, buf)) {\n this.memoryManager.free(buf);\n return false;\n }\n }\n this.memoryManager.free(buf);\n return true;\n }\n /**\n * Redact text that intersects ANY of the provided **quads** (device-space).\n * Returns `true` if the page changed. Always regenerates the page stream.\n */\n redactTextInRects(doc, page, rects, options) {\n const { recurseForms = true, drawBlackBoxes = false } = options ?? {};\n this.logger.debug(\n "PDFiumEngine",\n "Engine",\n "redactTextInQuads",\n doc.id,\n page.index,\n rects.length\n );\n const label = "RedactTextInQuads";\n this.logger.perf("PDFiumEngine", "Engine", label, "Begin", `${doc.id}-${page.index}`);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf("PDFiumEngine", "Engine", label, "End", `${doc.id}-${page.index}`);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const clean = (rects ?? []).filter(\n (r) => {\n var _a, _b, _c, _d;\n return r && Number.isFinite((_a = r.origin) == null ? void 0 : _a.x) && Number.isFinite((_b = r.origin) == null ? void 0 : _b.y) && Number.isFinite((_c = r.size) == null ? void 0 : _c.width) && Number.isFinite((_d = r.size) == null ? void 0 : _d.height) && r.size.width > 0 && r.size.height > 0;\n }\n );\n if (clean.length === 0) {\n this.logger.perf("PDFiumEngine", "Engine", label, "End", `${doc.id}-${page.index}`);\n return PdfTaskHelper.resolve(false);\n }\n const pageCtx = ctx.acquirePage(page.index);\n const { ptr, count } = this.allocFSQuadsBufferFromRects(doc, page, clean);\n let ok = false;\n try {\n ok = !!this.pdfiumModule.EPDFText_RedactInQuads(\n pageCtx.pagePtr,\n ptr,\n count,\n recurseForms ? true : false,\n false\n );\n } finally {\n this.memoryManager.free(ptr);\n }\n if (ok) {\n ok = !!this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);\n }\n pageCtx.disposeImmediate();\n this.logger.perf("PDFiumEngine", "Engine", label, "End", `${doc.id}-${page.index}`);\n return PdfTaskHelper.resolve(!!ok);\n }\n /**\n * Apply a single redaction annotation, permanently removing content underneath\n * and flattening the RO (Redact Overlay) appearance stream if present.\n * The annotation is removed after successful application.\n *\n * @param doc - document object\n * @param page - page object\n * @param annotation - the redact annotation to apply\n * @returns true if successful\n */\n applyRedaction(doc, page, annotation) {\n this.logger.debug(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "applyRedaction",\n doc.id,\n page.index,\n annotation.id\n );\n const label = "ApplyRedaction";\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", `${doc.id}-${page.index}`);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", `${doc.id}-${page.index}`);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const annotPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);\n if (!annotPtr) {\n pageCtx.release();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", `${doc.id}-${page.index}`);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.NotFound,\n message: "annotation not found"\n });\n }\n const ok = this.pdfiumModule.EPDFAnnot_ApplyRedaction(pageCtx.pagePtr, annotPtr);\n this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);\n if (ok) {\n this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);\n }\n pageCtx.disposeImmediate();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", `${doc.id}-${page.index}`);\n return PdfTaskHelper.resolve(!!ok);\n }\n /**\n * Apply all redaction annotations on a page, permanently removing content\n * underneath each one and flattening RO streams if present.\n * All redact annotations are removed after successful application.\n *\n * @param doc - document object\n * @param page - page object\n * @returns true if any redactions were applied\n */\n applyAllRedactions(doc, page) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "applyAllRedactions", doc.id, page.index);\n const label = "ApplyAllRedactions";\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", `${doc.id}-${page.index}`);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", `${doc.id}-${page.index}`);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const ok = this.pdfiumModule.EPDFPage_ApplyRedactions(pageCtx.pagePtr);\n if (ok) {\n this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);\n }\n pageCtx.disposeImmediate();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", `${doc.id}-${page.index}`);\n return PdfTaskHelper.resolve(!!ok);\n }\n /**\n * Flatten an annotation\'s appearance (AP/N) to page content.\n * The annotation\'s visual appearance becomes part of the page itself.\n * The annotation is automatically removed after flattening.\n *\n * @param doc - document object\n * @param page - page object\n * @param annotation - the annotation to flatten\n * @returns true if successful\n */\n flattenAnnotation(doc, page, annotation) {\n this.logger.debug(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "flattenAnnotation",\n doc.id,\n page.index,\n annotation.id\n );\n const label = "FlattenAnnotation";\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", `${doc.id}-${page.index}`);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", `${doc.id}-${page.index}`);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const annotPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);\n if (!annotPtr) {\n pageCtx.release();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", `${doc.id}-${page.index}`);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.NotFound,\n message: "annotation not found"\n });\n }\n const ok = this.pdfiumModule.EPDFAnnot_Flatten(pageCtx.pagePtr, annotPtr);\n this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);\n if (ok) {\n this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);\n }\n pageCtx.disposeImmediate();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", `${doc.id}-${page.index}`);\n return PdfTaskHelper.resolve(!!ok);\n }\n /** Pack device-space Rects into an FS_QUADPOINTSF[] buffer (page space). */\n allocFSQuadsBufferFromRects(doc, page, rects) {\n const STRIDE = 32;\n const count = rects.length;\n const ptr = this.memoryManager.malloc(STRIDE * count);\n const pdf = this.pdfiumModule.pdfium;\n for (let i = 0; i < count; i++) {\n const r = rects[i];\n const q = rectToQuad(r);\n const p1 = this.convertDevicePointToPagePoint(doc, page, q.p1);\n const p2 = this.convertDevicePointToPagePoint(doc, page, q.p2);\n const p3 = this.convertDevicePointToPagePoint(doc, page, q.p3);\n const p4 = this.convertDevicePointToPagePoint(doc, page, q.p4);\n const base = ptr + i * STRIDE;\n pdf.setValue(base + 0, p1.x, "float");\n pdf.setValue(base + 4, p1.y, "float");\n pdf.setValue(base + 8, p2.x, "float");\n pdf.setValue(base + 12, p2.y, "float");\n pdf.setValue(base + 16, p4.x, "float");\n pdf.setValue(base + 20, p4.y, "float");\n pdf.setValue(base + 24, p3.x, "float");\n pdf.setValue(base + 28, p3.y, "float");\n }\n return { ptr, count };\n }\n /**\n * Read ink list from annotation\n * @param doc - pdf document object\n * @param page - logical page info object (`PdfPageObject`)\n * @param pagePtr - pointer to the page\n * @param annotationPtr - pointer to the annotation whose ink list is needed\n * @returns ink list\n */\n getInkList(doc, page, annotationPtr) {\n const inkList = [];\n const pathCount = this.pdfiumModule.FPDFAnnot_GetInkListCount(annotationPtr);\n if (pathCount <= 0) return inkList;\n const pdf = this.pdfiumModule.pdfium;\n const POINT_STRIDE = 8;\n for (let i = 0; i < pathCount; i++) {\n const points = [];\n const n = this.pdfiumModule.FPDFAnnot_GetInkListPath(annotationPtr, i, 0, 0);\n if (n > 0) {\n const buf = this.memoryManager.malloc(n * POINT_STRIDE);\n this.pdfiumModule.FPDFAnnot_GetInkListPath(annotationPtr, i, buf, n);\n for (let j = 0; j < n; j++) {\n const base = buf + j * POINT_STRIDE;\n const px = pdf.getValue(base + 0, "float");\n const py = pdf.getValue(base + 4, "float");\n const d = this.convertPagePointToDevicePoint(doc, page, { x: px, y: py });\n points.push({ x: d.x, y: d.y });\n }\n this.memoryManager.free(buf);\n }\n inkList.push({ points });\n }\n return inkList;\n }\n /**\n * Add ink list to annotation\n * @param doc - pdf document object\n * @param page - logical page info object (`PdfPageObject`)\n * @param pagePtr - pointer to the page\n * @param annotationPtr - pointer to the annotation whose ink list is needed\n * @param inkList - ink list array of `PdfInkListObject`\n * @returns `true` if the operation was successful\n */\n setInkList(doc, page, annotationPtr, inkList) {\n const pdf = this.pdfiumModule.pdfium;\n const POINT_STRIDE = 8;\n for (const stroke of inkList) {\n const n = stroke.points.length;\n if (n === 0) continue;\n const buf = this.memoryManager.malloc(n * POINT_STRIDE);\n for (let i = 0; i < n; i++) {\n const pDev = stroke.points[i];\n const pPage = this.convertDevicePointToPagePoint(doc, page, pDev);\n pdf.setValue(buf + i * POINT_STRIDE + 0, pPage.x, "float");\n pdf.setValue(buf + i * POINT_STRIDE + 4, pPage.y, "float");\n }\n const idx = this.pdfiumModule.FPDFAnnot_AddInkStroke(annotationPtr, buf, n);\n this.memoryManager.free(buf);\n if (idx === -1) {\n return false;\n }\n }\n return true;\n }\n /**\n * Read pdf text annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf text annotation\n *\n * @private\n */\n readPdfTextAnno(doc, page, annotationPtr, index) {\n const annoRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, annoRect);\n const state = this.getAnnotString(annotationPtr, "State");\n const stateModel = this.getAnnotString(annotationPtr, "StateModel");\n const color = this.getAnnotationColor(annotationPtr);\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const icon = this.getAnnotationIcon(annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.TEXT,\n rect,\n strokeColor: color ?? "#FFFF00",\n color: color ?? "#FFFF00",\n opacity,\n state,\n stateModel,\n icon,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf freetext annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf freetext annotation\n *\n * @private\n */\n readPdfFreeTextAnno(doc, page, annotationPtr, index) {\n const annoRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, annoRect);\n const defaultStyle = this.getAnnotString(annotationPtr, "DS");\n const da = this.getAnnotationDefaultAppearance(annotationPtr);\n const bgColor = this.getAnnotationColor(annotationPtr);\n const textAlign = this.getAnnotationTextAlignment(annotationPtr);\n const verticalAlign = this.getAnnotationVerticalAlignment(annotationPtr);\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const richContent = this.getAnnotRichContent(annotationPtr);\n const rd = this.getRectangleDifferences(annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.FREETEXT,\n rect,\n fontFamily: (da == null ? void 0 : da.fontFamily) ?? PdfStandardFont.Unknown,\n fontSize: (da == null ? void 0 : da.fontSize) ?? 12,\n fontColor: (da == null ? void 0 : da.fontColor) ?? "#000000",\n verticalAlign,\n color: bgColor,\n // fill color (matches shape convention)\n backgroundColor: bgColor,\n // deprecated alias\n opacity,\n textAlign,\n defaultStyle,\n richContent,\n ...rd.ok && {\n rectangleDifferences: {\n left: rd.left,\n top: rd.top,\n right: rd.right,\n bottom: rd.bottom\n }\n },\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf link annotation from pdf document\n * @param page - pdf page infor\n * @param docPtr - pointer to pdf document object\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf link annotation\n *\n * @private\n */\n readPdfLinkAnno(doc, page, docPtr, annotationPtr, index) {\n const linkPtr = this.pdfiumModule.FPDFAnnot_GetLink(annotationPtr);\n if (!linkPtr) {\n return;\n }\n const annoRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, annoRect);\n const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);\n const strokeColor = this.getAnnotationColor(annotationPtr, PdfAnnotationColorType.Color);\n let strokeDashArray;\n if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {\n const { ok, pattern } = this.getBorderDashPattern(annotationPtr);\n if (ok) {\n strokeDashArray = pattern;\n }\n }\n const target = this.readPdfLinkAnnoTarget(\n docPtr,\n () => {\n return this.pdfiumModule.FPDFLink_GetAction(linkPtr);\n },\n () => {\n return this.pdfiumModule.FPDFLink_GetDest(docPtr, linkPtr);\n }\n );\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.LINK,\n rect,\n target,\n strokeColor,\n strokeWidth,\n strokeStyle,\n strokeDashArray,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf widget annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param formHandle - form handle\n * @param index - index of annotation in the pdf page\n * @returns pdf widget annotation\n *\n * @private\n */\n readPdfWidgetAnno(doc, page, annotationPtr, formHandle, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const field = this.readPdfWidgetAnnoField(formHandle, annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.WIDGET,\n rect,\n field,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf file attachment annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf file attachment annotation\n *\n * @private\n */\n readPdfFileAttachmentAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.FILEATTACHMENT,\n rect,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf ink annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf ink annotation\n *\n * @private\n */\n readPdfInkAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const strokeColor = this.getAnnotationColor(annotationPtr) ?? "#FF0000";\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const { width: strokeWidth } = this.getBorderStyle(annotationPtr);\n const inkList = this.getInkList(doc, page, annotationPtr);\n const blendMode = this.pdfiumModule.EPDFAnnot_GetBlendMode(annotationPtr);\n const intent = this.getAnnotIntent(annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.INK,\n rect,\n ...intent && { intent },\n blendMode,\n strokeColor,\n color: strokeColor,\n // deprecated alias\n opacity,\n strokeWidth: strokeWidth === 0 ? 1 : strokeWidth,\n inkList,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf polygon annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf polygon annotation\n *\n * @private\n */\n readPdfPolygonAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const vertices = this.readPdfAnnoVertices(doc, page, annotationPtr);\n const strokeColor = this.getAnnotationColor(annotationPtr);\n const interiorColor = this.getAnnotationColor(\n annotationPtr,\n PdfAnnotationColorType.InteriorColor\n );\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);\n let strokeDashArray;\n if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {\n const { ok, pattern } = this.getBorderDashPattern(annotationPtr);\n if (ok) {\n strokeDashArray = pattern;\n }\n }\n if (vertices.length > 1) {\n const first = vertices[0];\n const last = vertices[vertices.length - 1];\n if (first.x === last.x && first.y === last.y) {\n vertices.pop();\n }\n }\n const rd = this.getRectangleDifferences(annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.POLYGON,\n rect,\n strokeColor: strokeColor ?? "#FF0000",\n color: interiorColor ?? "transparent",\n opacity,\n strokeWidth: strokeWidth === 0 ? 1 : strokeWidth,\n strokeStyle,\n strokeDashArray,\n vertices,\n ...rd.ok && {\n rectangleDifferences: {\n left: rd.left,\n top: rd.top,\n right: rd.right,\n bottom: rd.bottom\n }\n },\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf polyline annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf polyline annotation\n *\n * @private\n */\n readPdfPolylineAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const vertices = this.readPdfAnnoVertices(doc, page, annotationPtr);\n const strokeColor = this.getAnnotationColor(annotationPtr);\n const interiorColor = this.getAnnotationColor(\n annotationPtr,\n PdfAnnotationColorType.InteriorColor\n );\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);\n let strokeDashArray;\n if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {\n const { ok, pattern } = this.getBorderDashPattern(annotationPtr);\n if (ok) {\n strokeDashArray = pattern;\n }\n }\n const lineEndings = this.getLineEndings(annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.POLYLINE,\n rect,\n strokeColor: strokeColor ?? "#FF0000",\n color: interiorColor ?? "transparent",\n opacity,\n strokeWidth: strokeWidth === 0 ? 1 : strokeWidth,\n strokeStyle,\n strokeDashArray,\n lineEndings,\n vertices,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf line annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf line annotation\n *\n * @private\n */\n readPdfLineAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const linePoints = this.getLinePoints(doc, page, annotationPtr);\n const lineEndings = this.getLineEndings(annotationPtr);\n const strokeColor = this.getAnnotationColor(annotationPtr);\n const interiorColor = this.getAnnotationColor(\n annotationPtr,\n PdfAnnotationColorType.InteriorColor\n );\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);\n let strokeDashArray;\n if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {\n const { ok, pattern } = this.getBorderDashPattern(annotationPtr);\n if (ok) {\n strokeDashArray = pattern;\n }\n }\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.LINE,\n rect,\n strokeWidth: strokeWidth === 0 ? 1 : strokeWidth,\n strokeStyle,\n strokeDashArray,\n strokeColor: strokeColor ?? "#FF0000",\n color: interiorColor ?? "transparent",\n opacity,\n linePoints: linePoints || { start: { x: 0, y: 0 }, end: { x: 0, y: 0 } },\n lineEndings: lineEndings || {\n start: PdfAnnotationLineEnding.None,\n end: PdfAnnotationLineEnding.None\n },\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf highlight annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf highlight annotation\n *\n * @private\n */\n readPdfHighlightAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const segmentRects = this.getQuadPointsAnno(doc, page, annotationPtr);\n const strokeColor = this.getAnnotationColor(annotationPtr) ?? "#FFFF00";\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const blendMode = this.pdfiumModule.EPDFAnnot_GetBlendMode(annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.HIGHLIGHT,\n rect,\n blendMode,\n segmentRects,\n strokeColor,\n color: strokeColor,\n // deprecated alias\n opacity,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf underline annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf underline annotation\n *\n * @private\n */\n readPdfUnderlineAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const segmentRects = this.getQuadPointsAnno(doc, page, annotationPtr);\n const strokeColor = this.getAnnotationColor(annotationPtr) ?? "#FF0000";\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const blendMode = this.pdfiumModule.EPDFAnnot_GetBlendMode(annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.UNDERLINE,\n rect,\n blendMode,\n segmentRects,\n strokeColor,\n color: strokeColor,\n // deprecated alias\n opacity,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read strikeout annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf strikeout annotation\n *\n * @private\n */\n readPdfStrikeOutAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const segmentRects = this.getQuadPointsAnno(doc, page, annotationPtr);\n const strokeColor = this.getAnnotationColor(annotationPtr) ?? "#FF0000";\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const blendMode = this.pdfiumModule.EPDFAnnot_GetBlendMode(annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.STRIKEOUT,\n rect,\n blendMode,\n segmentRects,\n strokeColor,\n color: strokeColor,\n // deprecated alias\n opacity,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf squiggly annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf squiggly annotation\n *\n * @private\n */\n readPdfSquigglyAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const segmentRects = this.getQuadPointsAnno(doc, page, annotationPtr);\n const strokeColor = this.getAnnotationColor(annotationPtr) ?? "#FF0000";\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const blendMode = this.pdfiumModule.EPDFAnnot_GetBlendMode(annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.SQUIGGLY,\n rect,\n blendMode,\n segmentRects,\n strokeColor,\n color: strokeColor,\n // deprecated alias\n opacity,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf caret annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf caret annotation\n *\n * @private\n */\n readPdfCaretAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const strokeColor = this.getAnnotationColor(annotationPtr);\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const intent = this.getAnnotIntent(annotationPtr);\n const rd = this.getRectangleDifferences(annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.CARET,\n rect,\n strokeColor,\n opacity,\n intent,\n ...rd.ok && {\n rectangleDifferences: {\n left: rd.left,\n top: rd.top,\n right: rd.right,\n bottom: rd.bottom\n }\n },\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf redact annotation\n * @param page - pdf page info\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf redact annotation\n *\n * @private\n */\n readPdfRedactAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const segmentRects = this.getQuadPointsAnno(doc, page, annotationPtr);\n const color = this.getAnnotationColor(annotationPtr, PdfAnnotationColorType.InteriorColor);\n const overlayColor = this.getAnnotationColor(\n annotationPtr,\n PdfAnnotationColorType.OverlayColor\n );\n const strokeColor = this.getAnnotationColor(annotationPtr, PdfAnnotationColorType.Color);\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const overlayText = this.getOverlayText(annotationPtr);\n const overlayTextRepeat = this.getOverlayTextRepeat(annotationPtr);\n const da = this.getAnnotationDefaultAppearance(annotationPtr);\n const textAlign = this.getAnnotationTextAlignment(annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.REDACT,\n rect,\n segmentRects,\n color,\n overlayColor,\n strokeColor,\n opacity,\n overlayText,\n overlayTextRepeat,\n fontFamily: da == null ? void 0 : da.fontFamily,\n fontSize: da == null ? void 0 : da.fontSize,\n fontColor: da == null ? void 0 : da.fontColor,\n textAlign,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf stamp annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf stamp annotation\n *\n * @private\n */\n readPdfStampAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.STAMP,\n rect,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf object in pdf page\n * @param pageObjectPtr - pointer to pdf object in page\n * @returns pdf object in page\n *\n * @private\n */\n readPdfPageObject(pageObjectPtr) {\n const type = this.pdfiumModule.FPDFPageObj_GetType(pageObjectPtr);\n switch (type) {\n case PdfPageObjectType.PATH:\n return this.readPathObject(pageObjectPtr);\n case PdfPageObjectType.IMAGE:\n return this.readImageObject(pageObjectPtr);\n case PdfPageObjectType.FORM:\n return this.readFormObject(pageObjectPtr);\n }\n }\n /**\n * Read pdf path object\n * @param pathObjectPtr - pointer to pdf path object in page\n * @returns pdf path object\n *\n * @private\n */\n readPathObject(pathObjectPtr) {\n const segmentCount = this.pdfiumModule.FPDFPath_CountSegments(pathObjectPtr);\n const leftPtr = this.memoryManager.malloc(4);\n const bottomPtr = this.memoryManager.malloc(4);\n const rightPtr = this.memoryManager.malloc(4);\n const topPtr = this.memoryManager.malloc(4);\n this.pdfiumModule.FPDFPageObj_GetBounds(pathObjectPtr, leftPtr, bottomPtr, rightPtr, topPtr);\n const left = this.pdfiumModule.pdfium.getValue(leftPtr, "float");\n const bottom = this.pdfiumModule.pdfium.getValue(bottomPtr, "float");\n const right = this.pdfiumModule.pdfium.getValue(rightPtr, "float");\n const top = this.pdfiumModule.pdfium.getValue(topPtr, "float");\n const bounds = { left, bottom, right, top };\n this.memoryManager.free(leftPtr);\n this.memoryManager.free(bottomPtr);\n this.memoryManager.free(rightPtr);\n this.memoryManager.free(topPtr);\n const segments = [];\n for (let i = 0; i < segmentCount; i++) {\n const segment = this.readPdfSegment(pathObjectPtr, i);\n segments.push(segment);\n }\n const matrix = this.readPdfPageObjectTransformMatrix(pathObjectPtr);\n return {\n type: PdfPageObjectType.PATH,\n bounds,\n segments,\n matrix\n };\n }\n /**\n * Read segment of pdf path object\n * @param annotationObjectPtr - pointer to pdf path object\n * @param segmentIndex - index of segment\n * @returns pdf segment in pdf path\n *\n * @private\n */\n readPdfSegment(annotationObjectPtr, segmentIndex) {\n const segmentPtr = this.pdfiumModule.FPDFPath_GetPathSegment(annotationObjectPtr, segmentIndex);\n const segmentType = this.pdfiumModule.FPDFPathSegment_GetType(segmentPtr);\n const isClosed = this.pdfiumModule.FPDFPathSegment_GetClose(segmentPtr);\n const pointXPtr = this.memoryManager.malloc(4);\n const pointYPtr = this.memoryManager.malloc(4);\n this.pdfiumModule.FPDFPathSegment_GetPoint(segmentPtr, pointXPtr, pointYPtr);\n const pointX = this.pdfiumModule.pdfium.getValue(pointXPtr, "float");\n const pointY = this.pdfiumModule.pdfium.getValue(pointYPtr, "float");\n this.memoryManager.free(pointXPtr);\n this.memoryManager.free(pointYPtr);\n return {\n type: segmentType,\n point: { x: pointX, y: pointY },\n isClosed\n };\n }\n /**\n * Read pdf image object from pdf document\n * @param pageObjectPtr - pointer to pdf image object in page\n * @returns pdf image object\n *\n * @private\n */\n readImageObject(imageObjectPtr) {\n const bitmapPtr = this.pdfiumModule.FPDFImageObj_GetBitmap(imageObjectPtr);\n const bitmapBufferPtr = this.pdfiumModule.FPDFBitmap_GetBuffer(bitmapPtr);\n const bitmapWidth = this.pdfiumModule.FPDFBitmap_GetWidth(bitmapPtr);\n const bitmapHeight = this.pdfiumModule.FPDFBitmap_GetHeight(bitmapPtr);\n const format = this.pdfiumModule.FPDFBitmap_GetFormat(bitmapPtr);\n const pixelCount = bitmapWidth * bitmapHeight;\n const bytesPerPixel = 4;\n const array = new Uint8ClampedArray(pixelCount * bytesPerPixel);\n for (let i = 0; i < pixelCount; i++) {\n switch (format) {\n case 2:\n {\n const blue = this.pdfiumModule.pdfium.getValue(bitmapBufferPtr + i * 3, "i8");\n const green = this.pdfiumModule.pdfium.getValue(bitmapBufferPtr + i * 3 + 1, "i8");\n const red = this.pdfiumModule.pdfium.getValue(bitmapBufferPtr + i * 3 + 2, "i8");\n array[i * bytesPerPixel] = red;\n array[i * bytesPerPixel + 1] = green;\n array[i * bytesPerPixel + 2] = blue;\n array[i * bytesPerPixel + 3] = 100;\n }\n break;\n }\n }\n const imageDataLike = {\n data: array,\n width: bitmapWidth,\n height: bitmapHeight\n };\n const matrix = this.readPdfPageObjectTransformMatrix(imageObjectPtr);\n return {\n type: PdfPageObjectType.IMAGE,\n imageData: imageDataLike,\n matrix\n };\n }\n /**\n * Read form object from pdf document\n * @param formObjectPtr - pointer to pdf form object in page\n * @returns pdf form object\n *\n * @private\n */\n readFormObject(formObjectPtr) {\n const objectCount = this.pdfiumModule.FPDFFormObj_CountObjects(formObjectPtr);\n const objects = [];\n for (let i = 0; i < objectCount; i++) {\n const pageObjectPtr = this.pdfiumModule.FPDFFormObj_GetObject(formObjectPtr, i);\n const pageObj = this.readPdfPageObject(pageObjectPtr);\n if (pageObj) {\n objects.push(pageObj);\n }\n }\n const matrix = this.readPdfPageObjectTransformMatrix(formObjectPtr);\n return {\n type: PdfPageObjectType.FORM,\n objects,\n matrix\n };\n }\n /**\n * Read pdf object in pdf page\n * @param pageObjectPtr - pointer to pdf object in page\n * @returns pdf object in page\n *\n * @private\n */\n readPdfPageObjectTransformMatrix(pageObjectPtr) {\n const matrixPtr = this.memoryManager.malloc(4 * 6);\n if (this.pdfiumModule.FPDFPageObj_GetMatrix(pageObjectPtr, matrixPtr)) {\n const a = this.pdfiumModule.pdfium.getValue(matrixPtr, "float");\n const b = this.pdfiumModule.pdfium.getValue(matrixPtr + 4, "float");\n const c = this.pdfiumModule.pdfium.getValue(matrixPtr + 8, "float");\n const d = this.pdfiumModule.pdfium.getValue(matrixPtr + 12, "float");\n const e = this.pdfiumModule.pdfium.getValue(matrixPtr + 16, "float");\n const f = this.pdfiumModule.pdfium.getValue(matrixPtr + 20, "float");\n this.memoryManager.free(matrixPtr);\n return { a, b, c, d, e, f };\n }\n this.memoryManager.free(matrixPtr);\n return { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };\n }\n /**\n * Read contents of a stamp annotation\n * @param annotationPtr - pointer to pdf annotation\n * @returns contents of the stamp annotation\n *\n * @private\n */\n readStampAnnotationContents(annotationPtr) {\n const contents = [];\n const objectCount = this.pdfiumModule.FPDFAnnot_GetObjectCount(annotationPtr);\n for (let i = 0; i < objectCount; i++) {\n const annotationObjectPtr = this.pdfiumModule.FPDFAnnot_GetObject(annotationPtr, i);\n const pageObj = this.readPdfPageObject(annotationObjectPtr);\n if (pageObj) {\n contents.push(pageObj);\n }\n }\n return contents;\n }\n /**\n * Return the stroke-width declared in the annotation’s /Border or /BS entry.\n * Falls back to 1 pt when nothing is defined.\n *\n * @param annotationPtr - pointer to pdf annotation\n * @returns stroke-width\n *\n * @private\n */\n getStrokeWidth(annotationPtr) {\n const hPtr = this.memoryManager.malloc(4);\n const vPtr = this.memoryManager.malloc(4);\n const wPtr = this.memoryManager.malloc(4);\n const ok = this.pdfiumModule.FPDFAnnot_GetBorder(annotationPtr, hPtr, vPtr, wPtr);\n const width = ok ? this.pdfiumModule.pdfium.getValue(wPtr, "float") : 1;\n this.memoryManager.free(hPtr);\n this.memoryManager.free(vPtr);\n this.memoryManager.free(wPtr);\n return width;\n }\n /**\n * Fetches the `/F` flag bit-field from an annotation.\n *\n * @param annotationPtr pointer to an `FPDF_ANNOTATION`\n * @returns `{ raw, flags }`\n * • `raw` – the 32-bit integer returned by PDFium\n * • `flags` – object with individual booleans\n */\n getAnnotationFlags(annotationPtr) {\n const rawFlags = this.pdfiumModule.FPDFAnnot_GetFlags(annotationPtr);\n return flagsToNames(rawFlags);\n }\n setAnnotationFlags(annotationPtr, flags) {\n const rawFlags = namesToFlags(flags);\n return this.pdfiumModule.FPDFAnnot_SetFlags(annotationPtr, rawFlags);\n }\n /**\n * Read circle annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf circle annotation\n *\n * @private\n */\n readPdfCircleAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const interiorColor = this.getAnnotationColor(\n annotationPtr,\n PdfAnnotationColorType.InteriorColor\n );\n const strokeColor = this.getAnnotationColor(annotationPtr);\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);\n let strokeDashArray;\n if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {\n const { ok, pattern } = this.getBorderDashPattern(annotationPtr);\n if (ok) {\n strokeDashArray = pattern;\n }\n }\n const rd = this.getRectangleDifferences(annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.CIRCLE,\n rect,\n color: interiorColor ?? "transparent",\n opacity,\n strokeWidth,\n strokeColor: strokeColor ?? "#FF0000",\n strokeStyle,\n ...strokeDashArray !== void 0 && { strokeDashArray },\n ...rd.ok && {\n rectangleDifferences: {\n left: rd.left,\n top: rd.top,\n right: rd.right,\n bottom: rd.bottom\n }\n },\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read square annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf square annotation\n *\n * @private\n */\n readPdfSquareAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const interiorColor = this.getAnnotationColor(\n annotationPtr,\n PdfAnnotationColorType.InteriorColor\n );\n const strokeColor = this.getAnnotationColor(annotationPtr);\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);\n let strokeDashArray;\n if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {\n const { ok, pattern } = this.getBorderDashPattern(annotationPtr);\n if (ok) {\n strokeDashArray = pattern;\n }\n }\n const rd = this.getRectangleDifferences(annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.SQUARE,\n rect,\n color: interiorColor ?? "transparent",\n opacity,\n strokeColor: strokeColor ?? "#FF0000",\n strokeWidth,\n strokeStyle,\n ...strokeDashArray !== void 0 && { strokeDashArray },\n ...rd.ok && {\n rectangleDifferences: {\n left: rd.left,\n top: rd.top,\n right: rd.right,\n bottom: rd.bottom\n }\n },\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read basic info of unsupported pdf annotation\n * @param page - pdf page infor\n * @param type - type of annotation\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf annotation\n *\n * @private\n */\n readPdfAnno(doc, page, type, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n return {\n pageIndex: page.index,\n id: index,\n type,\n rect,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Resolve `/IRT` → parent-annotation index on the same page.\n *\n * @param pagePtr - pointer to FPDF_PAGE\n * @param annotationPtr - pointer to FPDF_ANNOTATION\n * @returns index (`0…count-1`) or `undefined` when the annotation is *not* a reply\n *\n * @private\n */\n getInReplyToId(annotationPtr) {\n const parentPtr = this.pdfiumModule.FPDFAnnot_GetLinkedAnnot(annotationPtr, "IRT");\n if (!parentPtr) return;\n let nm = this.getAnnotString(parentPtr, "NM");\n if (!nm || !isUuidV4(nm)) {\n nm = uuidV4();\n this.setAnnotString(parentPtr, "NM", nm);\n }\n this.pdfiumModule.FPDFPage_CloseAnnot(parentPtr);\n return nm;\n }\n /**\n * Set the in reply to id of the annotation\n *\n * @param annotationPtr - pointer to an `FPDF_ANNOTATION`\n * @param id - the id of the parent annotation\n * @returns `true` on success\n */\n setInReplyToId(pagePtr, annotationPtr, id) {\n if (!id) {\n return this.pdfiumModule.EPDFAnnot_SetLinkedAnnot(annotationPtr, "IRT", 0);\n }\n const parentPtr = this.getAnnotationByName(pagePtr, id);\n if (!parentPtr) return false;\n return this.pdfiumModule.EPDFAnnot_SetLinkedAnnot(annotationPtr, "IRT", parentPtr);\n }\n /**\n * Rotate a point around a center by the given angle in degrees.\n * Used to rotate vertices for PDF storage.\n */\n rotatePointForSave(point, center, angleDegrees) {\n const rad = angleDegrees * Math.PI / 180;\n const cos = Math.cos(rad);\n const sin = Math.sin(rad);\n const dx = point.x - center.x;\n const dy = point.y - center.y;\n return {\n x: center.x + dx * cos - dy * sin,\n y: center.y + dx * sin + dy * cos\n };\n }\n /**\n * Prepare an annotation for saving to PDF.\n * For vertex types (ink, line, polygon, polyline) with rotation,\n * physically rotates the vertices by +rotation so that other PDF viewers\n * see the correct visual result. Our viewer reverse-rotates on load.\n */\n prepareAnnotationForSave(annotation) {\n const rotation = annotation.rotation;\n const unrotatedRect = annotation.unrotatedRect;\n if (!rotation || rotation === 0 || !unrotatedRect) {\n return annotation;\n }\n const center = {\n x: unrotatedRect.origin.x + unrotatedRect.size.width / 2,\n y: unrotatedRect.origin.y + unrotatedRect.size.height / 2\n };\n switch (annotation.type) {\n case PdfAnnotationSubtype.INK: {\n const ink = annotation;\n const rotatedInkList = ink.inkList.map((stroke) => ({\n points: stroke.points.map((p) => this.rotatePointForSave(p, center, rotation))\n }));\n return { ...ink, inkList: rotatedInkList };\n }\n case PdfAnnotationSubtype.LINE: {\n const line = annotation;\n return {\n ...line,\n linePoints: {\n start: this.rotatePointForSave(line.linePoints.start, center, rotation),\n end: this.rotatePointForSave(line.linePoints.end, center, rotation)\n }\n };\n }\n case PdfAnnotationSubtype.POLYGON: {\n const poly = annotation;\n return {\n ...poly,\n vertices: poly.vertices.map((v) => this.rotatePointForSave(v, center, rotation))\n };\n }\n case PdfAnnotationSubtype.POLYLINE: {\n const polyline = annotation;\n return {\n ...polyline,\n vertices: polyline.vertices.map((v) => this.rotatePointForSave(v, center, rotation))\n };\n }\n default:\n return annotation;\n }\n }\n /**\n * Apply all base annotation properties from PdfAnnotationObjectBase.\n * The setInReplyToId and setReplyType functions handle clearing when undefined.\n *\n * @param pagePtr - pointer to page object\n * @param annotationPtr - pointer to annotation object\n * @param annotation - the annotation object containing properties to apply\n * @returns `true` on success\n */\n applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation) {\n if (!this.setAnnotString(annotationPtr, "T", annotation.author || "")) {\n return false;\n }\n if (!this.setAnnotString(annotationPtr, "Contents", annotation.contents ?? "")) {\n return false;\n }\n if (annotation.modified) {\n if (!this.setAnnotationDate(annotationPtr, "M", annotation.modified)) {\n return false;\n }\n }\n if (annotation.created) {\n if (!this.setAnnotationDate(annotationPtr, "CreationDate", annotation.created)) {\n return false;\n }\n }\n if (annotation.flags) {\n if (!this.setAnnotationFlags(annotationPtr, annotation.flags)) {\n return false;\n }\n }\n const existingCustom = this.getAnnotCustom(annotationPtr) ?? {};\n const customData = {\n ...existingCustom,\n ...annotation.custom ?? {}\n };\n delete customData.unrotatedRect;\n delete customData.rotation;\n const hasCustomData = Object.keys(customData).length > 0;\n if (hasCustomData) {\n if (!this.setAnnotCustom(annotationPtr, customData)) {\n return false;\n }\n } else if (Object.keys(existingCustom).length > 0) {\n if (!this.setAnnotCustom(annotationPtr, null)) {\n return false;\n }\n }\n if (annotation.rotation !== void 0) {\n const pdfRotation = annotation.rotation ? (360 - annotation.rotation) % 360 : 0;\n this.setAnnotExtendedRotation(annotationPtr, pdfRotation);\n }\n if (annotation.unrotatedRect) {\n this.setAnnotUnrotatedRect(doc, page, annotationPtr, annotation.unrotatedRect);\n } else if (annotation.rotation && annotation.rotation !== 0) {\n this.setAnnotUnrotatedRect(doc, page, annotationPtr, annotation.rect);\n }\n if (!this.setInReplyToId(pagePtr, annotationPtr, annotation.inReplyToId)) {\n return false;\n }\n if (!this.setReplyType(annotationPtr, annotation.replyType)) {\n return false;\n }\n return true;\n }\n /**\n * Read all base annotation properties from PdfAnnotationObjectBase.\n * Returns an object that can be spread into the annotation return value.\n *\n * @param doc - pdf document object\n * @param page - pdf page object\n * @param annotationPtr - pointer to annotation object\n * @returns object with base annotation properties\n */\n readBaseAnnotationProperties(doc, page, annotationPtr) {\n const author = this.getAnnotString(annotationPtr, "T");\n const contents = this.getAnnotString(annotationPtr, "Contents") || "";\n const modified = this.getAnnotationDate(annotationPtr, "M");\n const created = this.getAnnotationDate(annotationPtr, "CreationDate");\n const flags = this.getAnnotationFlags(annotationPtr);\n const custom = this.getAnnotCustom(annotationPtr);\n const inReplyToId = this.getInReplyToId(annotationPtr);\n const replyType = this.getReplyType(annotationPtr);\n const pdfRotation = this.getAnnotExtendedRotation(annotationPtr);\n const rotation = pdfRotation !== 0 ? (360 - pdfRotation) % 360 : 0;\n const rawUnrotatedRect = this.readAnnotUnrotatedRect(annotationPtr);\n const unrotatedRect = rawUnrotatedRect ? this.convertPageRectToDeviceRect(doc, page, rawUnrotatedRect) : void 0;\n return {\n author,\n contents,\n modified,\n created,\n flags,\n custom,\n // Only include IRT if present\n ...inReplyToId && { inReplyToId },\n // Only include RT if present and not the default (Reply)\n ...replyType && replyType !== PdfAnnotationReplyType.Reply && { replyType },\n ...rotation !== 0 && { rotation },\n ...unrotatedRect !== void 0 && { unrotatedRect }\n };\n }\n /**\n * Fetch a string value (`/T`, `/M`, `/State`, …) from an annotation.\n *\n * @returns decoded UTF-8 string or `undefined` when the key is absent\n *\n * @private\n */\n getAnnotString(annotationPtr, key) {\n const len = this.pdfiumModule.FPDFAnnot_GetStringValue(annotationPtr, key, 0, 0);\n if (len === 0) return;\n const bytes = (len + 1) * 2;\n const ptr = this.memoryManager.malloc(bytes);\n this.pdfiumModule.FPDFAnnot_GetStringValue(annotationPtr, key, ptr, bytes);\n const value = this.pdfiumModule.pdfium.UTF16ToString(ptr);\n this.memoryManager.free(ptr);\n return value || void 0;\n }\n /**\n * Get a string value (`/T`, `/M`, `/State`, …) from an attachment.\n *\n * @returns decoded UTF-8 string or `undefined` when the key is absent\n *\n * @private\n */\n getAttachmentString(attachmentPtr, key) {\n const len = this.pdfiumModule.FPDFAttachment_GetStringValue(attachmentPtr, key, 0, 0);\n if (len === 0) return;\n const bytes = (len + 1) * 2;\n const ptr = this.memoryManager.malloc(bytes);\n this.pdfiumModule.FPDFAttachment_GetStringValue(attachmentPtr, key, ptr, bytes);\n const value = this.pdfiumModule.pdfium.UTF16ToString(ptr);\n this.memoryManager.free(ptr);\n return value || void 0;\n }\n /**\n * Get a number value (`/Size`) from an attachment.\n *\n * @returns number or `null` when the key is absent\n *\n * @private\n */\n getAttachmentNumber(attachmentPtr, key) {\n const outPtr = this.memoryManager.malloc(4);\n try {\n const ok = this.pdfiumModule.EPDFAttachment_GetIntegerValue(\n attachmentPtr,\n key,\n // FPDF_BYTESTRING → ASCII JS string is fine in your glue\n outPtr\n );\n if (!ok) return void 0;\n return this.pdfiumModule.pdfium.getValue(outPtr, "i32") >>> 0;\n } finally {\n this.memoryManager.free(outPtr);\n }\n }\n /**\n * Get custom data of the annotation\n * @param annotationPtr - pointer to pdf annotation\n * @returns custom data of the annotation\n *\n * @private\n */\n getAnnotCustom(annotationPtr) {\n const custom = this.getAnnotString(annotationPtr, "EPDFCustom");\n if (!custom) return;\n try {\n return JSON.parse(custom);\n } catch (error) {\n console.warn("Failed to parse annotation custom data as JSON:", error);\n console.warn("Invalid JSON string:", custom);\n return void 0;\n }\n }\n /**\n * Sets custom data for an annotation by safely stringifying and storing JSON\n * @private\n */\n setAnnotCustom(annotationPtr, data) {\n if (data === void 0 || data === null) {\n return this.setAnnotString(annotationPtr, "EPDFCustom", "");\n }\n try {\n const jsonString = JSON.stringify(data);\n return this.setAnnotString(annotationPtr, "EPDFCustom", jsonString);\n } catch (error) {\n console.warn("Failed to stringify annotation custom data as JSON:", error);\n console.warn("Invalid data object:", data);\n return false;\n }\n }\n /**\n * Fetches the /IT (Intent) name from an annotation as a UTF-8 JS string.\n *\n * Mirrors getAnnotString(): calls EPDFAnnot_GetIntent twice (length probe + copy).\n * Returns `undefined` if no intent present.\n */\n getAnnotIntent(annotationPtr) {\n const len = this.pdfiumModule.EPDFAnnot_GetIntent(annotationPtr, 0, 0);\n if (len === 0) return;\n const codeUnits = len + 1;\n const bytes = codeUnits * 2;\n const ptr = this.memoryManager.malloc(bytes);\n this.pdfiumModule.EPDFAnnot_GetIntent(annotationPtr, ptr, bytes);\n const value = this.pdfiumModule.pdfium.UTF16ToString(ptr);\n this.memoryManager.free(ptr);\n return value && value !== "undefined" ? value : void 0;\n }\n /**\n * Write the `/IT` (Intent) name into an annotation dictionary.\n *\n * Mirrors EPDFAnnot_SetIntent in PDFium (expects a UTF‑8 FPDF_BYTESTRING).\n *\n * @param annotationPtr Pointer returned by FPDFPage_GetAnnot\n * @param intent Name without leading slash, e.g. `"PolygonCloud"`\n * A leading “/” will be stripped for convenience.\n * @returns true on success, false otherwise\n */\n setAnnotIntent(annotationPtr, intent) {\n return this.pdfiumModule.EPDFAnnot_SetIntent(annotationPtr, intent);\n }\n /**\n * Returns the rich‑content string stored in the annotation’s `/RC` entry.\n *\n * Works like `getAnnotIntent()`: first probe for length, then copy.\n * `undefined` when the annotation has no rich content.\n */\n getAnnotRichContent(annotationPtr) {\n const len = this.pdfiumModule.EPDFAnnot_GetRichContent(annotationPtr, 0, 0);\n if (len === 0) return;\n const codeUnits = len + 1;\n const bytes = codeUnits * 2;\n const ptr = this.memoryManager.malloc(bytes);\n this.pdfiumModule.EPDFAnnot_GetRichContent(annotationPtr, ptr, bytes);\n const value = this.pdfiumModule.pdfium.UTF16ToString(ptr);\n this.memoryManager.free(ptr);\n return value || void 0;\n }\n /**\n * Get annotation by name\n * @param pagePtr - pointer to pdf page object\n * @param name - name of annotation\n * @returns pointer to pdf annotation\n *\n * @private\n */\n getAnnotationByName(pagePtr, name) {\n return this.withWString(name, (wNamePtr) => {\n return this.pdfiumModule.EPDFPage_GetAnnotByName(pagePtr, wNamePtr);\n });\n }\n /**\n * Remove annotation by name\n * @param pagePtr - pointer to pdf page object\n * @param name - name of annotation\n * @returns true on success\n *\n * @private\n */\n removeAnnotationByName(pagePtr, name) {\n return this.withWString(name, (wNamePtr) => {\n return this.pdfiumModule.EPDFPage_RemoveAnnotByName(pagePtr, wNamePtr);\n });\n }\n /**\n * Set a string value (`/T`, `/M`, `/State`, …) to an annotation.\n *\n * @returns `true` if the operation was successful\n *\n * @private\n */\n setAnnotString(annotationPtr, key, value) {\n return this.withWString(value, (wValPtr) => {\n return this.pdfiumModule.FPDFAnnot_SetStringValue(annotationPtr, key, wValPtr);\n });\n }\n /**\n * Set a string value (`/T`, `/M`, `/State`, …) to an attachment.\n *\n * @returns `true` if the operation was successful\n *\n * @private\n */\n setAttachmentString(attachmentPtr, key, value) {\n return this.withWString(value, (wValPtr) => {\n return this.pdfiumModule.FPDFAttachment_SetStringValue(attachmentPtr, key, wValPtr);\n });\n }\n /**\n * Read vertices of pdf annotation\n * @param doc - pdf document object\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @returns vertices of pdf annotation\n *\n * @private\n */\n readPdfAnnoVertices(doc, page, annotationPtr) {\n const vertices = [];\n const count = this.pdfiumModule.FPDFAnnot_GetVertices(annotationPtr, 0, 0);\n const pointMemorySize = 8;\n const pointsPtr = this.memoryManager.malloc(count * pointMemorySize);\n this.pdfiumModule.FPDFAnnot_GetVertices(annotationPtr, pointsPtr, count);\n for (let i = 0; i < count; i++) {\n const pointX = this.pdfiumModule.pdfium.getValue(pointsPtr + i * pointMemorySize, "float");\n const pointY = this.pdfiumModule.pdfium.getValue(\n pointsPtr + i * pointMemorySize + 4,\n "float"\n );\n const { x, y } = this.convertPagePointToDevicePoint(doc, page, {\n x: pointX,\n y: pointY\n });\n const last = vertices[vertices.length - 1];\n if (!last || last.x !== x || last.y !== y) {\n vertices.push({ x, y });\n }\n }\n this.memoryManager.free(pointsPtr);\n return vertices;\n }\n /**\n * Sync the vertices of a polygon or polyline annotation.\n *\n * @param doc - pdf document object\n * @param page - pdf page infor\n * @param annotPtr - pointer to pdf annotation\n * @param vertices - the vertices to be set\n * @returns true on success\n *\n * @private\n */\n setPdfAnnoVertices(doc, page, annotPtr, vertices) {\n const pdf = this.pdfiumModule.pdfium;\n const FS_POINTF_SIZE = 8;\n const buf = this.memoryManager.malloc(FS_POINTF_SIZE * vertices.length);\n vertices.forEach((v, i) => {\n const pagePt = this.convertDevicePointToPagePoint(doc, page, v);\n pdf.setValue(buf + i * FS_POINTF_SIZE + 0, pagePt.x, "float");\n pdf.setValue(buf + i * FS_POINTF_SIZE + 4, pagePt.y, "float");\n });\n const ok = this.pdfiumModule.EPDFAnnot_SetVertices(annotPtr, buf, vertices.length);\n this.memoryManager.free(buf);\n return ok;\n }\n /**\n * Read the target of pdf bookmark\n * @param docPtr - pointer to pdf document object\n * @param getActionPtr - callback function to retrive the pointer of action\n * @param getDestinationPtr - callback function to retrive the pointer of destination\n * @returns target of pdf bookmark\n *\n * @private\n */\n readPdfBookmarkTarget(docPtr, getActionPtr, getDestinationPtr) {\n const actionPtr = getActionPtr();\n if (actionPtr) {\n const action = this.readPdfAction(docPtr, actionPtr);\n return {\n type: "action",\n action\n };\n } else {\n const destinationPtr = getDestinationPtr();\n if (destinationPtr) {\n const destination = this.readPdfDestination(docPtr, destinationPtr);\n return {\n type: "destination",\n destination\n };\n }\n }\n }\n /**\n * Read field of pdf widget annotation\n * @param formHandle - form handle\n * @param annotationPtr - pointer to pdf annotation\n * @returns field of pdf widget annotation\n *\n * @private\n */\n readPdfWidgetAnnoField(formHandle, annotationPtr) {\n const flag = this.pdfiumModule.FPDFAnnot_GetFormFieldFlags(\n formHandle,\n annotationPtr\n );\n const type = this.pdfiumModule.FPDFAnnot_GetFormFieldType(\n formHandle,\n annotationPtr\n );\n const name = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFAnnot_GetFormFieldName(\n formHandle,\n annotationPtr,\n buffer,\n bufferLength\n );\n },\n this.pdfiumModule.pdfium.UTF16ToString\n );\n const alternateName = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFAnnot_GetFormFieldAlternateName(\n formHandle,\n annotationPtr,\n buffer,\n bufferLength\n );\n },\n this.pdfiumModule.pdfium.UTF16ToString\n );\n const value = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFAnnot_GetFormFieldValue(\n formHandle,\n annotationPtr,\n buffer,\n bufferLength\n );\n },\n this.pdfiumModule.pdfium.UTF16ToString\n );\n const options = [];\n if (type === PDF_FORM_FIELD_TYPE.COMBOBOX || type === PDF_FORM_FIELD_TYPE.LISTBOX) {\n const count = this.pdfiumModule.FPDFAnnot_GetOptionCount(formHandle, annotationPtr);\n for (let i = 0; i < count; i++) {\n const label = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFAnnot_GetOptionLabel(\n formHandle,\n annotationPtr,\n i,\n buffer,\n bufferLength\n );\n },\n this.pdfiumModule.pdfium.UTF16ToString\n );\n const isSelected = this.pdfiumModule.FPDFAnnot_IsOptionSelected(\n formHandle,\n annotationPtr,\n i\n );\n options.push({\n label,\n isSelected\n });\n }\n }\n let isChecked = false;\n if (type === PDF_FORM_FIELD_TYPE.CHECKBOX || type === PDF_FORM_FIELD_TYPE.RADIOBUTTON) {\n isChecked = this.pdfiumModule.FPDFAnnot_IsChecked(formHandle, annotationPtr);\n }\n return {\n flag,\n type,\n name,\n alternateName,\n value,\n isChecked,\n options\n };\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.renderAnnotation}\n *\n * @public\n */\n renderPageAnnotationRaw(doc, page, annotation, options) {\n const {\n scaleFactor = 1,\n rotation = Rotation.Degree0,\n dpr = 1,\n mode = AppearanceMode.Normal\n } = options ?? {};\n this.logger.debug(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "renderPageAnnotation",\n doc,\n page,\n annotation,\n options\n );\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RenderPageAnnotation`,\n "Begin",\n `${doc.id}-${page.index}-${annotation.id}`\n );\n const task = new Task();\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RenderPageAnnotation`,\n "End",\n `${doc.id}-${page.index}-${annotation.id}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const annotPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);\n if (!annotPtr) {\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RenderPageAnnotation`,\n "End",\n `${doc.id}-${page.index}-${annotation.id}`\n );\n pageCtx.release();\n return PdfTaskHelper.reject({ code: PdfErrorCode.NotFound, message: "annotation not found" });\n }\n const finalScale = Math.max(0.01, scaleFactor * dpr);\n const unrotated = !!(options == null ? void 0 : options.unrotated) && !!annotation.unrotatedRect;\n const renderRect = unrotated ? annotation.unrotatedRect : annotation.rect;\n const rect = toIntRect(renderRect);\n const devRect = toIntRect(transformRect(page.size, rect, rotation, finalScale));\n const wDev = Math.max(1, devRect.size.width);\n const hDev = Math.max(1, devRect.size.height);\n const stride = wDev * 4;\n const bytes = stride * hDev;\n const heapPtr = this.memoryManager.malloc(bytes);\n const bitmapPtr = this.pdfiumModule.FPDFBitmap_CreateEx(\n wDev,\n hDev,\n 4,\n heapPtr,\n stride\n );\n this.pdfiumModule.FPDFBitmap_FillRect(bitmapPtr, 0, 0, wDev, hDev, 0);\n const M = buildUserToDeviceMatrix(\n rect,\n // {origin:{L,B}, size:{W,H}}\n rotation,\n wDev,\n hDev\n );\n const mPtr = this.memoryManager.malloc(6 * 4);\n const mView = new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer, mPtr, 6);\n mView.set([M.a, M.b, M.c, M.d, M.e, M.f]);\n const FLAGS = 16;\n let ok = false;\n try {\n if (unrotated) {\n ok = !!this.pdfiumModule.EPDF_RenderAnnotBitmapUnrotated(\n bitmapPtr,\n pageCtx.pagePtr,\n annotPtr,\n mode,\n mPtr,\n FLAGS\n );\n } else {\n ok = !!this.pdfiumModule.EPDF_RenderAnnotBitmap(\n bitmapPtr,\n pageCtx.pagePtr,\n annotPtr,\n mode,\n mPtr,\n FLAGS\n );\n }\n } finally {\n this.memoryManager.free(mPtr);\n this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);\n this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);\n pageCtx.release();\n }\n if (!ok) {\n this.memoryManager.free(heapPtr);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RenderPageAnnotation`,\n "End",\n `${doc.id}-${page.index}-${annotation.id}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: "EPDF_RenderAnnotBitmap failed"\n });\n }\n const data = this.pdfiumModule.pdfium.HEAPU8.subarray(heapPtr, heapPtr + bytes);\n const imageDataLike = {\n data: new Uint8ClampedArray(data),\n width: wDev,\n height: hDev\n };\n task.resolve(imageDataLike);\n this.memoryManager.free(heapPtr);\n return task;\n }\n /**\n * Batch-render all annotation appearance streams for a page in one call.\n * Returns a map of annotation ID -> rendered appearances (Normal/Rollover/Down).\n * Skips annotations that have rotation + unrotatedRect (EmbedPDF-rotated)\n * and annotations without any appearance stream.\n *\n * @public\n */\n renderPageAnnotationsRaw(doc, page, options) {\n const { scaleFactor = 1, rotation = Rotation.Degree0, dpr = 1 } = options ?? {};\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "renderPageAnnotationsRaw", doc, page, options);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "RenderPageAnnotationsRaw",\n "Begin",\n `${doc.id}-${page.index}`\n );\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "RenderPageAnnotationsRaw",\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const result = {};\n const finalScale = Math.max(0.01, scaleFactor * dpr);\n const annotCount = this.pdfiumModule.FPDFPage_GetAnnotCount(pageCtx.pagePtr);\n for (let i = 0; i < annotCount; i++) {\n const annotPtr = this.pdfiumModule.FPDFPage_GetAnnot(pageCtx.pagePtr, i);\n if (!annotPtr) continue;\n try {\n const nm = this.getAnnotString(annotPtr, "NM");\n if (!nm) continue;\n const extRotation = this.getAnnotExtendedRotation(annotPtr);\n if (extRotation !== 0) {\n const unrotatedRaw = this.readAnnotUnrotatedRect(annotPtr);\n if (unrotatedRaw) continue;\n }\n const apModes = this.pdfiumModule.EPDFAnnot_GetAvailableAppearanceModes(annotPtr);\n if (!apModes) continue;\n const appearances = {};\n const modesToRender = [\n { bit: AP_MODE_NORMAL, mode: AppearanceMode.Normal, key: "normal" },\n { bit: AP_MODE_ROLLOVER, mode: AppearanceMode.Rollover, key: "rollover" },\n { bit: AP_MODE_DOWN, mode: AppearanceMode.Down, key: "down" }\n ];\n for (const { bit, mode, key } of modesToRender) {\n if (!(apModes & bit)) continue;\n const rendered = this.renderSingleAnnotAppearance(\n doc,\n page,\n pageCtx,\n annotPtr,\n mode,\n rotation,\n finalScale\n );\n if (rendered) {\n appearances[key] = rendered;\n }\n }\n if (appearances.normal || appearances.rollover || appearances.down) {\n result[nm] = appearances;\n }\n } finally {\n this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);\n }\n }\n pageCtx.release();\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "RenderPageAnnotationsRaw",\n "End",\n `${doc.id}-${page.index}`\n );\n const task = new Task();\n task.resolve(result);\n return task;\n }\n /**\n * Render a single annotation\'s appearance for a given mode.\n * Returns the image data and rect, or null on failure.\n * @private\n */\n renderSingleAnnotAppearance(doc, page, pageCtx, annotPtr, mode, rotation, finalScale) {\n const pageRect = this.readPageAnnoRect(annotPtr);\n const annotRect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const rect = toIntRect(annotRect);\n const devRect = toIntRect(transformRect(page.size, rect, rotation, finalScale));\n const wDev = Math.max(1, devRect.size.width);\n const hDev = Math.max(1, devRect.size.height);\n const stride = wDev * 4;\n const bytes = stride * hDev;\n const heapPtr = this.memoryManager.malloc(bytes);\n const bitmapPtr = this.pdfiumModule.FPDFBitmap_CreateEx(\n wDev,\n hDev,\n 4,\n heapPtr,\n stride\n );\n this.pdfiumModule.FPDFBitmap_FillRect(bitmapPtr, 0, 0, wDev, hDev, 0);\n const M = buildUserToDeviceMatrix(rect, rotation, wDev, hDev);\n const mPtr = this.memoryManager.malloc(6 * 4);\n const mView = new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer, mPtr, 6);\n mView.set([M.a, M.b, M.c, M.d, M.e, M.f]);\n const FLAGS = 16;\n let ok = false;\n try {\n ok = !!this.pdfiumModule.EPDF_RenderAnnotBitmap(\n bitmapPtr,\n pageCtx.pagePtr,\n annotPtr,\n mode,\n mPtr,\n FLAGS\n );\n } finally {\n this.memoryManager.free(mPtr);\n this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);\n }\n if (!ok) {\n this.memoryManager.free(heapPtr);\n return null;\n }\n const data = this.pdfiumModule.pdfium.HEAPU8.subarray(heapPtr, heapPtr + bytes);\n const imageData = {\n data: new Uint8ClampedArray(data),\n width: wDev,\n height: hDev\n };\n this.memoryManager.free(heapPtr);\n return { data: imageData, rect: annotRect };\n }\n renderRectEncoded(doc, page, rect, options) {\n const task = new Task();\n const rotation = (options == null ? void 0 : options.rotation) ?? Rotation.Degree0;\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const scale = Math.max(0.01, (options == null ? void 0 : options.scaleFactor) ?? 1);\n const dpr = Math.max(1, (options == null ? void 0 : options.dpr) ?? 1);\n const finalScale = scale * dpr;\n const baseW = rect.size.width;\n const baseH = rect.size.height;\n const swap2 = (rotation & 1) === 1;\n const wDev = Math.max(1, Math.round((swap2 ? baseH : baseW) * finalScale));\n const hDev = Math.max(1, Math.round((swap2 ? baseW : baseH) * finalScale));\n const stride = wDev * 4;\n const bytes = stride * hDev;\n const pageCtx = ctx.acquirePage(page.index);\n const shouldRenderForms = (options == null ? void 0 : options.withForms) ?? false;\n const formHandle = shouldRenderForms ? pageCtx.getFormHandle() : void 0;\n const heapPtr = this.memoryManager.malloc(bytes);\n const bitmapPtr = this.pdfiumModule.FPDFBitmap_CreateEx(\n wDev,\n hDev,\n 4,\n heapPtr,\n stride\n );\n this.pdfiumModule.FPDFBitmap_FillRect(bitmapPtr, 0, 0, wDev, hDev, 4294967295);\n const M = buildUserToDeviceMatrix(rect, rotation, wDev, hDev);\n const mPtr = this.memoryManager.malloc(6 * 4);\n const mView = new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer, mPtr, 6);\n mView.set([M.a, M.b, M.c, M.d, M.e, M.f]);\n const clipPtr = this.memoryManager.malloc(4 * 4);\n const clipView = new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer, clipPtr, 4);\n clipView.set([0, 0, wDev, hDev]);\n let flags = 16;\n if ((options == null ? void 0 : options.withAnnotations) ?? false) flags |= 1;\n try {\n this.pdfiumModule.FPDF_RenderPageBitmapWithMatrix(\n bitmapPtr,\n pageCtx.pagePtr,\n mPtr,\n clipPtr,\n flags\n );\n if (formHandle !== void 0) {\n const formParams = computeFormDrawParams(M, rect, page.size, rotation);\n const { startX, startY, formsWidth, formsHeight, scaleX, scaleY } = formParams;\n this.pdfiumModule.FPDF_FFLDraw(\n formHandle,\n bitmapPtr,\n pageCtx.pagePtr,\n startX,\n startY,\n formsWidth,\n formsHeight,\n rotation,\n flags\n );\n }\n } finally {\n pageCtx.release();\n this.memoryManager.free(mPtr);\n this.memoryManager.free(clipPtr);\n }\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RenderRectEncodedData`,\n "Begin",\n `${doc.id}-${page.index}`\n );\n const data = this.pdfiumModule.pdfium.HEAPU8.subarray(heapPtr, heapPtr + bytes);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RenderRectEncodedData`,\n "End",\n `${doc.id}-${page.index}`\n );\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RenderRectEncodedImageData`,\n "Begin",\n `${doc.id}-${page.index}`\n );\n const imageDataLike = {\n data: new Uint8ClampedArray(data),\n width: wDev,\n height: hDev\n };\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RenderRectEncodedImageData`,\n "End",\n `${doc.id}-${page.index}`\n );\n task.resolve(imageDataLike);\n this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);\n this.memoryManager.free(heapPtr);\n return task;\n }\n /**\n * Read the target of pdf link annotation\n * @param docPtr - pointer to pdf document object\n * @param getActionPtr - callback function to retrive the pointer of action\n * @param getDestinationPtr - callback function to retrive the pointer of destination\n * @returns target of link\n *\n * @private\n */\n readPdfLinkAnnoTarget(docPtr, getActionPtr, getDestinationPtr) {\n const destinationPtr = getDestinationPtr();\n if (destinationPtr) {\n const destination = this.readPdfDestination(docPtr, destinationPtr);\n return {\n type: "destination",\n destination\n };\n } else {\n const actionPtr = getActionPtr();\n if (actionPtr) {\n const action = this.readPdfAction(docPtr, actionPtr);\n return {\n type: "action",\n action\n };\n }\n }\n }\n createLocalDestPtr(docPtr, dest) {\n var _a, _b;\n const pagePtr = this.pdfiumModule.FPDF_LoadPage(docPtr, dest.pageIndex);\n if (!pagePtr) return 0;\n try {\n if (dest.zoom.mode === PdfZoomMode.XYZ) {\n const { x, y, zoom } = dest.zoom.params;\n return this.pdfiumModule.EPDFDest_CreateXYZ(\n pagePtr,\n /*has_left*/\n true,\n x,\n /*has_top*/\n true,\n y,\n /*has_zoom*/\n true,\n zoom\n );\n }\n let viewEnum;\n let params = [];\n switch (dest.zoom.mode) {\n case PdfZoomMode.FitPage:\n viewEnum = PdfZoomMode.FitPage;\n break;\n case PdfZoomMode.FitHorizontal:\n viewEnum = PdfZoomMode.FitHorizontal;\n params = [((_a = dest.view) == null ? void 0 : _a[0]) ?? 0];\n break;\n case PdfZoomMode.FitVertical:\n viewEnum = PdfZoomMode.FitVertical;\n params = [((_b = dest.view) == null ? void 0 : _b[0]) ?? 0];\n break;\n case PdfZoomMode.FitRectangle:\n {\n const v = dest.view ?? [];\n params = [v[0] ?? 0, v[1] ?? 0, v[2] ?? 0, v[3] ?? 0];\n viewEnum = PdfZoomMode.FitRectangle;\n }\n break;\n case PdfZoomMode.Unknown:\n default:\n return 0;\n }\n return this.withFloatArray(\n params,\n (ptr, count) => this.pdfiumModule.EPDFDest_CreateView(pagePtr, viewEnum, ptr, count)\n );\n } finally {\n this.pdfiumModule.FPDF_ClosePage(pagePtr);\n }\n }\n applyBookmarkTarget(docPtr, bmPtr, target) {\n if (target.type === "destination") {\n const destPtr = this.createLocalDestPtr(docPtr, target.destination);\n if (!destPtr) return false;\n const ok = this.pdfiumModule.EPDFBookmark_SetDest(docPtr, bmPtr, destPtr);\n return !!ok;\n }\n const action = target.action;\n switch (action.type) {\n case PdfActionType.Goto: {\n const destPtr = this.createLocalDestPtr(docPtr, action.destination);\n if (!destPtr) return false;\n const actPtr = this.pdfiumModule.EPDFAction_CreateGoTo(docPtr, destPtr);\n if (!actPtr) return false;\n return !!this.pdfiumModule.EPDFBookmark_SetAction(docPtr, bmPtr, actPtr);\n }\n case PdfActionType.URI: {\n const actPtr = this.pdfiumModule.EPDFAction_CreateURI(docPtr, action.uri);\n if (!actPtr) return false;\n return !!this.pdfiumModule.EPDFBookmark_SetAction(docPtr, bmPtr, actPtr);\n }\n case PdfActionType.LaunchAppOrOpenFile: {\n const actPtr = this.withWString(\n action.path,\n (wptr) => this.pdfiumModule.EPDFAction_CreateLaunch(docPtr, wptr)\n );\n if (!actPtr) return false;\n return !!this.pdfiumModule.EPDFBookmark_SetAction(docPtr, bmPtr, actPtr);\n }\n case PdfActionType.RemoteGoto:\n return false;\n case PdfActionType.Unsupported:\n default:\n return false;\n }\n }\n /**\n * Apply a link target (action or destination) to a link annotation\n * @param docPtr - pointer to pdf document\n * @param annotationPtr - pointer to the link annotation\n * @param target - the link target to apply\n * @returns true if successful\n *\n * @private\n */\n applyLinkTarget(docPtr, annotationPtr, target) {\n if (target.type === "destination") {\n const destPtr = this.createLocalDestPtr(docPtr, target.destination);\n if (!destPtr) return false;\n const actPtr = this.pdfiumModule.EPDFAction_CreateGoTo(docPtr, destPtr);\n if (!actPtr) return false;\n return !!this.pdfiumModule.EPDFAnnot_SetAction(annotationPtr, actPtr);\n }\n const action = target.action;\n switch (action.type) {\n case PdfActionType.Goto: {\n const destPtr = this.createLocalDestPtr(docPtr, action.destination);\n if (!destPtr) return false;\n const actPtr = this.pdfiumModule.EPDFAction_CreateGoTo(docPtr, destPtr);\n if (!actPtr) return false;\n return !!this.pdfiumModule.EPDFAnnot_SetAction(annotationPtr, actPtr);\n }\n case PdfActionType.URI: {\n const actPtr = this.pdfiumModule.EPDFAction_CreateURI(docPtr, action.uri);\n if (!actPtr) return false;\n return !!this.pdfiumModule.EPDFAnnot_SetAction(annotationPtr, actPtr);\n }\n case PdfActionType.LaunchAppOrOpenFile: {\n const actPtr = this.withWString(\n action.path,\n (wptr) => this.pdfiumModule.EPDFAction_CreateLaunch(docPtr, wptr)\n );\n if (!actPtr) return false;\n return !!this.pdfiumModule.EPDFAnnot_SetAction(annotationPtr, actPtr);\n }\n case PdfActionType.RemoteGoto:\n case PdfActionType.Unsupported:\n default:\n return false;\n }\n }\n /**\n * Read pdf action from pdf document\n * @param docPtr - pointer to pdf document object\n * @param actionPtr - pointer to pdf action object\n * @returns pdf action object\n *\n * @private\n */\n readPdfAction(docPtr, actionPtr) {\n const actionType = this.pdfiumModule.FPDFAction_GetType(actionPtr);\n let action;\n switch (actionType) {\n case PdfActionType.Unsupported:\n action = {\n type: PdfActionType.Unsupported\n };\n break;\n case PdfActionType.Goto:\n {\n const destinationPtr = this.pdfiumModule.FPDFAction_GetDest(docPtr, actionPtr);\n if (destinationPtr) {\n const destination = this.readPdfDestination(docPtr, destinationPtr);\n action = {\n type: PdfActionType.Goto,\n destination\n };\n } else {\n action = {\n type: PdfActionType.Unsupported\n };\n }\n }\n break;\n case PdfActionType.RemoteGoto:\n {\n action = {\n type: PdfActionType.Unsupported\n };\n }\n break;\n case PdfActionType.URI:\n {\n const uri = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFAction_GetURIPath(\n docPtr,\n actionPtr,\n buffer,\n bufferLength\n );\n },\n this.pdfiumModule.pdfium.UTF8ToString\n );\n action = {\n type: PdfActionType.URI,\n uri\n };\n }\n break;\n case PdfActionType.LaunchAppOrOpenFile:\n {\n const path = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFAction_GetFilePath(actionPtr, buffer, bufferLength);\n },\n this.pdfiumModule.pdfium.UTF8ToString\n );\n action = {\n type: PdfActionType.LaunchAppOrOpenFile,\n path\n };\n }\n break;\n }\n return action;\n }\n /**\n * Read pdf destination object\n * @param docPtr - pointer to pdf document object\n * @param destinationPtr - pointer to pdf destination\n * @returns pdf destination object\n *\n * @private\n */\n readPdfDestination(docPtr, destinationPtr) {\n const pageIndex = this.pdfiumModule.FPDFDest_GetDestPageIndex(docPtr, destinationPtr);\n const maxParmamsCount = 4;\n const paramsCountPtr = this.memoryManager.malloc(maxParmamsCount);\n const paramsPtr = this.memoryManager.malloc(maxParmamsCount * 4);\n const zoomMode = this.pdfiumModule.FPDFDest_GetView(\n destinationPtr,\n paramsCountPtr,\n paramsPtr\n );\n const paramsCount = this.pdfiumModule.pdfium.getValue(paramsCountPtr, "i32");\n const view = [];\n for (let i = 0; i < paramsCount; i++) {\n const paramPtr = paramsPtr + i * 4;\n view.push(this.pdfiumModule.pdfium.getValue(paramPtr, "float"));\n }\n this.memoryManager.free(paramsCountPtr);\n this.memoryManager.free(paramsPtr);\n if (zoomMode === PdfZoomMode.XYZ) {\n const hasXPtr = this.memoryManager.malloc(1);\n const hasYPtr = this.memoryManager.malloc(1);\n const hasZPtr = this.memoryManager.malloc(1);\n const xPtr = this.memoryManager.malloc(4);\n const yPtr = this.memoryManager.malloc(4);\n const zPtr = this.memoryManager.malloc(4);\n const isSucceed = this.pdfiumModule.FPDFDest_GetLocationInPage(\n destinationPtr,\n hasXPtr,\n hasYPtr,\n hasZPtr,\n xPtr,\n yPtr,\n zPtr\n );\n if (isSucceed) {\n const hasX = this.pdfiumModule.pdfium.getValue(hasXPtr, "i8");\n const hasY = this.pdfiumModule.pdfium.getValue(hasYPtr, "i8");\n const hasZ = this.pdfiumModule.pdfium.getValue(hasZPtr, "i8");\n const x = hasX ? this.pdfiumModule.pdfium.getValue(xPtr, "float") : 0;\n const y = hasY ? this.pdfiumModule.pdfium.getValue(yPtr, "float") : 0;\n const zoom = hasZ ? this.pdfiumModule.pdfium.getValue(zPtr, "float") : 0;\n this.memoryManager.free(hasXPtr);\n this.memoryManager.free(hasYPtr);\n this.memoryManager.free(hasZPtr);\n this.memoryManager.free(xPtr);\n this.memoryManager.free(yPtr);\n this.memoryManager.free(zPtr);\n return {\n pageIndex,\n zoom: {\n mode: zoomMode,\n params: {\n x,\n y,\n zoom\n }\n },\n view\n };\n }\n this.memoryManager.free(hasXPtr);\n this.memoryManager.free(hasYPtr);\n this.memoryManager.free(hasZPtr);\n this.memoryManager.free(xPtr);\n this.memoryManager.free(yPtr);\n this.memoryManager.free(zPtr);\n return {\n pageIndex,\n zoom: {\n mode: zoomMode,\n params: {\n x: 0,\n y: 0,\n zoom: 0\n }\n },\n view\n };\n }\n return {\n pageIndex,\n zoom: {\n mode: zoomMode\n },\n view\n };\n }\n /**\n * Read attachmet from pdf document\n * @param docPtr - pointer to pdf document object\n * @param index - index of attachment\n * @returns attachment content\n *\n * @private\n */\n readPdfAttachment(docPtr, index) {\n const attachmentPtr = this.pdfiumModule.FPDFDoc_GetAttachment(docPtr, index);\n const name = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFAttachment_GetName(attachmentPtr, buffer, bufferLength);\n },\n this.pdfiumModule.pdfium.UTF16ToString\n );\n const description = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.EPDFAttachment_GetDescription(attachmentPtr, buffer, bufferLength);\n },\n this.pdfiumModule.pdfium.UTF16ToString\n );\n const mimeType = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFAttachment_GetSubtype(attachmentPtr, buffer, bufferLength);\n },\n this.pdfiumModule.pdfium.UTF16ToString\n );\n const creationDate = this.getAttachmentDate(attachmentPtr, "CreationDate");\n const checksum = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFAttachment_GetStringValue(\n attachmentPtr,\n "Checksum",\n buffer,\n bufferLength\n );\n },\n this.pdfiumModule.pdfium.UTF16ToString\n );\n const size = this.getAttachmentNumber(attachmentPtr, "Size");\n return {\n index,\n name,\n description,\n mimeType,\n size,\n creationDate,\n checksum\n };\n }\n /**\n * Convert coordinate of point from device coordinate to page coordinate\n * @param doc - pdf document object\n * @param page - pdf page infor\n * @param position - position of point\n * @returns converted position\n *\n * @private\n */\n convertDevicePointToPagePoint(doc, page, position) {\n const DW = page.size.width;\n const DH = page.size.height;\n const r = doc.normalizedRotation ? 0 : page.rotation & 3;\n if (r === 0) {\n return { x: position.x, y: DH - position.y };\n }\n if (r === 1) {\n return { x: position.y, y: position.x };\n }\n if (r === 2) {\n return { x: DW - position.x, y: position.y };\n }\n {\n return { x: DH - position.y, y: DW - position.x };\n }\n }\n /**\n * Convert coordinate of point from page coordinate to device coordinate\n * @param doc - pdf document object\n * @param page - pdf page infor\n * @param position - position of point\n * @returns converted position\n *\n * @private\n */\n convertPagePointToDevicePoint(doc, page, position) {\n const DW = page.size.width;\n const DH = page.size.height;\n const r = doc.normalizedRotation ? 0 : page.rotation & 3;\n if (r === 0) {\n return { x: position.x, y: DH - position.y };\n }\n if (r === 1) {\n return { x: position.y, y: position.x };\n }\n if (r === 2) {\n return { x: DW - position.x, y: position.y };\n }\n {\n return { x: DW - position.y, y: DH - position.x };\n }\n }\n /**\n * Convert coordinate of rectangle from page coordinate to device coordinate\n * @param doc - pdf document object\n * @param page - pdf page infor\n * @param pagePtr - pointer to pdf page object\n * @param pageRect - rectangle that needs to be converted\n * @returns converted rectangle\n *\n * @private\n */\n convertPageRectToDeviceRect(doc, page, pageRect) {\n const { x, y } = this.convertPagePointToDevicePoint(doc, page, {\n x: pageRect.left,\n y: pageRect.top\n });\n const rect = {\n origin: {\n x,\n y\n },\n size: {\n width: Math.abs(pageRect.right - pageRect.left),\n height: Math.abs(pageRect.top - pageRect.bottom)\n }\n };\n return rect;\n }\n /**\n * Read the appearance stream of annotation\n * @param annotationPtr - pointer to pdf annotation\n * @param mode - appearance mode\n * @returns appearance stream\n *\n * @private\n */\n readPageAnnoAppearanceStreams(annotationPtr) {\n return {\n normal: this.readPageAnnoAppearanceStream(annotationPtr, AppearanceMode.Normal),\n rollover: this.readPageAnnoAppearanceStream(annotationPtr, AppearanceMode.Rollover),\n down: this.readPageAnnoAppearanceStream(annotationPtr, AppearanceMode.Down)\n };\n }\n /**\n * Read the appearance stream of annotation\n * @param annotationPtr - pointer to pdf annotation\n * @param mode - appearance mode\n * @returns appearance stream\n *\n * @private\n */\n readPageAnnoAppearanceStream(annotationPtr, mode = AppearanceMode.Normal) {\n const utf16Length = this.pdfiumModule.FPDFAnnot_GetAP(annotationPtr, mode, 0, 0);\n const bytesCount = (utf16Length + 1) * 2;\n const bufferPtr = this.memoryManager.malloc(bytesCount);\n this.pdfiumModule.FPDFAnnot_GetAP(annotationPtr, mode, bufferPtr, bytesCount);\n const ap = this.pdfiumModule.pdfium.UTF16ToString(bufferPtr);\n this.memoryManager.free(bufferPtr);\n return ap;\n }\n /**\n * Set the appearance stream of annotation\n * @param annotationPtr - pointer to pdf annotation\n * @param mode - appearance mode\n * @param apContent - appearance stream content (null to remove)\n * @returns whether the appearance stream was set successfully\n *\n * @private\n */\n setPageAnnoAppearanceStream(annotationPtr, mode = AppearanceMode.Normal, apContent) {\n const bytes = 2 * (apContent.length + 1);\n const ptr = this.memoryManager.malloc(bytes);\n try {\n this.pdfiumModule.pdfium.stringToUTF16(apContent, ptr, bytes);\n const ok = this.pdfiumModule.FPDFAnnot_SetAP(annotationPtr, mode, ptr);\n return !!ok;\n } finally {\n this.memoryManager.free(ptr);\n }\n }\n /**\n * Set the rect of specified annotation\n * @param doc - pdf document object\n * @param page - page info that the annotation is belonged to\n * @param annotationPtr - pointer to annotation object\n * @param rect - target rectangle\n * @returns whether the rect is setted\n *\n * @private\n */\n setPageAnnoRect(doc, page, annotPtr, rect) {\n const x0d = Math.floor(rect.origin.x);\n const y0d = Math.floor(rect.origin.y);\n const x1d = Math.floor(rect.origin.x + rect.size.width);\n const y1d = Math.floor(rect.origin.y + rect.size.height);\n const TL = this.convertDevicePointToPagePoint(doc, page, { x: x0d, y: y0d });\n const TR = this.convertDevicePointToPagePoint(doc, page, { x: x1d, y: y0d });\n const BR = this.convertDevicePointToPagePoint(doc, page, { x: x1d, y: y1d });\n const BL = this.convertDevicePointToPagePoint(doc, page, { x: x0d, y: y1d });\n let left = Math.min(TL.x, TR.x, BR.x, BL.x);\n let right = Math.max(TL.x, TR.x, BR.x, BL.x);\n let bottom = Math.min(TL.y, TR.y, BR.y, BL.y);\n let top = Math.max(TL.y, TR.y, BR.y, BL.y);\n if (left > right) [left, right] = [right, left];\n if (bottom > top) [bottom, top] = [top, bottom];\n const ptr = this.memoryManager.malloc(16);\n const pdf = this.pdfiumModule.pdfium;\n pdf.setValue(ptr + 0, left, "float");\n pdf.setValue(ptr + 4, top, "float");\n pdf.setValue(ptr + 8, right, "float");\n pdf.setValue(ptr + 12, bottom, "float");\n const ok = this.pdfiumModule.FPDFAnnot_SetRect(annotPtr, ptr);\n this.memoryManager.free(ptr);\n return !!ok;\n }\n /**\n * Read the rectangle of annotation\n * @param annotationPtr - pointer to pdf annotation\n * @returns rectangle of annotation\n *\n * @private\n */\n readPageAnnoRect(annotationPtr) {\n const pageRectPtr = this.memoryManager.malloc(4 * 4);\n const pageRect = {\n left: 0,\n top: 0,\n right: 0,\n bottom: 0\n };\n if (this.pdfiumModule.EPDFAnnot_GetRect(annotationPtr, pageRectPtr)) {\n pageRect.left = this.pdfiumModule.pdfium.getValue(pageRectPtr, "float");\n pageRect.top = this.pdfiumModule.pdfium.getValue(pageRectPtr + 4, "float");\n pageRect.right = this.pdfiumModule.pdfium.getValue(pageRectPtr + 8, "float");\n pageRect.bottom = this.pdfiumModule.pdfium.getValue(pageRectPtr + 12, "float");\n }\n this.memoryManager.free(pageRectPtr);\n return pageRect;\n }\n /**\n * Get highlight rects for a specific character range (for search highlighting)\n * @param doc - pdf document object\n * @param page - pdf page info\n * @param pagePtr - pointer to pdf page\n * @param textPagePtr - pointer to pdf text page\n * @param startIndex - starting character index\n * @param charCount - number of characters in the range\n * @returns array of rectangles for highlighting the specified character range\n *\n * @private\n */\n getHighlightRects(doc, page, textPagePtr, startIndex, charCount) {\n const rectsCount = this.pdfiumModule.FPDFText_CountRects(textPagePtr, startIndex, charCount);\n const highlightRects = [];\n const l = this.memoryManager.malloc(8);\n const t = this.memoryManager.malloc(8);\n const r = this.memoryManager.malloc(8);\n const b = this.memoryManager.malloc(8);\n for (let i = 0; i < rectsCount; i++) {\n const ok = this.pdfiumModule.FPDFText_GetRect(textPagePtr, i, l, t, r, b);\n if (!ok) continue;\n const left = this.pdfiumModule.pdfium.getValue(l, "double");\n const top = this.pdfiumModule.pdfium.getValue(t, "double");\n const right = this.pdfiumModule.pdfium.getValue(r, "double");\n const bottom = this.pdfiumModule.pdfium.getValue(b, "double");\n const p1 = this.convertPagePointToDevicePoint(doc, page, { x: left, y: top });\n const p2 = this.convertPagePointToDevicePoint(doc, page, { x: right, y: top });\n const p3 = this.convertPagePointToDevicePoint(doc, page, { x: right, y: bottom });\n const p4 = this.convertPagePointToDevicePoint(doc, page, { x: left, y: bottom });\n const xs = [p1.x, p2.x, p3.x, p4.x];\n const ys = [p1.y, p2.y, p3.y, p4.y];\n const x = Math.min(...xs);\n const y = Math.min(...ys);\n const width = Math.max(...xs) - x;\n const height = Math.max(...ys) - y;\n highlightRects.push({\n origin: { x, y },\n size: { width: Math.ceil(width), height: Math.ceil(height) }\n });\n }\n this.memoryManager.free(l);\n this.memoryManager.free(t);\n this.memoryManager.free(r);\n this.memoryManager.free(b);\n return highlightRects;\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.searchAllPages}\n *\n * Runs inside the worker.\n * Emits per-page progress: { page, results }\n *\n * @public\n */\n searchInPage(doc, page, keyword, flags) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "searchInPage", doc, page, keyword, flags);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `SearchInPage`, "Begin", `${doc.id}-${page.index}`);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `PreparePrintDocument`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "Document is not open"\n });\n }\n const length = 2 * (keyword.length + 1);\n const keywordPtr = this.memoryManager.malloc(length);\n this.pdfiumModule.pdfium.stringToUTF16(keyword, keywordPtr, length);\n try {\n const results = this.searchAllInPage(doc, ctx, page, keywordPtr, flags);\n return PdfTaskHelper.resolve(results);\n } finally {\n this.memoryManager.free(keywordPtr);\n }\n }\n /**\n * Get annotations for multiple pages in a single batch.\n * Emits progress per page for streaming updates.\n *\n * @param doc - PDF document\n * @param pages - Array of pages to process\n * @returns Task with results keyed by page index, with per-page progress\n *\n * @public\n */\n getAnnotationsBatch(doc, pages) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getAnnotationsBatch", doc.id, pages.length);\n const task = new Task();\n queueMicrotask(() => {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetAnnotationsBatch", "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n task.reject({ code: PdfErrorCode.DocNotOpen, message: "Document is not open" });\n return;\n }\n const results = {};\n const total = pages.length;\n for (let i = 0; i < pages.length; i++) {\n const page = pages[i];\n const annotations = this.readPageAnnotationsRaw(doc, ctx, page);\n results[page.index] = annotations;\n task.progress({\n pageIndex: page.index,\n result: annotations,\n completed: i + 1,\n total\n });\n }\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetAnnotationsBatch", "End", doc.id);\n task.resolve(results);\n });\n return task;\n }\n /**\n * Search across multiple pages in a single batch.\n * Emits progress per page for streaming updates.\n *\n * @param doc - PDF document\n * @param pages - Array of pages to search\n * @param keyword - Search keyword\n * @param flags - Search flags\n * @returns Task with results keyed by page index, with per-page progress\n *\n * @public\n */\n searchBatch(doc, pages, keyword, flags) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "searchBatch", doc.id, pages.length, keyword);\n const task = new Task();\n queueMicrotask(() => {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "SearchBatch", "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n task.reject({ code: PdfErrorCode.DocNotOpen, message: "Document is not open" });\n return;\n }\n const length = 2 * (keyword.length + 1);\n const keywordPtr = this.memoryManager.malloc(length);\n this.pdfiumModule.pdfium.stringToUTF16(keyword, keywordPtr, length);\n try {\n const results = {};\n const total = pages.length;\n for (let i = 0; i < pages.length; i++) {\n const page = pages[i];\n const pageResults = this.searchAllInPage(doc, ctx, page, keywordPtr, flags);\n results[page.index] = pageResults;\n task.progress({\n pageIndex: page.index,\n result: pageResults,\n completed: i + 1,\n total\n });\n }\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "SearchBatch", "End", doc.id);\n task.resolve(results);\n } finally {\n this.memoryManager.free(keywordPtr);\n }\n });\n return task;\n }\n /**\n * Extract word-aligned context for a search hit.\n *\n * @param fullText full UTF-16 page text (fetch this once per page!)\n * @param start index of 1st char that matched\n * @param count number of chars in the match\n * @param windowChars minimum context chars to keep left & right\n */\n buildContext(fullText, start, count, windowChars = 30) {\n const WORD_BREAK = /[\\s\\u00A0.,;:!?()\\[\\]{}<>/\\\\\\-"\'`"”\\u2013\\u2014]/;\n const findWordStart = (index) => {\n while (index > 0 && !WORD_BREAK.test(fullText[index - 1])) index--;\n return index;\n };\n const findWordEnd = (index) => {\n while (index < fullText.length && !WORD_BREAK.test(fullText[index])) index++;\n return index;\n };\n let left = start;\n while (left > 0 && WORD_BREAK.test(fullText[left - 1])) left--;\n let collected = 0;\n while (left > 0 && collected < windowChars) {\n left--;\n if (!WORD_BREAK.test(fullText[left])) collected++;\n }\n left = findWordStart(left);\n let right = start + count;\n while (right < fullText.length && WORD_BREAK.test(fullText[right])) right++;\n collected = 0;\n while (right < fullText.length && collected < windowChars) {\n if (!WORD_BREAK.test(fullText[right])) collected++;\n right++;\n }\n right = findWordEnd(right);\n const before = fullText.slice(left, start).replace(/\\s+/g, " ").trimStart();\n const match = fullText.slice(start, start + count);\n const after = fullText.slice(start + count, right).replace(/\\s+/g, " ").trimEnd();\n return {\n before: this.tidy(before),\n match: this.tidy(match),\n after: this.tidy(after),\n truncatedLeft: left > 0,\n truncatedRight: right < fullText.length\n };\n }\n /**\n * Tidy the text to remove any non-printable characters and whitespace\n * @param s - text to tidy\n * @returns tidied text\n *\n * @private\n */\n tidy(s) {\n return s.replace(/-\\uFFFE\\s*/g, "").replace(/[\\uFFFE\\u00AD\\u200B\\u2060\\uFEFF]/g, "").replace(/\\s+/g, " ");\n }\n /**\n * Search for all occurrences of a keyword on a single page\n * This method efficiently loads the page only once and finds all matches\n *\n * @param docPtr - pointer to pdf document\n * @param page - pdf page object\n * @param pageIndex - index of the page\n * @param keywordPtr - pointer to the search keyword\n * @param flag - search flags\n * @returns array of search results on this page\n *\n * @private\n */\n searchAllInPage(doc, ctx, page, keywordPtr, flag) {\n return ctx.borrowPage(page.index, (pageCtx) => {\n const textPagePtr = pageCtx.getTextPage();\n const total = this.pdfiumModule.FPDFText_CountChars(textPagePtr);\n const bufPtr = this.memoryManager.malloc(2 * (total + 1));\n this.pdfiumModule.FPDFText_GetText(textPagePtr, 0, total, bufPtr);\n const fullText = this.pdfiumModule.pdfium.UTF16ToString(bufPtr);\n this.memoryManager.free(bufPtr);\n const pageResults = [];\n const searchHandle = this.pdfiumModule.FPDFText_FindStart(\n textPagePtr,\n keywordPtr,\n flag,\n 0\n // Start from the beginning of the page\n );\n while (this.pdfiumModule.FPDFText_FindNext(searchHandle)) {\n const charIndex = this.pdfiumModule.FPDFText_GetSchResultIndex(searchHandle);\n const charCount = this.pdfiumModule.FPDFText_GetSchCount(searchHandle);\n const rects = this.getHighlightRects(doc, page, textPagePtr, charIndex, charCount);\n const context = this.buildContext(fullText, charIndex, charCount);\n pageResults.push({\n pageIndex: page.index,\n charIndex,\n charCount,\n rects,\n context\n });\n }\n this.pdfiumModule.FPDFText_FindClose(searchHandle);\n return pageResults;\n });\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.preparePrintDocument}\n *\n * Prepares a PDF document for printing with specified options.\n * Creates a new document with selected pages and optionally removes annotations\n * for optimal printing performance.\n *\n * @public\n */\n preparePrintDocument(doc, options) {\n const { includeAnnotations = true, pageRange = null } = options ?? {};\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "preparePrintDocument", doc, options);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `PreparePrintDocument`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `PreparePrintDocument`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "Document is not open"\n });\n }\n const printDocPtr = this.pdfiumModule.FPDF_CreateNewDocument();\n if (!printDocPtr) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `PreparePrintDocument`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantCreateNewDoc,\n message: "Cannot create print document"\n });\n }\n try {\n const sanitizedPageRange = this.sanitizePageRange(pageRange, doc.pageCount);\n if (!this.pdfiumModule.FPDF_ImportPages(\n printDocPtr,\n ctx.docPtr,\n sanitizedPageRange ?? "",\n 0\n // Insert at beginning\n )) {\n this.pdfiumModule.FPDF_CloseDocument(printDocPtr);\n this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, "Failed to import pages for printing");\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `PreparePrintDocument`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantImportPages,\n message: "Failed to import pages for printing"\n });\n }\n if (!includeAnnotations) {\n const removalResult = this.removeAnnotationsFromPrintDocument(printDocPtr);\n if (!removalResult.success) {\n this.pdfiumModule.FPDF_CloseDocument(printDocPtr);\n this.logger.error(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `Failed to remove annotations: ${removalResult.error}`\n );\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `PreparePrintDocument`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: `Failed to prepare print document: ${removalResult.error}`\n });\n }\n this.logger.debug(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `Removed ${removalResult.annotationsRemoved} annotations from ${removalResult.pagesProcessed} pages`\n );\n }\n const buffer = this.saveDocument(printDocPtr);\n this.pdfiumModule.FPDF_CloseDocument(printDocPtr);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `PreparePrintDocument`, "End", doc.id);\n return PdfTaskHelper.resolve(buffer);\n } catch (error) {\n if (printDocPtr) {\n this.pdfiumModule.FPDF_CloseDocument(printDocPtr);\n }\n this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, "preparePrintDocument failed", error);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `PreparePrintDocument`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: error instanceof Error ? error.message : "Failed to prepare print document"\n });\n }\n }\n /**\n * Removes all annotations from a print document using fast raw annotation functions.\n * This method is optimized for performance by avoiding full page loading.\n *\n * @param printDocPtr - Pointer to the print document\n * @returns Result object with success status and statistics\n *\n * @private\n */\n removeAnnotationsFromPrintDocument(printDocPtr) {\n let totalAnnotationsRemoved = 0;\n let pagesProcessed = 0;\n try {\n const pageCount = this.pdfiumModule.FPDF_GetPageCount(printDocPtr);\n for (let pageIndex = 0; pageIndex < pageCount; pageIndex++) {\n const annotCount = this.pdfiumModule.EPDFPage_GetAnnotCountRaw(printDocPtr, pageIndex);\n if (annotCount <= 0) {\n pagesProcessed++;\n continue;\n }\n let annotationsRemovedFromPage = 0;\n for (let annotIndex = annotCount - 1; annotIndex >= 0; annotIndex--) {\n const removed = this.pdfiumModule.EPDFPage_RemoveAnnotRaw(\n printDocPtr,\n pageIndex,\n annotIndex\n );\n if (removed) {\n annotationsRemovedFromPage++;\n totalAnnotationsRemoved++;\n } else {\n this.logger.warn(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `Failed to remove annotation ${annotIndex} from page ${pageIndex}`\n );\n }\n }\n if (annotationsRemovedFromPage > 0) {\n const pagePtr = this.pdfiumModule.FPDF_LoadPage(printDocPtr, pageIndex);\n if (pagePtr) {\n this.pdfiumModule.FPDFPage_GenerateContent(pagePtr);\n this.pdfiumModule.FPDF_ClosePage(pagePtr);\n }\n }\n pagesProcessed++;\n }\n return {\n success: true,\n annotationsRemoved: totalAnnotationsRemoved,\n pagesProcessed\n };\n } catch (error) {\n return {\n success: false,\n annotationsRemoved: totalAnnotationsRemoved,\n pagesProcessed,\n error: error instanceof Error ? error.message : "Unknown error during annotation removal"\n };\n }\n }\n /**\n * Sanitizes and validates a page range string.\n * Ensures page numbers are within valid bounds and properly formatted.\n *\n * @param pageRange - Page range string (e.g., "1,3,5-7") or null for all pages\n * @param totalPages - Total number of pages in the document\n * @returns Sanitized page range string or null for all pages\n *\n * @private\n */\n sanitizePageRange(pageRange, totalPages) {\n if (!pageRange || pageRange.trim() === "") {\n return null;\n }\n try {\n const sanitized = [];\n const parts = pageRange.split(",");\n for (const part of parts) {\n const trimmed = part.trim();\n if (trimmed.includes("-")) {\n const [startStr, endStr] = trimmed.split("-").map((s) => s.trim());\n const start = parseInt(startStr, 10);\n const end = parseInt(endStr, 10);\n if (isNaN(start) || isNaN(end)) {\n this.logger.warn(LOG_SOURCE$1, LOG_CATEGORY$1, `Invalid range: ${trimmed}`);\n continue;\n }\n const validStart = Math.max(1, Math.min(start, totalPages));\n const validEnd = Math.max(1, Math.min(end, totalPages));\n for (let i = validStart; i <= validEnd; i++) {\n if (!sanitized.includes(i)) {\n sanitized.push(i);\n }\n }\n } else {\n const pageNum = parseInt(trimmed, 10);\n if (isNaN(pageNum)) {\n this.logger.warn(LOG_SOURCE$1, LOG_CATEGORY$1, `Invalid page number: ${trimmed}`);\n continue;\n }\n const validPageNum = Math.max(1, Math.min(pageNum, totalPages));\n if (!sanitized.includes(validPageNum)) {\n sanitized.push(validPageNum);\n }\n }\n }\n if (sanitized.length === 0) {\n this.logger.warn(LOG_SOURCE$1, LOG_CATEGORY$1, "No valid pages in range, using all pages");\n return null;\n }\n sanitized.sort((a, b) => a - b);\n const optimized = [];\n let rangeStart = sanitized[0];\n let rangeEnd = sanitized[0];\n for (let i = 1; i < sanitized.length; i++) {\n if (sanitized[i] === rangeEnd + 1) {\n rangeEnd = sanitized[i];\n } else {\n if (rangeStart === rangeEnd) {\n optimized.push(rangeStart.toString());\n } else if (rangeEnd - rangeStart === 1) {\n optimized.push(rangeStart.toString());\n optimized.push(rangeEnd.toString());\n } else {\n optimized.push(`${rangeStart}-${rangeEnd}`);\n }\n rangeStart = sanitized[i];\n rangeEnd = sanitized[i];\n }\n }\n if (rangeStart === rangeEnd) {\n optimized.push(rangeStart.toString());\n } else if (rangeEnd - rangeStart === 1) {\n optimized.push(rangeStart.toString());\n optimized.push(rangeEnd.toString());\n } else {\n optimized.push(`${rangeStart}-${rangeEnd}`);\n }\n const result = optimized.join(",");\n this.logger.debug(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `Sanitized page range: "${pageRange}" -> "${result}"`\n );\n return result;\n } catch (error) {\n this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, `Error sanitizing page range: ${error}`);\n return null;\n }\n }\n}\nconst LOG_SOURCE = "PdfiumNativeRunner";\nconst LOG_CATEGORY = "Worker";\nclass PdfiumNativeRunner {\n constructor(logger) {\n this.native = null;\n this.activeTasks = /* @__PURE__ */ new Map();\n this.logger = logger ?? new NoopLogger();\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "PdfiumNativeRunner created");\n }\n /**\n * Initialize PDFium with WASM binary\n */\n async prepare(wasmBinary, logger) {\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "Preparing PDFium...");\n try {\n const module = await init({ wasmBinary });\n this.native = new PdfiumNative(module, { logger: logger ?? this.logger });\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "PDFium initialized successfully");\n } catch (error) {\n this.logger.error(LOG_SOURCE, LOG_CATEGORY, "Failed to initialize PDFium:", error);\n throw error;\n }\n }\n /**\n * Start listening for messages\n */\n listen() {\n self.onmessage = (evt) => {\n this.handle(evt);\n };\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "Listening for messages");\n }\n /**\n * Handle incoming messages\n */\n handle(evt) {\n const request = evt.data;\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "Received message:", request.type);\n try {\n switch (request.type) {\n case "init":\n this.handleInit(request);\n break;\n case "execute":\n this.handleExecute(request);\n break;\n default:\n this.logger.warn(LOG_SOURCE, LOG_CATEGORY, "Unknown message type:", request.type);\n }\n } catch (error) {\n this.logger.error(LOG_SOURCE, LOG_CATEGORY, "Error handling message:", error);\n this.respond({\n id: request.id,\n type: "error",\n error: {\n type: "reject",\n reason: { code: PdfErrorCode.Unknown, message: String(error) }\n }\n });\n }\n }\n /**\n * Handle initialization request\n */\n async handleInit(request) {\n if (!request.wasmUrl) {\n this.respond({\n id: request.id,\n type: "error",\n error: {\n type: "reject",\n reason: { code: PdfErrorCode.Unknown, message: "Missing wasmUrl" }\n }\n });\n return;\n }\n try {\n const response = await fetch(request.wasmUrl);\n const wasmBinary = await response.arrayBuffer();\n await this.prepare(wasmBinary);\n this.respond({\n id: request.id,\n type: "ready"\n });\n } catch (error) {\n this.respond({\n id: request.id,\n type: "error",\n error: {\n type: "reject",\n reason: { code: PdfErrorCode.Unknown, message: String(error) }\n }\n });\n }\n }\n /**\n * Handle method execution request\n */\n async handleExecute(request) {\n if (!this.native) {\n this.respond({\n id: request.id,\n type: "error",\n error: {\n type: "reject",\n reason: { code: PdfErrorCode.NotReady, message: "PDFium not initialized" }\n }\n });\n return;\n }\n if (!request.method) {\n this.respond({\n id: request.id,\n type: "error",\n error: {\n type: "reject",\n reason: { code: PdfErrorCode.Unknown, message: "Missing method name" }\n }\n });\n return;\n }\n const method = request.method;\n const args = request.args ?? [];\n if (!(method in this.native) || typeof this.native[method] !== "function") {\n this.respond({\n id: request.id,\n type: "error",\n error: {\n type: "reject",\n reason: { code: PdfErrorCode.NotSupport, message: `Method ${method} not supported` }\n }\n });\n return;\n }\n try {\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, `Executing method: ${method}`);\n const result = this.native[method](...args);\n if (result && typeof result === "object" && "wait" in result) {\n const task = result;\n this.activeTasks.set(request.id, task);\n task.onProgress((progress) => {\n this.respond({\n id: request.id,\n type: "progress",\n progress\n });\n });\n task.wait(\n (data) => {\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, `Method ${method} resolved`);\n this.respond({\n id: request.id,\n type: "result",\n data\n });\n this.activeTasks.delete(request.id);\n },\n (error) => {\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, `Method ${method} failed:`, error);\n this.respond({\n id: request.id,\n type: "error",\n error\n });\n this.activeTasks.delete(request.id);\n }\n );\n } else {\n this.respond({\n id: request.id,\n type: "result",\n data: result\n });\n }\n } catch (error) {\n this.logger.error(LOG_SOURCE, LOG_CATEGORY, `Error executing ${method}:`, error);\n this.respond({\n id: request.id,\n type: "error",\n error: {\n type: "reject",\n reason: { code: PdfErrorCode.Unknown, message: String(error) }\n }\n });\n }\n }\n /**\n * Send response back to main thread\n */\n respond(response) {\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "Sending response:", response.type);\n self.postMessage(response);\n }\n /**\n * Ready notification\n */\n ready() {\n this.listen();\n this.respond({\n id: "0",\n type: "ready"\n });\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "Runner is ready");\n }\n}\nclass PdfiumEngineRunner extends PdfiumNativeRunner {\n /**\n * Create an instance of PdfiumEngineRunner\n * @param wasmBinary - wasm binary that contains the pdfium wasm file\n * @param logger - optional logger instance\n * @param fontFallback - optional font fallback configuration\n */\n constructor(wasmBinary, logger, fontFallback) {\n super(logger);\n this.wasmBinary = wasmBinary;\n this.fontFallback = fontFallback;\n }\n /**\n * Initialize runner\n */\n async prepare() {\n const wasmBinary = this.wasmBinary;\n const wasmModule = await init({ wasmBinary });\n this.native = new PdfiumNative(wasmModule, {\n logger: this.logger,\n fontFallback: this.fontFallback\n });\n this.ready();\n }\n}\nconst fonts$6 = [\n { file: "NotoSansJP-Thin.otf", weight: 100 },\n { file: "NotoSansJP-Light.otf", weight: 300 },\n { file: "NotoSansJP-DemiLight.otf", weight: 350 },\n { file: "NotoSansJP-Regular.otf", weight: 400 },\n { file: "NotoSansJP-Medium.otf", weight: 500 },\n { file: "NotoSansJP-Bold.otf", weight: 700 },\n { file: "NotoSansJP-Black.otf", weight: 900 }\n];\nconst fonts$5 = [\n { file: "NotoSansKR-Thin.otf", weight: 100 },\n { file: "NotoSansKR-Light.otf", weight: 300 },\n { file: "NotoSansKR-DemiLight.otf", weight: 350 },\n { file: "NotoSansKR-Regular.otf", weight: 400 },\n { file: "NotoSansKR-Medium.otf", weight: 500 },\n { file: "NotoSansKR-Bold.otf", weight: 700 },\n { file: "NotoSansKR-Black.otf", weight: 900 }\n];\nconst fonts$4 = [\n { file: "NotoSansHans-Light.otf", weight: 300 },\n { file: "NotoSansHans-DemiLight.otf", weight: 350 },\n { file: "NotoSansHans-Regular.otf", weight: 400 },\n { file: "NotoSansHans-Medium.otf", weight: 500 },\n { file: "NotoSansHans-Bold.otf", weight: 700 }\n];\nconst fonts$3 = [\n { file: "NotoSansHant-Thin.otf", weight: 100 },\n { file: "NotoSansHant-Light.otf", weight: 300 },\n { file: "NotoSansHant-DemiLight.otf", weight: 350 },\n { file: "NotoSansHant-Regular.otf", weight: 400 },\n { file: "NotoSansHant-Medium.otf", weight: 500 },\n { file: "NotoSansHant-Bold.otf", weight: 700 },\n { file: "NotoSansHant-Black.otf", weight: 900 }\n];\nconst fonts$2 = [\n { file: "NotoNaskhArabic-Regular.ttf", weight: 400 },\n { file: "NotoNaskhArabic-Bold.ttf", weight: 700 }\n];\nconst fonts$1 = [\n { file: "NotoSansHebrew-Regular.ttf", weight: 400 },\n { file: "NotoSansHebrew-Bold.ttf", weight: 700 }\n];\nconst fonts = [\n // Thin (100)\n { file: "NotoSans-Thin.ttf", weight: 100 },\n { file: "NotoSans-ThinItalic.ttf", weight: 100, italic: true },\n // ExtraLight (200)\n { file: "NotoSans-ExtraLight.ttf", weight: 200 },\n { file: "NotoSans-ExtraLightItalic.ttf", weight: 200, italic: true },\n // Light (300)\n { file: "NotoSans-Light.ttf", weight: 300 },\n { file: "NotoSans-LightItalic.ttf", weight: 300, italic: true },\n // Regular (400)\n { file: "NotoSans-Regular.ttf", weight: 400 },\n { file: "NotoSans-Italic.ttf", weight: 400, italic: true },\n // Medium (500)\n { file: "NotoSans-Medium.ttf", weight: 500 },\n { file: "NotoSans-MediumItalic.ttf", weight: 500, italic: true },\n // SemiBold (600)\n { file: "NotoSans-SemiBold.ttf", weight: 600 },\n { file: "NotoSans-SemiBoldItalic.ttf", weight: 600, italic: true },\n // Bold (700)\n { file: "NotoSans-Bold.ttf", weight: 700 },\n { file: "NotoSans-BoldItalic.ttf", weight: 700, italic: true },\n // ExtraBold (800)\n { file: "NotoSans-ExtraBold.ttf", weight: 800 },\n { file: "NotoSans-ExtraBoldItalic.ttf", weight: 800, italic: true },\n // Black (900)\n { file: "NotoSans-Black.ttf", weight: 900 },\n { file: "NotoSans-BlackItalic.ttf", weight: 900, italic: true }\n];\nfunction buildCdnUrls(version = "latest") {\n return {\n jp: `https://cdn.jsdelivr.net/npm/@embedpdf/fonts-jp@${version}/fonts`,\n kr: `https://cdn.jsdelivr.net/npm/@embedpdf/fonts-kr@${version}/fonts`,\n sc: `https://cdn.jsdelivr.net/npm/@embedpdf/fonts-sc@${version}/fonts`,\n tc: `https://cdn.jsdelivr.net/npm/@embedpdf/fonts-tc@${version}/fonts`,\n arabic: `https://cdn.jsdelivr.net/npm/@embedpdf/fonts-arabic@${version}/fonts`,\n hebrew: `https://cdn.jsdelivr.net/npm/@embedpdf/fonts-hebrew@${version}/fonts`,\n latin: `https://cdn.jsdelivr.net/npm/@embedpdf/fonts-latin@${version}/fonts`\n };\n}\nfunction toFontVariants(fonts2, baseUrl) {\n return fonts2.map((f) => ({\n url: `${baseUrl}/${f.file}`,\n weight: f.weight,\n italic: f.italic\n }));\n}\nfunction buildCdnFontConfig(urls) {\n return {\n fonts: {\n [FontCharset.SHIFTJIS]: toFontVariants(fonts$6, urls.jp),\n [FontCharset.HANGEUL]: toFontVariants(fonts$5, urls.kr),\n [FontCharset.GB2312]: toFontVariants(fonts$4, urls.sc),\n [FontCharset.CHINESEBIG5]: toFontVariants(fonts$3, urls.tc),\n [FontCharset.ARABIC]: toFontVariants(fonts$2, urls.arabic),\n [FontCharset.HEBREW]: toFontVariants(fonts$1, urls.hebrew),\n [FontCharset.CYRILLIC]: toFontVariants(fonts, urls.latin),\n [FontCharset.GREEK]: toFontVariants(fonts, urls.latin),\n [FontCharset.VIETNAMESE]: toFontVariants(fonts, urls.latin)\n }\n };\n}\nconst FONT_CDN_URLS = buildCdnUrls("latest");\nconst cdnFontConfig = buildCdnFontConfig(FONT_CDN_URLS);\nlet runner = null;\nself.onmessage = async (event) => {\n const { type, wasmUrl, logger: serializedLogger, fontFallback } = event.data;\n if (type === "wasmInit" && wasmUrl && !runner) {\n try {\n const response = await fetch(wasmUrl);\n const wasmBinary = await response.arrayBuffer();\n const logger = serializedLogger ? deserializeLogger(serializedLogger) : void 0;\n const effectiveFontFallback = fontFallback === null ? void 0 : fontFallback ?? cdnFontConfig;\n runner = new PdfiumEngineRunner(wasmBinary, logger, effectiveFontFallback);\n await runner.prepare();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n self.postMessage({ type: "wasmError", error: message });\n }\n }\n};\n'],{type:"application/javascript"})),{type:"module"}),u=new l(d,{wasmUrl:t,logger:a,fontFallback:s}),c=URL.createObjectURL(new Blob(['async function encodeImage(imageData, imageType, quality) {\n if (typeof OffscreenCanvas === "undefined") {\n throw new Error("OffscreenCanvas is not available in this worker environment");\n }\n const { data, width, height } = imageData;\n const imgData = new ImageData(new Uint8ClampedArray(data), width, height);\n const canvas = new OffscreenCanvas(width, height);\n const ctx = canvas.getContext("2d");\n if (!ctx) {\n throw new Error("Failed to get 2D context from OffscreenCanvas");\n }\n ctx.putImageData(imgData, 0, 0);\n return canvas.convertToBlob({ type: imageType, quality });\n}\nself.onmessage = async (event) => {\n const request = event.data;\n if (request.type !== "encode") {\n return;\n }\n try {\n const { imageData, imageType, quality } = request.data;\n const blob = await encodeImage(imageData, imageType, quality);\n const response = {\n id: request.id,\n type: "result",\n data: blob\n };\n self.postMessage(response);\n } catch (error) {\n const response = {\n id: request.id,\n type: "error",\n data: {\n message: error instanceof Error ? error.message : String(error)\n }\n };\n self.postMessage(response);\n }\n};\n'],{type:"application/javascript"})),m=new p(i??2,c,a);return new n(u,{imageConverter:e(m),logger:a})}export{m as createPdfiumEngine}; diff --git a/src/components/BootstrapBlazor.EmbedPDF/wwwroot/worker-engine-DZTIUfA0.js b/src/components/BootstrapBlazor.EmbedPDF/wwwroot/worker-engine-DZTIUfA0.js deleted file mode 100644 index 8418e5fa..00000000 --- a/src/components/BootstrapBlazor.EmbedPDF/wwwroot/worker-engine-DZTIUfA0.js +++ /dev/null @@ -1 +0,0 @@ -import{P as n,c as e}from"./browser-BISJ9naB-DfsGA31F.js";import{P as t,N as r,T as o,s as a}from"./embedpdf-DX_zb2Zx.js";const i="RemoteExecutor",s="Worker",d=class n{constructor(e,d){this.worker=e,this.pendingRequests=new Map,this.requestCounter=0,this.handleMessage=n=>{const e=n.data;if("ready"===e.type)return this.logger.debug(i,s,"Worker is ready"),void this.readyTask.resolve(!0);const r=this.pendingRequests.get(e.id);if(r)switch(e.type){case"result":this.logger.debug(i,s,`Received result for ${e.id}`),r.resolve(e.data),this.pendingRequests.delete(e.id);break;case"error":this.logger.debug(i,s,`Received error for ${e.id}:`,e.error),e.error?r.fail(e.error):r.reject({code:t.Unknown,message:"Unknown error"}),this.pendingRequests.delete(e.id);break;case"progress":this.logger.debug(i,s,`Received progress for ${e.id}`),r.progress(e.progress)}else this.logger.warn(i,s,`Received response for unknown request: ${e.id}`)},this.logger=d.logger??new r,this.worker.addEventListener("message",this.handleMessage),this.readyTask=new o,this.pendingRequests.set(n.READY_TASK_ID,this.readyTask),this.worker.postMessage({id:n.READY_TASK_ID,type:"wasmInit",wasmUrl:d.wasmUrl,logger:d.logger?a(d.logger):void 0,fontFallback:d.fontFallback}),this.logger.debug(i,s,"RemoteExecutor created")}generateId(){return`req-${Date.now()}-${this.requestCounter++}`}send(n,e){const r=this.generateId(),a=new o,d={id:r,type:"execute",method:n,args:e};return this.readyTask.wait(()=>{this.pendingRequests.set(r,a),this.logger.debug(i,s,`Sending ${n} request:`,r),this.worker.postMessage(d)},e=>{this.logger.error(i,s,`Worker init failed, rejecting ${n}:`,e),a.reject({code:t.Initialization,message:"Worker initialization failed"})}),a}destroy(){this.worker.removeEventListener("message",this.handleMessage),this.pendingRequests.forEach((e,t)=>{t!==n.READY_TASK_ID&&(e.abort("Worker destroyed"),this.logger.debug(i,s,`Aborted pending request: ${t}`))}),this.pendingRequests.clear(),this.worker.terminate(),this.logger.debug(i,s,"RemoteExecutor destroyed")}openDocumentBuffer(n,e){return this.send("openDocumentBuffer",[n,e])}getMetadata(n){return this.send("getMetadata",[n])}setMetadata(n,e){return this.send("setMetadata",[n,e])}getDocPermissions(n){return this.send("getDocPermissions",[n])}getDocUserPermissions(n){return this.send("getDocUserPermissions",[n])}getSignatures(n){return this.send("getSignatures",[n])}getBookmarks(n){return this.send("getBookmarks",[n])}setBookmarks(n,e){return this.send("setBookmarks",[n,e])}deleteBookmarks(n){return this.send("deleteBookmarks",[n])}renderPageRaw(n,e,t){return this.send("renderPageRaw",[n,e,t])}renderPageRect(n,e,t,r){return this.send("renderPageRect",[n,e,t,r])}renderThumbnailRaw(n,e,t){return this.send("renderThumbnailRaw",[n,e,t])}renderPageAnnotationRaw(n,e,t,r){return this.send("renderPageAnnotationRaw",[n,e,t,r])}getPageAnnotationsRaw(n,e){return this.send("getPageAnnotationsRaw",[n,e])}getPageAnnotations(n,e){return this.send("getPageAnnotations",[n,e])}createPageAnnotation(n,e,t,r){return this.send("createPageAnnotation",[n,e,t,r])}updatePageAnnotation(n,e,t){return this.send("updatePageAnnotation",[n,e,t])}removePageAnnotation(n,e,t){return this.send("removePageAnnotation",[n,e,t])}getPageTextRects(n,e){return this.send("getPageTextRects",[n,e])}searchInPage(n,e,t,r){return this.send("searchInPage",[n,e,t,r])}getAnnotationsBatch(n,e){return this.send("getAnnotationsBatch",[n,e])}searchBatch(n,e,t,r){return this.send("searchBatch",[n,e,t,r])}getAttachments(n){return this.send("getAttachments",[n])}addAttachment(n,e){return this.send("addAttachment",[n,e])}removeAttachment(n,e){return this.send("removeAttachment",[n,e])}readAttachmentContent(n,e){return this.send("readAttachmentContent",[n,e])}setFormFieldValue(n,e,t,r){return this.send("setFormFieldValue",[n,e,t,r])}flattenPage(n,e,t){return this.send("flattenPage",[n,e,t])}extractPages(n,e){return this.send("extractPages",[n,e])}extractText(n,e){return this.send("extractText",[n,e])}redactTextInRects(n,e,t,r){return this.send("redactTextInRects",[n,e,t,r])}applyRedaction(n,e,t){return this.send("applyRedaction",[n,e,t])}applyAllRedactions(n,e){return this.send("applyAllRedactions",[n,e])}flattenAnnotation(n,e,t){return this.send("flattenAnnotation",[n,e,t])}getTextSlices(n,e){return this.send("getTextSlices",[n,e])}getPageGlyphs(n,e){return this.send("getPageGlyphs",[n,e])}getPageGeometry(n,e){return this.send("getPageGeometry",[n,e])}getPageTextRuns(n,e){return this.send("getPageTextRuns",[n,e])}merge(n){return this.send("merge",[n])}mergePages(n){return this.send("mergePages",[n])}preparePrintDocument(n,e){return this.send("preparePrintDocument",[n,e])}saveAsCopy(n){return this.send("saveAsCopy",[n])}closeDocument(n){return this.send("closeDocument",[n])}closeAllDocuments(){return this.send("closeAllDocuments",[])}setDocumentEncryption(n,e,t,r){return this.send("setDocumentEncryption",[n,e,t,r])}removeEncryption(n){return this.send("removeEncryption",[n])}unlockOwnerPermissions(n,e){return this.send("unlockOwnerPermissions",[n,e])}isEncrypted(n){return this.send("isEncrypted",[n])}isOwnerUnlocked(n){return this.send("isOwnerUnlocked",[n])}};d.READY_TASK_ID="0";let l=d;const u="ImageEncoderPool",c="Encoder";class p{constructor(n=2,e,t){this.poolSize=n,this.workerUrl=e,this.workers=[],this.pendingTasks=new Map,this.nextWorkerId=0,this.requestCounter=0,this.logger=t??new r,this.initialize()}initialize(){this.logger.debug(u,c,`Creating worker pool with ${this.poolSize} workers`);for(let n=0;n{const a=this.getNextWorker();if(!a)return void o(new Error("No workers available in the pool"));const i=`encode-${Date.now()}-${this.requestCounter++}`;this.pendingTasks.set(i,{resolve:r,reject:o});const s={id:i,type:"encode",data:{imageData:{data:n.data,width:n.width,height:n.height},imageType:e,quality:t}};this.logger.debug(u,c,`Sending encoding request ${i} (${n.width}x${n.height})`),a.postMessage(s,[n.data.buffer])})}destroy(){this.logger.debug(u,c,"Destroying worker pool"),this.pendingTasks.forEach((n,e)=>{n.reject(new Error("Worker pool destroyed")),this.logger.debug(u,c,`Rejected pending task: ${e}`)}),this.pendingTasks.clear(),this.workers.forEach((n,e)=>{n.terminate(),this.logger.debug(u,c,`Worker ${e} terminated`)}),this.workers=[]}get activeWorkers(){return this.workers.length}get pendingTasksCount(){return this.pendingTasks.size}}function m(t,r){const o=r instanceof Object&&"debug"in r?{logger:r}:r||{},{logger:a,encoderPoolSize:i,fontFallback:s}=o,d=new Worker(URL.createObjectURL(new Blob(['var Rotation = /* @__PURE__ */ ((Rotation2) => {\n Rotation2[Rotation2["Degree0"] = 0] = "Degree0";\n Rotation2[Rotation2["Degree90"] = 1] = "Degree90";\n Rotation2[Rotation2["Degree180"] = 2] = "Degree180";\n Rotation2[Rotation2["Degree270"] = 3] = "Degree270";\n return Rotation2;\n})(Rotation || {});\nfunction toIntPos(p) {\n return { x: Math.floor(p.x), y: Math.floor(p.y) };\n}\nfunction toIntSize(s) {\n return { width: Math.ceil(s.width), height: Math.ceil(s.height) };\n}\nfunction toIntRect(r) {\n return {\n origin: toIntPos(r.origin),\n size: toIntSize(r.size)\n };\n}\nfunction swap(size) {\n const { width, height } = size;\n return {\n width: height,\n height: width\n };\n}\nfunction quadToRect(q) {\n const xs = [q.p1.x, q.p2.x, q.p3.x, q.p4.x];\n const ys = [q.p1.y, q.p2.y, q.p3.y, q.p4.y];\n return {\n origin: { x: Math.min(...xs), y: Math.min(...ys) },\n size: {\n width: Math.max(...xs) - Math.min(...xs),\n height: Math.max(...ys) - Math.min(...ys)\n }\n };\n}\nfunction rectToQuad(r) {\n return {\n p1: { x: r.origin.x, y: r.origin.y },\n p2: { x: r.origin.x + r.size.width, y: r.origin.y },\n p3: { x: r.origin.x + r.size.width, y: r.origin.y + r.size.height },\n p4: { x: r.origin.x, y: r.origin.y + r.size.height }\n };\n}\nfunction rotateRect(containerSize, rect, rotation) {\n let x = rect.origin.x;\n let y = rect.origin.y;\n let size = rect.size;\n switch (rotation) {\n case 0:\n break;\n case 1:\n x = containerSize.height - rect.origin.y - rect.size.height;\n y = rect.origin.x;\n size = swap(rect.size);\n break;\n case 2:\n x = containerSize.width - rect.origin.x - rect.size.width;\n y = containerSize.height - rect.origin.y - rect.size.height;\n break;\n case 3:\n x = rect.origin.y;\n y = containerSize.width - rect.origin.x - rect.size.width;\n size = swap(rect.size);\n break;\n }\n return {\n origin: {\n x,\n y\n },\n size: {\n width: size.width,\n height: size.height\n }\n };\n}\nfunction scaleRect(rect, scaleFactor) {\n return {\n origin: {\n x: rect.origin.x * scaleFactor,\n y: rect.origin.y * scaleFactor\n },\n size: {\n width: rect.size.width * scaleFactor,\n height: rect.size.height * scaleFactor\n }\n };\n}\nfunction transformRect(containerSize, rect, rotation, scaleFactor) {\n return scaleRect(rotateRect(containerSize, rect, rotation), scaleFactor);\n}\nfunction buildUserToDeviceMatrix(rect, rotation, outW, outH) {\n const L = rect.origin.x;\n const B = rect.origin.y;\n const W = rect.size.width;\n const H = rect.size.height;\n const sx0 = outW / W;\n const sy0 = outH / H;\n const sx90 = outW / H;\n const sy90 = outH / W;\n switch (rotation) {\n case 0:\n return { a: sx0, b: 0, c: 0, d: sy0, e: -sx0 * L, f: -sy0 * B };\n case 3:\n return { a: 0, b: -sy90, c: sx90, d: 0, e: -sx90 * B, f: sy90 * (L + W) };\n case 2:\n return { a: -sx0, b: 0, c: 0, d: -sy0, e: sx0 * (L + W), f: sy0 * (B + H) };\n case 1:\n return { a: 0, b: sy90, c: -sx90, d: 0, e: sx90 * (B + H), f: -sy90 * L };\n }\n}\nclass NoopLogger {\n /** {@inheritDoc Logger.isEnabled} */\n isEnabled() {\n return false;\n }\n /** {@inheritDoc Logger.debug} */\n debug() {\n }\n /** {@inheritDoc Logger.info} */\n info() {\n }\n /** {@inheritDoc Logger.warn} */\n warn() {\n }\n /** {@inheritDoc Logger.error} */\n error() {\n }\n /** {@inheritDoc Logger.perf} */\n perf() {\n }\n}\nclass ConsoleLogger {\n /** {@inheritDoc Logger.isEnabled} */\n isEnabled() {\n return true;\n }\n /** {@inheritDoc Logger.debug} */\n debug(source, category, ...args) {\n console.debug(`${source}.${category}`, ...args);\n }\n /** {@inheritDoc Logger.info} */\n info(source, category, ...args) {\n console.info(`${source}.${category}`, ...args);\n }\n /** {@inheritDoc Logger.warn} */\n warn(source, category, ...args) {\n console.warn(`${source}.${category}`, ...args);\n }\n /** {@inheritDoc Logger.error} */\n error(source, category, ...args) {\n console.error(`${source}.${category}`, ...args);\n }\n /** {@inheritDoc Logger.perf} */\n perf(source, category, event, phase, ...args) {\n console.info(`${source}.${category}.${event}.${phase}`, ...args);\n }\n}\nclass LevelLogger {\n /**\n * create new LevelLogger\n * @param logger - the original logger\n * @param level - log level that used for filtering, all logs lower than this level will be filtered out\n */\n constructor(logger, level) {\n this.logger = logger;\n this.level = level;\n }\n /** {@inheritDoc Logger.isEnabled} */\n isEnabled(level) {\n const levelMap = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3\n /* Error */\n };\n return this.level <= levelMap[level];\n }\n /** {@inheritDoc Logger.debug} */\n debug(source, category, ...args) {\n if (this.level <= 0) {\n this.logger.debug(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.info} */\n info(source, category, ...args) {\n if (this.level <= 1) {\n this.logger.info(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.warn} */\n warn(source, category, ...args) {\n if (this.level <= 2) {\n this.logger.warn(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.error} */\n error(source, category, ...args) {\n if (this.level <= 3) {\n this.logger.error(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.perf} */\n perf(source, category, event, phase, ...args) {\n this.logger.perf(source, category, event, phase, ...args);\n }\n}\nclass PerfLogger {\n /**\n * create new PerfLogger\n */\n constructor() {\n this.marks = /* @__PURE__ */ new Map();\n }\n /** {@inheritDoc Logger.isEnabled} */\n isEnabled() {\n return false;\n }\n /** {@inheritDoc Logger.debug} */\n debug(source, category, ...args) {\n }\n /** {@inheritDoc Logger.info} */\n info(source, category, ...args) {\n }\n /** {@inheritDoc Logger.warn} */\n warn(source, category, ...args) {\n }\n /** {@inheritDoc Logger.error} */\n error(source, category, ...args) {\n }\n /** {@inheritDoc Logger.perf} */\n perf(source, category, event, phase, identifier, ...args) {\n const markName = `${source}.${category}.${event}.${phase}.${identifier}`;\n switch (phase) {\n case "Begin":\n globalThis.performance.mark(markName, { detail: args });\n this.marks.set(`${source}.${category}.${event}.${identifier}`, Date.now());\n break;\n case "End":\n globalThis.performance.mark(markName, { detail: args });\n const measureName = `${source}.${category}.${event}.Measure.${identifier}`;\n const beginMark = `${source}.${category}.${event}.Begin.${identifier}`;\n globalThis.performance.measure(measureName, beginMark, markName);\n const startTime = this.marks.get(`${source}.${category}.${event}.${identifier}`);\n if (startTime) {\n const duration = Date.now() - startTime;\n console.info(`⏱️ ${source}.${category}.${event}.${identifier}: ${duration}ms`);\n this.marks.delete(`${source}.${category}.${event}.${identifier}`);\n }\n break;\n }\n }\n}\nclass AllLogger {\n /**\n * create new PerfLogger\n */\n constructor(loggers) {\n this.loggers = loggers;\n }\n /** {@inheritDoc Logger.isEnabled} */\n isEnabled(level) {\n return this.loggers.some((logger) => logger.isEnabled(level));\n }\n /** {@inheritDoc Logger.debug} */\n debug(source, category, ...args) {\n for (const logger of this.loggers) {\n logger.debug(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.info} */\n info(source, category, ...args) {\n for (const logger of this.loggers) {\n logger.info(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.warn} */\n warn(source, category, ...args) {\n for (const logger of this.loggers) {\n logger.warn(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.error} */\n error(source, category, ...args) {\n for (const logger of this.loggers) {\n logger.error(source, category, ...args);\n }\n }\n /** {@inheritDoc Logger.perf} */\n perf(source, category, event, phase, ...args) {\n for (const logger of this.loggers) {\n logger.perf(source, category, event, phase, ...args);\n }\n }\n}\nclass TaskAbortedError extends Error {\n constructor(reason) {\n super(`Task aborted: ${JSON.stringify(reason)}`);\n this.name = "TaskAbortedError";\n this.reason = reason;\n }\n}\nclass TaskRejectedError extends Error {\n constructor(reason) {\n super(`Task rejected: ${JSON.stringify(reason)}`);\n this.name = "TaskRejectedError";\n this.reason = reason;\n }\n}\nclass Task {\n constructor() {\n this.state = {\n stage: 0\n /* Pending */\n };\n this.resolvedCallbacks = [];\n this.rejectedCallbacks = [];\n this._promise = null;\n this.progressCbs = [];\n }\n /**\n * Convert task to promise\n * @returns promise that will be resolved when task is settled\n */\n toPromise() {\n if (!this._promise) {\n this._promise = new Promise((resolve, reject) => {\n this.wait(\n (result) => resolve(result),\n (error) => {\n if (error.type === "abort") {\n reject(new TaskAbortedError(error.reason));\n } else {\n reject(new TaskRejectedError(error.reason));\n }\n }\n );\n });\n }\n return this._promise;\n }\n /**\n * wait for task to be settled\n * @param resolvedCallback - callback for resolved value\n * @param rejectedCallback - callback for rejected value\n */\n wait(resolvedCallback, rejectedCallback) {\n switch (this.state.stage) {\n case 0:\n this.resolvedCallbacks.push(resolvedCallback);\n this.rejectedCallbacks.push(rejectedCallback);\n break;\n case 1:\n resolvedCallback(this.state.result);\n break;\n case 2:\n rejectedCallback({\n type: "reject",\n reason: this.state.reason\n });\n break;\n case 3:\n rejectedCallback({\n type: "abort",\n reason: this.state.reason\n });\n break;\n }\n }\n /**\n * resolve task with specific result\n * @param result - result value\n */\n resolve(result) {\n if (this.state.stage === 0) {\n this.state = {\n stage: 1,\n result\n };\n for (const resolvedCallback of this.resolvedCallbacks) {\n try {\n resolvedCallback(result);\n } catch (e) {\n }\n }\n this.resolvedCallbacks = [];\n this.rejectedCallbacks = [];\n }\n }\n /**\n * reject task with specific reason\n * @param reason - abort reason\n *\n */\n reject(reason) {\n if (this.state.stage === 0) {\n this.state = {\n stage: 2,\n reason\n };\n for (const rejectedCallback of this.rejectedCallbacks) {\n try {\n rejectedCallback({\n type: "reject",\n reason\n });\n } catch (e) {\n }\n }\n this.resolvedCallbacks = [];\n this.rejectedCallbacks = [];\n }\n }\n /**\n * abort task with specific reason\n * @param reason - abort reason\n */\n abort(reason) {\n if (this.state.stage === 0) {\n this.state = {\n stage: 3,\n reason\n };\n for (const rejectedCallback of this.rejectedCallbacks) {\n try {\n rejectedCallback({\n type: "abort",\n reason\n });\n } catch (e) {\n }\n }\n this.resolvedCallbacks = [];\n this.rejectedCallbacks = [];\n }\n }\n /**\n * fail task with a TaskError from another task\n * This is a convenience method for error propagation between tasks\n * @param error - TaskError from another task\n */\n fail(error) {\n if (error.type === "abort") {\n this.abort(error.reason);\n } else {\n this.reject(error.reason);\n }\n }\n /**\n * add a progress callback\n * @param cb - progress callback\n */\n onProgress(cb) {\n this.progressCbs.push(cb);\n }\n /**\n * call progress callback\n * @param p - progress value\n */\n progress(p) {\n for (const cb of this.progressCbs) cb(p);\n }\n /**\n * Static method to wait for all tasks to resolve\n * Returns a new task that resolves with an array of all results\n * Rejects immediately if any task fails\n *\n * @param tasks - array of tasks to wait for\n * @returns new task that resolves when all input tasks resolve\n * @public\n */\n static all(tasks) {\n const combinedTask = new Task();\n if (tasks.length === 0) {\n combinedTask.resolve([]);\n return combinedTask;\n }\n const results = new Array(tasks.length);\n let resolvedCount = 0;\n let isSettled = false;\n tasks.forEach((task, index) => {\n task.wait(\n (result) => {\n if (isSettled) return;\n results[index] = result;\n resolvedCount++;\n if (resolvedCount === tasks.length) {\n isSettled = true;\n combinedTask.resolve(results);\n }\n },\n (error) => {\n if (isSettled) return;\n isSettled = true;\n if (error.type === "abort") {\n combinedTask.abort(error.reason);\n } else {\n combinedTask.reject(error.reason);\n }\n }\n );\n });\n return combinedTask;\n }\n /**\n * Static method to wait for all tasks to settle (resolve, reject, or abort)\n * Always resolves with an array of settlement results\n *\n * @param tasks - array of tasks to wait for\n * @returns new task that resolves when all input tasks settle\n * @public\n */\n static allSettled(tasks) {\n const combinedTask = new Task();\n if (tasks.length === 0) {\n combinedTask.resolve([]);\n return combinedTask;\n }\n const results = new Array(tasks.length);\n let settledCount = 0;\n tasks.forEach((task, index) => {\n task.wait(\n (result) => {\n results[index] = { status: "resolved", value: result };\n settledCount++;\n if (settledCount === tasks.length) {\n combinedTask.resolve(results);\n }\n },\n (error) => {\n results[index] = {\n status: error.type === "abort" ? "aborted" : "rejected",\n reason: error.reason\n };\n settledCount++;\n if (settledCount === tasks.length) {\n combinedTask.resolve(results);\n }\n }\n );\n });\n return combinedTask;\n }\n /**\n * Static method that resolves/rejects with the first task that settles\n *\n * @param tasks - array of tasks to race\n * @returns new task that settles with the first input task that settles\n * @public\n */\n static race(tasks) {\n const combinedTask = new Task();\n if (tasks.length === 0) {\n combinedTask.reject("No tasks provided");\n return combinedTask;\n }\n let isSettled = false;\n tasks.forEach((task) => {\n task.wait(\n (result) => {\n if (isSettled) return;\n isSettled = true;\n combinedTask.resolve(result);\n },\n (error) => {\n if (isSettled) return;\n isSettled = true;\n if (error.type === "abort") {\n combinedTask.abort(error.reason);\n } else {\n combinedTask.reject(error.reason);\n }\n }\n );\n });\n return combinedTask;\n }\n /**\n * Utility to track progress of multiple tasks\n *\n * @param tasks - array of tasks to track\n * @param onProgress - callback called when any task completes\n * @returns new task that resolves when all input tasks resolve\n * @public\n */\n static withProgress(tasks, onProgress) {\n const combinedTask = Task.all(tasks);\n if (onProgress) {\n let completedCount = 0;\n tasks.forEach((task) => {\n task.wait(\n () => {\n completedCount++;\n onProgress(completedCount, tasks.length);\n },\n () => {\n completedCount++;\n onProgress(completedCount, tasks.length);\n }\n );\n });\n }\n return combinedTask;\n }\n}\nconst PdfSoftHyphenMarker = "­";\nconst PdfZeroWidthSpace = "​";\nconst PdfWordJoiner = "⁠";\nconst PdfBomOrZwnbsp = "\\uFEFF";\nconst PdfNonCharacterFFFE = "￾";\nconst PdfNonCharacterFFFF = "￿";\nconst PdfUnwantedTextMarkers = Object.freeze([\n PdfSoftHyphenMarker,\n PdfZeroWidthSpace,\n PdfWordJoiner,\n PdfBomOrZwnbsp,\n PdfNonCharacterFFFE,\n PdfNonCharacterFFFF\n]);\nconst PdfUnwantedTextRegex = new RegExp(`[${PdfUnwantedTextMarkers.join("")}]`, "g");\nfunction stripPdfUnwantedMarkers(text) {\n return text.replace(PdfUnwantedTextRegex, "");\n}\nvar PdfZoomMode = /* @__PURE__ */ ((PdfZoomMode2) => {\n PdfZoomMode2[PdfZoomMode2["Unknown"] = 0] = "Unknown";\n PdfZoomMode2[PdfZoomMode2["XYZ"] = 1] = "XYZ";\n PdfZoomMode2[PdfZoomMode2["FitPage"] = 2] = "FitPage";\n PdfZoomMode2[PdfZoomMode2["FitHorizontal"] = 3] = "FitHorizontal";\n PdfZoomMode2[PdfZoomMode2["FitVertical"] = 4] = "FitVertical";\n PdfZoomMode2[PdfZoomMode2["FitRectangle"] = 5] = "FitRectangle";\n PdfZoomMode2[PdfZoomMode2["FitBoundingBox"] = 6] = "FitBoundingBox";\n PdfZoomMode2[PdfZoomMode2["FitBoundingBoxHorizontal"] = 7] = "FitBoundingBoxHorizontal";\n PdfZoomMode2[PdfZoomMode2["FitBoundingBoxVertical"] = 8] = "FitBoundingBoxVertical";\n return PdfZoomMode2;\n})(PdfZoomMode || {});\nvar PdfTrappedStatus = /* @__PURE__ */ ((PdfTrappedStatus2) => {\n PdfTrappedStatus2[PdfTrappedStatus2["NotSet"] = 0] = "NotSet";\n PdfTrappedStatus2[PdfTrappedStatus2["True"] = 1] = "True";\n PdfTrappedStatus2[PdfTrappedStatus2["False"] = 2] = "False";\n PdfTrappedStatus2[PdfTrappedStatus2["Unknown"] = 3] = "Unknown";\n return PdfTrappedStatus2;\n})(PdfTrappedStatus || {});\nvar PdfStandardFont = /* @__PURE__ */ ((PdfStandardFont2) => {\n PdfStandardFont2[PdfStandardFont2["Unknown"] = -1] = "Unknown";\n PdfStandardFont2[PdfStandardFont2["Courier"] = 0] = "Courier";\n PdfStandardFont2[PdfStandardFont2["Courier_Bold"] = 1] = "Courier_Bold";\n PdfStandardFont2[PdfStandardFont2["Courier_BoldOblique"] = 2] = "Courier_BoldOblique";\n PdfStandardFont2[PdfStandardFont2["Courier_Oblique"] = 3] = "Courier_Oblique";\n PdfStandardFont2[PdfStandardFont2["Helvetica"] = 4] = "Helvetica";\n PdfStandardFont2[PdfStandardFont2["Helvetica_Bold"] = 5] = "Helvetica_Bold";\n PdfStandardFont2[PdfStandardFont2["Helvetica_BoldOblique"] = 6] = "Helvetica_BoldOblique";\n PdfStandardFont2[PdfStandardFont2["Helvetica_Oblique"] = 7] = "Helvetica_Oblique";\n PdfStandardFont2[PdfStandardFont2["Times_Roman"] = 8] = "Times_Roman";\n PdfStandardFont2[PdfStandardFont2["Times_Bold"] = 9] = "Times_Bold";\n PdfStandardFont2[PdfStandardFont2["Times_BoldItalic"] = 10] = "Times_BoldItalic";\n PdfStandardFont2[PdfStandardFont2["Times_Italic"] = 11] = "Times_Italic";\n PdfStandardFont2[PdfStandardFont2["Symbol"] = 12] = "Symbol";\n PdfStandardFont2[PdfStandardFont2["ZapfDingbats"] = 13] = "ZapfDingbats";\n return PdfStandardFont2;\n})(PdfStandardFont || {});\nvar PdfTextAlignment = /* @__PURE__ */ ((PdfTextAlignment2) => {\n PdfTextAlignment2[PdfTextAlignment2["Left"] = 0] = "Left";\n PdfTextAlignment2[PdfTextAlignment2["Center"] = 1] = "Center";\n PdfTextAlignment2[PdfTextAlignment2["Right"] = 2] = "Right";\n return PdfTextAlignment2;\n})(PdfTextAlignment || {});\nvar PdfBlendMode = /* @__PURE__ */ ((PdfBlendMode2) => {\n PdfBlendMode2[PdfBlendMode2["Normal"] = 0] = "Normal";\n PdfBlendMode2[PdfBlendMode2["Multiply"] = 1] = "Multiply";\n PdfBlendMode2[PdfBlendMode2["Screen"] = 2] = "Screen";\n PdfBlendMode2[PdfBlendMode2["Overlay"] = 3] = "Overlay";\n PdfBlendMode2[PdfBlendMode2["Darken"] = 4] = "Darken";\n PdfBlendMode2[PdfBlendMode2["Lighten"] = 5] = "Lighten";\n PdfBlendMode2[PdfBlendMode2["ColorDodge"] = 6] = "ColorDodge";\n PdfBlendMode2[PdfBlendMode2["ColorBurn"] = 7] = "ColorBurn";\n PdfBlendMode2[PdfBlendMode2["HardLight"] = 8] = "HardLight";\n PdfBlendMode2[PdfBlendMode2["SoftLight"] = 9] = "SoftLight";\n PdfBlendMode2[PdfBlendMode2["Difference"] = 10] = "Difference";\n PdfBlendMode2[PdfBlendMode2["Exclusion"] = 11] = "Exclusion";\n PdfBlendMode2[PdfBlendMode2["Hue"] = 12] = "Hue";\n PdfBlendMode2[PdfBlendMode2["Saturation"] = 13] = "Saturation";\n PdfBlendMode2[PdfBlendMode2["Color"] = 14] = "Color";\n PdfBlendMode2[PdfBlendMode2["Luminosity"] = 15] = "Luminosity";\n return PdfBlendMode2;\n})(PdfBlendMode || {});\nvar PdfStampFit = /* @__PURE__ */ ((PdfStampFit2) => {\n PdfStampFit2[PdfStampFit2["Contain"] = 0] = "Contain";\n PdfStampFit2[PdfStampFit2["Cover"] = 1] = "Cover";\n PdfStampFit2[PdfStampFit2["Stretch"] = 2] = "Stretch";\n return PdfStampFit2;\n})(PdfStampFit || {});\nvar PdfActionType = /* @__PURE__ */ ((PdfActionType2) => {\n PdfActionType2[PdfActionType2["Unsupported"] = 0] = "Unsupported";\n PdfActionType2[PdfActionType2["Goto"] = 1] = "Goto";\n PdfActionType2[PdfActionType2["RemoteGoto"] = 2] = "RemoteGoto";\n PdfActionType2[PdfActionType2["URI"] = 3] = "URI";\n PdfActionType2[PdfActionType2["LaunchAppOrOpenFile"] = 4] = "LaunchAppOrOpenFile";\n return PdfActionType2;\n})(PdfActionType || {});\nvar PdfAnnotationSubtype = /* @__PURE__ */ ((PdfAnnotationSubtype2) => {\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["UNKNOWN"] = 0] = "UNKNOWN";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["TEXT"] = 1] = "TEXT";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["LINK"] = 2] = "LINK";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["FREETEXT"] = 3] = "FREETEXT";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["LINE"] = 4] = "LINE";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["SQUARE"] = 5] = "SQUARE";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["CIRCLE"] = 6] = "CIRCLE";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["POLYGON"] = 7] = "POLYGON";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["POLYLINE"] = 8] = "POLYLINE";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["HIGHLIGHT"] = 9] = "HIGHLIGHT";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["UNDERLINE"] = 10] = "UNDERLINE";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["SQUIGGLY"] = 11] = "SQUIGGLY";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["STRIKEOUT"] = 12] = "STRIKEOUT";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["STAMP"] = 13] = "STAMP";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["CARET"] = 14] = "CARET";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["INK"] = 15] = "INK";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["POPUP"] = 16] = "POPUP";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["FILEATTACHMENT"] = 17] = "FILEATTACHMENT";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["SOUND"] = 18] = "SOUND";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["MOVIE"] = 19] = "MOVIE";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["WIDGET"] = 20] = "WIDGET";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["SCREEN"] = 21] = "SCREEN";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["PRINTERMARK"] = 22] = "PRINTERMARK";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["TRAPNET"] = 23] = "TRAPNET";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["WATERMARK"] = 24] = "WATERMARK";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["THREED"] = 25] = "THREED";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["RICHMEDIA"] = 26] = "RICHMEDIA";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["XFAWIDGET"] = 27] = "XFAWIDGET";\n PdfAnnotationSubtype2[PdfAnnotationSubtype2["REDACT"] = 28] = "REDACT";\n return PdfAnnotationSubtype2;\n})(PdfAnnotationSubtype || {});\nvar AppearanceMode = /* @__PURE__ */ ((AppearanceMode2) => {\n AppearanceMode2[AppearanceMode2["Normal"] = 0] = "Normal";\n AppearanceMode2[AppearanceMode2["Rollover"] = 1] = "Rollover";\n AppearanceMode2[AppearanceMode2["Down"] = 2] = "Down";\n return AppearanceMode2;\n})(AppearanceMode || {});\nvar PdfAnnotationIcon = /* @__PURE__ */ ((PdfAnnotationIcon2) => {\n PdfAnnotationIcon2[PdfAnnotationIcon2["Unknown"] = -1] = "Unknown";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Comment"] = 0] = "Comment";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Key"] = 1] = "Key";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Note"] = 2] = "Note";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Help"] = 3] = "Help";\n PdfAnnotationIcon2[PdfAnnotationIcon2["NewParagraph"] = 4] = "NewParagraph";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Paragraph"] = 5] = "Paragraph";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Insert"] = 6] = "Insert";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Graph"] = 7] = "Graph";\n PdfAnnotationIcon2[PdfAnnotationIcon2["PushPin"] = 8] = "PushPin";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Paperclip"] = 9] = "Paperclip";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Tag"] = 10] = "Tag";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Speaker"] = 11] = "Speaker";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Mic"] = 12] = "Mic";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Approved"] = 13] = "Approved";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Experimental"] = 14] = "Experimental";\n PdfAnnotationIcon2[PdfAnnotationIcon2["NotApproved"] = 15] = "NotApproved";\n PdfAnnotationIcon2[PdfAnnotationIcon2["AsIs"] = 16] = "AsIs";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Expired"] = 17] = "Expired";\n PdfAnnotationIcon2[PdfAnnotationIcon2["NotForPublicRelease"] = 18] = "NotForPublicRelease";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Confidential"] = 19] = "Confidential";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Final"] = 20] = "Final";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Sold"] = 21] = "Sold";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Departmental"] = 22] = "Departmental";\n PdfAnnotationIcon2[PdfAnnotationIcon2["ForComment"] = 23] = "ForComment";\n PdfAnnotationIcon2[PdfAnnotationIcon2["TopSecret"] = 24] = "TopSecret";\n PdfAnnotationIcon2[PdfAnnotationIcon2["Draft"] = 25] = "Draft";\n PdfAnnotationIcon2[PdfAnnotationIcon2["ForPublicRelease"] = 26] = "ForPublicRelease";\n return PdfAnnotationIcon2;\n})(PdfAnnotationIcon || {});\nvar PdfAnnotationLineEnding = /* @__PURE__ */ ((PdfAnnotationLineEnding2) => {\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["None"] = 0] = "None";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["Square"] = 1] = "Square";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["Circle"] = 2] = "Circle";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["Diamond"] = 3] = "Diamond";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["OpenArrow"] = 4] = "OpenArrow";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["ClosedArrow"] = 5] = "ClosedArrow";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["Butt"] = 6] = "Butt";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["ROpenArrow"] = 7] = "ROpenArrow";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["RClosedArrow"] = 8] = "RClosedArrow";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["Slash"] = 9] = "Slash";\n PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["Unknown"] = 10] = "Unknown";\n return PdfAnnotationLineEnding2;\n})(PdfAnnotationLineEnding || {});\nvar PdfAnnotationReplyType = /* @__PURE__ */ ((PdfAnnotationReplyType2) => {\n PdfAnnotationReplyType2[PdfAnnotationReplyType2["Unknown"] = 0] = "Unknown";\n PdfAnnotationReplyType2[PdfAnnotationReplyType2["Reply"] = 1] = "Reply";\n PdfAnnotationReplyType2[PdfAnnotationReplyType2["Group"] = 2] = "Group";\n return PdfAnnotationReplyType2;\n})(PdfAnnotationReplyType || {});\nvar PDF_FORM_FIELD_TYPE = /* @__PURE__ */ ((PDF_FORM_FIELD_TYPE2) => {\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["UNKNOWN"] = 0] = "UNKNOWN";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["PUSHBUTTON"] = 1] = "PUSHBUTTON";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["CHECKBOX"] = 2] = "CHECKBOX";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["RADIOBUTTON"] = 3] = "RADIOBUTTON";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["COMBOBOX"] = 4] = "COMBOBOX";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["LISTBOX"] = 5] = "LISTBOX";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["TEXTFIELD"] = 6] = "TEXTFIELD";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["SIGNATURE"] = 7] = "SIGNATURE";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA"] = 8] = "XFA";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA_CHECKBOX"] = 9] = "XFA_CHECKBOX";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA_COMBOBOX"] = 10] = "XFA_COMBOBOX";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA_IMAGEFIELD"] = 11] = "XFA_IMAGEFIELD";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA_LISTBOX"] = 12] = "XFA_LISTBOX";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA_PUSHBUTTON"] = 13] = "XFA_PUSHBUTTON";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA_SIGNATURE"] = 14] = "XFA_SIGNATURE";\n PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA_TEXTFIELD"] = 15] = "XFA_TEXTFIELD";\n return PDF_FORM_FIELD_TYPE2;\n})(PDF_FORM_FIELD_TYPE || {});\nvar PdfAnnotationColorType = /* @__PURE__ */ ((PdfAnnotationColorType2) => {\n PdfAnnotationColorType2[PdfAnnotationColorType2["Color"] = 0] = "Color";\n PdfAnnotationColorType2[PdfAnnotationColorType2["InteriorColor"] = 1] = "InteriorColor";\n PdfAnnotationColorType2[PdfAnnotationColorType2["OverlayColor"] = 2] = "OverlayColor";\n return PdfAnnotationColorType2;\n})(PdfAnnotationColorType || {});\nvar PdfAnnotationBorderStyle = /* @__PURE__ */ ((PdfAnnotationBorderStyle2) => {\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["UNKNOWN"] = 0] = "UNKNOWN";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["SOLID"] = 1] = "SOLID";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["DASHED"] = 2] = "DASHED";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["BEVELED"] = 3] = "BEVELED";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["INSET"] = 4] = "INSET";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["UNDERLINE"] = 5] = "UNDERLINE";\n PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["CLOUDY"] = 6] = "CLOUDY";\n return PdfAnnotationBorderStyle2;\n})(PdfAnnotationBorderStyle || {});\nvar PdfPageObjectType = /* @__PURE__ */ ((PdfPageObjectType2) => {\n PdfPageObjectType2[PdfPageObjectType2["UNKNOWN"] = 0] = "UNKNOWN";\n PdfPageObjectType2[PdfPageObjectType2["TEXT"] = 1] = "TEXT";\n PdfPageObjectType2[PdfPageObjectType2["PATH"] = 2] = "PATH";\n PdfPageObjectType2[PdfPageObjectType2["IMAGE"] = 3] = "IMAGE";\n PdfPageObjectType2[PdfPageObjectType2["SHADING"] = 4] = "SHADING";\n PdfPageObjectType2[PdfPageObjectType2["FORM"] = 5] = "FORM";\n return PdfPageObjectType2;\n})(PdfPageObjectType || {});\nconst PdfAnnotationFlagName = Object.freeze({\n [\n 1\n /* INVISIBLE */\n ]: "invisible",\n [\n 2\n /* HIDDEN */\n ]: "hidden",\n [\n 4\n /* PRINT */\n ]: "print",\n [\n 8\n /* NO_ZOOM */\n ]: "noZoom",\n [\n 16\n /* NO_ROTATE */\n ]: "noRotate",\n [\n 32\n /* NO_VIEW */\n ]: "noView",\n [\n 64\n /* READ_ONLY */\n ]: "readOnly",\n [\n 128\n /* LOCKED */\n ]: "locked",\n [\n 256\n /* TOGGLE_NOVIEW */\n ]: "toggleNoView"\n});\nconst PdfAnnotationFlagValue = Object.entries(\n PdfAnnotationFlagName\n).reduce(\n (acc, [bit, name]) => {\n acc[name] = Number(bit);\n return acc;\n },\n {}\n);\nfunction flagsToNames(raw) {\n return Object.keys(PdfAnnotationFlagName).filter((flag) => (raw & flag) !== 0).map((flag) => PdfAnnotationFlagName[flag]);\n}\nfunction namesToFlags(names) {\n return names.reduce(\n (mask, name) => mask | PdfAnnotationFlagValue[name],\n 0\n /* NONE */\n );\n}\nvar FontCharset = /* @__PURE__ */ ((FontCharset2) => {\n FontCharset2[FontCharset2["ANSI"] = 0] = "ANSI";\n FontCharset2[FontCharset2["DEFAULT"] = 1] = "DEFAULT";\n FontCharset2[FontCharset2["SYMBOL"] = 2] = "SYMBOL";\n FontCharset2[FontCharset2["SHIFTJIS"] = 128] = "SHIFTJIS";\n FontCharset2[FontCharset2["HANGEUL"] = 129] = "HANGEUL";\n FontCharset2[FontCharset2["GB2312"] = 134] = "GB2312";\n FontCharset2[FontCharset2["CHINESEBIG5"] = 136] = "CHINESEBIG5";\n FontCharset2[FontCharset2["GREEK"] = 161] = "GREEK";\n FontCharset2[FontCharset2["VIETNAMESE"] = 163] = "VIETNAMESE";\n FontCharset2[FontCharset2["HEBREW"] = 177] = "HEBREW";\n FontCharset2[FontCharset2["ARABIC"] = 178] = "ARABIC";\n FontCharset2[FontCharset2["CYRILLIC"] = 204] = "CYRILLIC";\n FontCharset2[FontCharset2["THAI"] = 222] = "THAI";\n FontCharset2[FontCharset2["EASTERNEUROPEAN"] = 238] = "EASTERNEUROPEAN";\n return FontCharset2;\n})(FontCharset || {});\nvar PdfPageFlattenFlag = /* @__PURE__ */ ((PdfPageFlattenFlag2) => {\n PdfPageFlattenFlag2[PdfPageFlattenFlag2["Display"] = 0] = "Display";\n PdfPageFlattenFlag2[PdfPageFlattenFlag2["Print"] = 1] = "Print";\n return PdfPageFlattenFlag2;\n})(PdfPageFlattenFlag || {});\nvar PdfErrorCode = /* @__PURE__ */ ((PdfErrorCode2) => {\n PdfErrorCode2[PdfErrorCode2["Ok"] = 0] = "Ok";\n PdfErrorCode2[PdfErrorCode2["Unknown"] = 1] = "Unknown";\n PdfErrorCode2[PdfErrorCode2["NotFound"] = 2] = "NotFound";\n PdfErrorCode2[PdfErrorCode2["WrongFormat"] = 3] = "WrongFormat";\n PdfErrorCode2[PdfErrorCode2["Password"] = 4] = "Password";\n PdfErrorCode2[PdfErrorCode2["Security"] = 5] = "Security";\n PdfErrorCode2[PdfErrorCode2["PageError"] = 6] = "PageError";\n PdfErrorCode2[PdfErrorCode2["XFALoad"] = 7] = "XFALoad";\n PdfErrorCode2[PdfErrorCode2["XFALayout"] = 8] = "XFALayout";\n PdfErrorCode2[PdfErrorCode2["Cancelled"] = 9] = "Cancelled";\n PdfErrorCode2[PdfErrorCode2["Initialization"] = 10] = "Initialization";\n PdfErrorCode2[PdfErrorCode2["NotReady"] = 11] = "NotReady";\n PdfErrorCode2[PdfErrorCode2["NotSupport"] = 12] = "NotSupport";\n PdfErrorCode2[PdfErrorCode2["LoadDoc"] = 13] = "LoadDoc";\n PdfErrorCode2[PdfErrorCode2["DocNotOpen"] = 14] = "DocNotOpen";\n PdfErrorCode2[PdfErrorCode2["CantCloseDoc"] = 15] = "CantCloseDoc";\n PdfErrorCode2[PdfErrorCode2["CantCreateNewDoc"] = 16] = "CantCreateNewDoc";\n PdfErrorCode2[PdfErrorCode2["CantImportPages"] = 17] = "CantImportPages";\n PdfErrorCode2[PdfErrorCode2["CantCreateAnnot"] = 18] = "CantCreateAnnot";\n PdfErrorCode2[PdfErrorCode2["CantSetAnnotRect"] = 19] = "CantSetAnnotRect";\n PdfErrorCode2[PdfErrorCode2["CantSetAnnotContent"] = 20] = "CantSetAnnotContent";\n PdfErrorCode2[PdfErrorCode2["CantRemoveInkList"] = 21] = "CantRemoveInkList";\n PdfErrorCode2[PdfErrorCode2["CantAddInkStoke"] = 22] = "CantAddInkStoke";\n PdfErrorCode2[PdfErrorCode2["CantReadAttachmentSize"] = 23] = "CantReadAttachmentSize";\n PdfErrorCode2[PdfErrorCode2["CantReadAttachmentContent"] = 24] = "CantReadAttachmentContent";\n PdfErrorCode2[PdfErrorCode2["CantFocusAnnot"] = 25] = "CantFocusAnnot";\n PdfErrorCode2[PdfErrorCode2["CantSelectText"] = 26] = "CantSelectText";\n PdfErrorCode2[PdfErrorCode2["CantSelectOption"] = 27] = "CantSelectOption";\n PdfErrorCode2[PdfErrorCode2["CantCheckField"] = 28] = "CantCheckField";\n PdfErrorCode2[PdfErrorCode2["CantSetAnnotString"] = 29] = "CantSetAnnotString";\n return PdfErrorCode2;\n})(PdfErrorCode || {});\nclass PdfTaskHelper {\n /**\n * Create a task\n * @returns new task\n */\n static create() {\n return new Task();\n }\n /**\n * Create a task that has been resolved with value\n * @param result - resolved value\n * @returns resolved task\n */\n static resolve(result) {\n const task = new Task();\n task.resolve(result);\n return task;\n }\n /**\n * Create a task that has been rejected with error\n * @param reason - rejected error\n * @returns rejected task\n */\n static reject(reason) {\n const task = new Task();\n task.reject(reason);\n return task;\n }\n /**\n * Create a task that has been aborted with error\n * @param reason - aborted error\n * @returns aborted task\n */\n static abort(reason) {\n const task = new Task();\n task.reject(reason);\n return task;\n }\n}\nfunction pdfColorToWebColor(c) {\n const clamp = (n) => Math.max(0, Math.min(255, n));\n const toHex = (n) => clamp(n).toString(16).padStart(2, "0");\n return `#${toHex(c.red)}${toHex(c.green)}${toHex(c.blue)}`;\n}\nfunction webColorToPdfColor(color) {\n if (/^#?[0-9a-f]{3}$/i.test(color)) {\n color = color.replace(/^#?([0-9a-f])([0-9a-f])([0-9a-f])$/i, "#$1$1$2$2$3$3").toLowerCase();\n }\n const [, r, g, b] = /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(color) ?? (() => {\n throw new Error(`Invalid hex colour: "${color}"`);\n })();\n return {\n red: parseInt(r, 16),\n green: parseInt(g, 16),\n blue: parseInt(b, 16)\n };\n}\nfunction pdfAlphaToWebOpacity(alpha) {\n const clamp = (n) => Math.max(0, Math.min(255, n));\n return clamp(alpha) / 255;\n}\nfunction webOpacityToPdfAlpha(opacity) {\n const clamp = (n, hi = 255) => Math.max(0, Math.min(hi, n));\n return clamp(Math.round(opacity * 255));\n}\nfunction pdfDateToDate(pdf) {\n if (!(pdf == null ? void 0 : pdf.startsWith("D:")) || pdf.length < 16) return;\n const y = +pdf.slice(2, 6);\n const mo = +pdf.slice(6, 8) - 1;\n const d = +pdf.slice(8, 10);\n const H = +pdf.slice(10, 12);\n const M = +pdf.slice(12, 14);\n const S = +pdf.slice(14, 16);\n return new Date(Date.UTC(y, mo, d, H, M, S));\n}\nfunction dateToPdfDate(date = /* @__PURE__ */ new Date()) {\n const z = (n, len = 2) => n.toString().padStart(len, "0");\n const YYYY = date.getUTCFullYear();\n const MM = z(date.getUTCMonth() + 1);\n const DD = z(date.getUTCDate());\n const HH = z(date.getUTCHours());\n const mm = z(date.getUTCMinutes());\n const SS = z(date.getUTCSeconds());\n return `D:${YYYY}${MM}${DD}${HH}${mm}${SS}`;\n}\nconst TEXT_ALIGNMENT_INFOS = Object.freeze([\n { id: PdfTextAlignment.Left, label: "Left", css: "left" },\n { id: PdfTextAlignment.Center, label: "Center", css: "center" },\n { id: PdfTextAlignment.Right, label: "Right", css: "right" }\n]);\nTEXT_ALIGNMENT_INFOS.reduce(\n (m, info) => {\n m[info.id] = info;\n return m;\n },\n {}\n);\nTEXT_ALIGNMENT_INFOS.reduce(\n (m, info) => {\n m[info.css] = info.id;\n return m;\n },\n {}\n);\nTEXT_ALIGNMENT_INFOS.map((info) => ({\n value: info.id,\n label: info.label\n}));\nvar PdfStandardFontFamily = /* @__PURE__ */ ((PdfStandardFontFamily2) => {\n PdfStandardFontFamily2["Courier"] = "Courier";\n PdfStandardFontFamily2["Helvetica"] = "Helvetica";\n PdfStandardFontFamily2["Times"] = "Times";\n PdfStandardFontFamily2["Symbol"] = "Symbol";\n PdfStandardFontFamily2["ZapfDingbats"] = "ZapfDingbats";\n PdfStandardFontFamily2["Unknown"] = "Unknown";\n return PdfStandardFontFamily2;\n})(PdfStandardFontFamily || {});\nPdfStandardFont.Helvetica;\nconst HELVETICA_DESC = {\n id: PdfStandardFont.Helvetica,\n family: "Helvetica",\n bold: false,\n italic: false,\n label: "Helvetica",\n css: "Helvetica, Arial, sans-serif"\n};\nconst STANDARD_FONT_DESCRIPTORS = Object.freeze([\n {\n id: PdfStandardFont.Courier,\n family: "Courier",\n bold: false,\n italic: false,\n label: "Courier",\n css: "Courier, monospace"\n },\n {\n id: PdfStandardFont.Courier_Bold,\n family: "Courier",\n bold: true,\n italic: false,\n label: "Courier Bold",\n css: "Courier, monospace"\n },\n {\n id: PdfStandardFont.Courier_BoldOblique,\n family: "Courier",\n bold: true,\n italic: true,\n label: "Courier Bold Oblique",\n css: "Courier, monospace"\n },\n {\n id: PdfStandardFont.Courier_Oblique,\n family: "Courier",\n bold: false,\n italic: true,\n label: "Courier Oblique",\n css: "Courier, monospace"\n },\n HELVETICA_DESC,\n {\n id: PdfStandardFont.Helvetica_Bold,\n family: "Helvetica",\n bold: true,\n italic: false,\n label: "Helvetica Bold",\n css: "Helvetica, Arial, sans-serif"\n },\n {\n id: PdfStandardFont.Helvetica_BoldOblique,\n family: "Helvetica",\n bold: true,\n italic: true,\n label: "Helvetica Bold Oblique",\n css: "Helvetica, Arial, sans-serif"\n },\n {\n id: PdfStandardFont.Helvetica_Oblique,\n family: "Helvetica",\n bold: false,\n italic: true,\n label: "Helvetica Oblique",\n css: "Helvetica, Arial, sans-serif"\n },\n {\n id: PdfStandardFont.Times_Roman,\n family: "Times",\n bold: false,\n italic: false,\n label: "Times Roman",\n css: \'"Times New Roman", Times, serif\'\n },\n {\n id: PdfStandardFont.Times_Bold,\n family: "Times",\n bold: true,\n italic: false,\n label: "Times Bold",\n css: \'"Times New Roman", Times, serif\'\n },\n {\n id: PdfStandardFont.Times_BoldItalic,\n family: "Times",\n bold: true,\n italic: true,\n label: "Times Bold Italic",\n css: \'"Times New Roman", Times, serif\'\n },\n {\n id: PdfStandardFont.Times_Italic,\n family: "Times",\n bold: false,\n italic: true,\n label: "Times Italic",\n css: \'"Times New Roman", Times, serif\'\n },\n {\n id: PdfStandardFont.Symbol,\n family: "Symbol",\n bold: false,\n italic: false,\n label: "Symbol",\n css: "Symbol, serif"\n },\n {\n id: PdfStandardFont.ZapfDingbats,\n family: "ZapfDingbats",\n bold: false,\n italic: false,\n label: "Zapf Dingbats",\n css: "ZapfDingbats, serif"\n }\n]);\nSTANDARD_FONT_DESCRIPTORS.reduce((m, d) => (m[d.id] = d, m), {});\nconst familyStyleToId = /* @__PURE__ */ new Map();\nfor (const d of STANDARD_FONT_DESCRIPTORS) {\n familyStyleToId.set(`${d.family}_${d.bold}_${d.italic}`, d.id);\n}\nObject.values(PdfStandardFontFamily).filter(\n (f) => f !== "Unknown"\n /* Unknown */\n).map((family) => ({ value: family, label: family }));\n[\n ...new Set(STANDARD_FONT_DESCRIPTORS.map((d) => d.family))\n];\nconst BLEND_MODE_INFOS = Object.freeze([\n { id: PdfBlendMode.Normal, label: "Normal", css: "normal" },\n { id: PdfBlendMode.Multiply, label: "Multiply", css: "multiply" },\n { id: PdfBlendMode.Screen, label: "Screen", css: "screen" },\n { id: PdfBlendMode.Overlay, label: "Overlay", css: "overlay" },\n { id: PdfBlendMode.Darken, label: "Darken", css: "darken" },\n { id: PdfBlendMode.Lighten, label: "Lighten", css: "lighten" },\n { id: PdfBlendMode.ColorDodge, label: "Color Dodge", css: "color-dodge" },\n { id: PdfBlendMode.ColorBurn, label: "Color Burn", css: "color-burn" },\n { id: PdfBlendMode.HardLight, label: "Hard Light", css: "hard-light" },\n { id: PdfBlendMode.SoftLight, label: "Soft Light", css: "soft-light" },\n { id: PdfBlendMode.Difference, label: "Difference", css: "difference" },\n { id: PdfBlendMode.Exclusion, label: "Exclusion", css: "exclusion" },\n { id: PdfBlendMode.Hue, label: "Hue", css: "hue" },\n { id: PdfBlendMode.Saturation, label: "Saturation", css: "saturation" },\n { id: PdfBlendMode.Color, label: "Color", css: "color" },\n { id: PdfBlendMode.Luminosity, label: "Luminosity", css: "luminosity" }\n]);\nBLEND_MODE_INFOS.reduce(\n (m, info) => {\n m[info.id] = info;\n return m;\n },\n {}\n);\nBLEND_MODE_INFOS.reduce(\n (m, info) => {\n m[info.css] = info.id;\n return m;\n },\n {}\n);\nBLEND_MODE_INFOS.map((info) => ({\n value: info.id,\n label: info.label\n}));\nBLEND_MODE_INFOS.map((info) => info.id);\nfunction deserializeLogger(serialized) {\n var _a, _b, _c;\n switch (serialized.type) {\n case "noop":\n return new NoopLogger();\n case "console":\n return new ConsoleLogger();\n case "perf":\n return new PerfLogger();\n case "level":\n if (!((_a = serialized.config) == null ? void 0 : _a.logger) || ((_b = serialized.config) == null ? void 0 : _b.level) === void 0) {\n throw new Error("LevelLogger requires logger and level in config");\n }\n return new LevelLogger(deserializeLogger(serialized.config.logger), serialized.config.level);\n case "all":\n if (!((_c = serialized.config) == null ? void 0 : _c.loggers)) {\n throw new Error("AllLogger requires loggers array in config");\n }\n return new AllLogger(serialized.config.loggers.map(deserializeLogger));\n default:\n return new NoopLogger();\n }\n}\nconst V4_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\nfunction isUuidV4(str) {\n return V4_REGEX.test(str);\n}\nfunction getRandomBytes(len) {\n var _a;\n if (typeof ((_a = globalThis.crypto) == null ? void 0 : _a.getRandomValues) === "function") {\n return globalThis.crypto.getRandomValues(new Uint8Array(len));\n }\n if (typeof require === "function") {\n try {\n const { randomBytes } = require("crypto");\n return randomBytes(len);\n } catch {\n }\n }\n const bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) bytes[i] = Math.floor(Math.random() * 256);\n return bytes;\n}\nfunction uuidV4() {\n var _a;\n if (typeof ((_a = globalThis.crypto) == null ? void 0 : _a.randomUUID) === "function") {\n return globalThis.crypto.randomUUID();\n }\n const bytes = getRandomBytes(16);\n bytes[6] = bytes[6] & 15 | 64;\n bytes[8] = bytes[8] & 63 | 128;\n const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\nvar createPdfium = (() => {\n var _scriptName = import.meta.url;\n return async function(moduleArg = {}) {\n var moduleRtn;\n var Module = moduleArg;\n var readyPromiseResolve, readyPromiseReject;\n var readyPromise = new Promise((resolve, reject) => {\n readyPromiseResolve = resolve;\n readyPromiseReject = reject;\n });\n [\n "_EPDF_GetMetaKeyCount",\n "_EPDF_GetMetaKeyName",\n "_EPDF_GetMetaTrapped",\n "_EPDF_GetPageRotationByIndex",\n "_EPDF_GetPageSizeByIndexNormalized",\n "_EPDF_HasMetaText",\n "_EPDF_IsEncrypted",\n "_EPDF_IsOwnerUnlocked",\n "_EPDF_LoadPageNormalized",\n "_EPDF_PNG_EncodeRGBA",\n "_EPDF_RemoveEncryption",\n "_EPDF_RenderAnnotBitmap",\n "_EPDF_RenderAnnotBitmapUnrotated",\n "_EPDF_SetEncryption",\n "_EPDF_SetMetaText",\n "_EPDF_SetMetaTrapped",\n "_EPDF_UnlockOwnerPermissions",\n "_EPDFAction_CreateGoTo",\n "_EPDFAction_CreateGoToNamed",\n "_EPDFAction_CreateLaunch",\n "_EPDFAction_CreateRemoteGoToByName",\n "_EPDFAction_CreateRemoteGoToDest",\n "_EPDFAction_CreateURI",\n "_EPDFAnnot_ApplyRedaction",\n "_EPDFAnnot_ClearColor",\n "_EPDFAnnot_Flatten",\n "_EPDFAnnot_GenerateAppearance",\n "_EPDFAnnot_GenerateAppearanceWithBlend",\n "_EPDFAnnot_GetAPMatrix",\n "_EPDFAnnot_GetAvailableAppearanceModes",\n "_EPDFAnnot_GetBlendMode",\n "_EPDFAnnot_GetBorderDashPattern",\n "_EPDFAnnot_GetBorderDashPatternCount",\n "_EPDFAnnot_GetBorderEffect",\n "_EPDFAnnot_GetBorderStyle",\n "_EPDFAnnot_GetColor",\n "_EPDFAnnot_GetDefaultAppearance",\n "_EPDFAnnot_GetExtendedRotation",\n "_EPDFAnnot_GetIcon",\n "_EPDFAnnot_GetIntent",\n "_EPDFAnnot_GetLineEndings",\n "_EPDFAnnot_GetOpacity",\n "_EPDFAnnot_GetOverlayText",\n "_EPDFAnnot_GetOverlayTextRepeat",\n "_EPDFAnnot_GetRect",\n "_EPDFAnnot_GetRectangleDifferences",\n "_EPDFAnnot_GetReplyType",\n "_EPDFAnnot_GetRichContent",\n "_EPDFAnnot_GetRotate",\n "_EPDFAnnot_GetTextAlignment",\n "_EPDFAnnot_GetUnrotatedRect",\n "_EPDFAnnot_GetVerticalAlignment",\n "_EPDFAnnot_SetAction",\n "_EPDFAnnot_SetAPMatrix",\n "_EPDFAnnot_SetBorderDashPattern",\n "_EPDFAnnot_SetBorderStyle",\n "_EPDFAnnot_SetColor",\n "_EPDFAnnot_SetDefaultAppearance",\n "_EPDFAnnot_SetExtendedRotation",\n "_EPDFAnnot_SetIcon",\n "_EPDFAnnot_SetIntent",\n "_EPDFAnnot_SetLine",\n "_EPDFAnnot_SetLineEndings",\n "_EPDFAnnot_SetLinkedAnnot",\n "_EPDFAnnot_SetOpacity",\n "_EPDFAnnot_SetOverlayText",\n "_EPDFAnnot_SetOverlayTextRepeat",\n "_EPDFAnnot_SetReplyType",\n "_EPDFAnnot_SetRotate",\n "_EPDFAnnot_SetTextAlignment",\n "_EPDFAnnot_SetUnrotatedRect",\n "_EPDFAnnot_SetVerticalAlignment",\n "_EPDFAnnot_SetVertices",\n "_EPDFAnnot_UpdateAppearanceToRect",\n "_EPDFAttachment_GetDescription",\n "_EPDFAttachment_GetIntegerValue",\n "_EPDFAttachment_SetDescription",\n "_EPDFAttachment_SetSubtype",\n "_EPDFBookmark_AppendChild",\n "_EPDFBookmark_Clear",\n "_EPDFBookmark_ClearTarget",\n "_EPDFBookmark_Create",\n "_EPDFBookmark_Delete",\n "_EPDFBookmark_InsertAfter",\n "_EPDFBookmark_SetAction",\n "_EPDFBookmark_SetDest",\n "_EPDFBookmark_SetTitle",\n "_EPDFCatalog_GetLanguage",\n "_EPDFDest_CreateRemoteView",\n "_EPDFDest_CreateRemoteXYZ",\n "_EPDFDest_CreateView",\n "_EPDFDest_CreateXYZ",\n "_EPDFNamedDest_Remove",\n "_EPDFNamedDest_SetDest",\n "_EPDFPage_ApplyRedactions",\n "_EPDFPage_CreateAnnot",\n "_EPDFPage_GetAnnotByName",\n "_EPDFPage_GetAnnotCountRaw",\n "_EPDFPage_GetAnnotRaw",\n "_EPDFPage_RemoveAnnotByName",\n "_EPDFPage_RemoveAnnotRaw",\n "_EPDFText_RedactInQuads",\n "_EPDFText_RedactInRect",\n "_FORM_CanRedo",\n "_FORM_CanUndo",\n "_FORM_DoDocumentAAction",\n "_FORM_DoDocumentJSAction",\n "_FORM_DoDocumentOpenAction",\n "_FORM_DoPageAAction",\n "_FORM_ForceToKillFocus",\n "_FORM_GetFocusedAnnot",\n "_FORM_GetFocusedText",\n "_FORM_GetSelectedText",\n "_FORM_IsIndexSelected",\n "_FORM_OnAfterLoadPage",\n "_FORM_OnBeforeClosePage",\n "_FORM_OnChar",\n "_FORM_OnFocus",\n "_FORM_OnKeyDown",\n "_FORM_OnKeyUp",\n "_FORM_OnLButtonDoubleClick",\n "_FORM_OnLButtonDown",\n "_FORM_OnLButtonUp",\n "_FORM_OnMouseMove",\n "_FORM_OnMouseWheel",\n "_FORM_OnRButtonDown",\n "_FORM_OnRButtonUp",\n "_FORM_Redo",\n "_FORM_ReplaceAndKeepSelection",\n "_FORM_ReplaceSelection",\n "_FORM_SelectAllText",\n "_FORM_SetFocusedAnnot",\n "_FORM_SetIndexSelected",\n "_FORM_Undo",\n "_FPDF_AddInstalledFont",\n "_FPDF_CloseDocument",\n "_FPDF_ClosePage",\n "_FPDF_CloseXObject",\n "_FPDF_CopyViewerPreferences",\n "_FPDF_CountNamedDests",\n "_FPDF_CreateClipPath",\n "_FPDF_CreateNewDocument",\n "_FPDF_DestroyClipPath",\n "_FPDF_DestroyLibrary",\n "_FPDF_DeviceToPage",\n "_FPDF_DocumentHasValidCrossReferenceTable",\n "_FPDF_FFLDraw",\n "_FPDF_FreeDefaultSystemFontInfo",\n "_FPDF_GetDefaultSystemFontInfo",\n "_FPDF_GetDefaultTTFMap",\n "_FPDF_GetDefaultTTFMapCount",\n "_FPDF_GetDefaultTTFMapEntry",\n "_FPDF_GetDocPermissions",\n "_FPDF_GetDocUserPermissions",\n "_FPDF_GetFileIdentifier",\n "_FPDF_GetFileVersion",\n "_FPDF_GetFormType",\n "_FPDF_GetLastError",\n "_FPDF_GetMetaText",\n "_FPDF_GetNamedDest",\n "_FPDF_GetNamedDestByName",\n "_FPDF_GetPageAAction",\n "_FPDF_GetPageBoundingBox",\n "_FPDF_GetPageCount",\n "_FPDF_GetPageHeight",\n "_FPDF_GetPageHeightF",\n "_FPDF_GetPageLabel",\n "_FPDF_GetPageSizeByIndex",\n "_FPDF_GetPageSizeByIndexF",\n "_FPDF_GetPageWidth",\n "_FPDF_GetPageWidthF",\n "_FPDF_GetSecurityHandlerRevision",\n "_FPDF_GetSignatureCount",\n "_FPDF_GetSignatureObject",\n "_FPDF_GetTrailerEnds",\n "_FPDF_GetXFAPacketContent",\n "_FPDF_GetXFAPacketCount",\n "_FPDF_GetXFAPacketName",\n "_FPDF_ImportNPagesToOne",\n "_FPDF_ImportPages",\n "_FPDF_ImportPagesByIndex",\n "_FPDF_InitLibrary",\n "_FPDF_InitLibraryWithConfig",\n "_FPDF_LoadCustomDocument",\n "_FPDF_LoadDocument",\n "_FPDF_LoadMemDocument",\n "_FPDF_LoadMemDocument64",\n "_FPDF_LoadPage",\n "_FPDF_LoadXFA",\n "_FPDF_MovePages",\n "_FPDF_NewFormObjectFromXObject",\n "_FPDF_NewXObjectFromPage",\n "_FPDF_PageToDevice",\n "_FPDF_RemoveFormFieldHighlight",\n "_FPDF_RenderPage_Close",\n "_FPDF_RenderPage_Continue",\n "_FPDF_RenderPageBitmap",\n "_FPDF_RenderPageBitmap_Start",\n "_FPDF_RenderPageBitmapWithColorScheme_Start",\n "_FPDF_RenderPageBitmapWithMatrix",\n "_FPDF_SaveAsCopy",\n "_FPDF_SaveWithVersion",\n "_FPDF_SetFormFieldHighlightAlpha",\n "_FPDF_SetFormFieldHighlightColor",\n "_FPDF_SetSandBoxPolicy",\n "_FPDF_SetSystemFontInfo",\n "_FPDF_StructElement_Attr_CountChildren",\n "_FPDF_StructElement_Attr_GetBlobValue",\n "_FPDF_StructElement_Attr_GetBooleanValue",\n "_FPDF_StructElement_Attr_GetChildAtIndex",\n "_FPDF_StructElement_Attr_GetCount",\n "_FPDF_StructElement_Attr_GetName",\n "_FPDF_StructElement_Attr_GetNumberValue",\n "_FPDF_StructElement_Attr_GetStringValue",\n "_FPDF_StructElement_Attr_GetType",\n "_FPDF_StructElement_Attr_GetValue",\n "_FPDF_StructElement_CountChildren",\n "_FPDF_StructElement_GetActualText",\n "_FPDF_StructElement_GetAltText",\n "_FPDF_StructElement_GetAttributeAtIndex",\n "_FPDF_StructElement_GetAttributeCount",\n "_FPDF_StructElement_GetChildAtIndex",\n "_FPDF_StructElement_GetChildMarkedContentID",\n "_FPDF_StructElement_GetID",\n "_FPDF_StructElement_GetLang",\n "_FPDF_StructElement_GetMarkedContentID",\n "_FPDF_StructElement_GetMarkedContentIdAtIndex",\n "_FPDF_StructElement_GetMarkedContentIdCount",\n "_FPDF_StructElement_GetObjType",\n "_FPDF_StructElement_GetParent",\n "_FPDF_StructElement_GetStringAttribute",\n "_FPDF_StructElement_GetTitle",\n "_FPDF_StructElement_GetType",\n "_FPDF_StructTree_Close",\n "_FPDF_StructTree_CountChildren",\n "_FPDF_StructTree_GetChildAtIndex",\n "_FPDF_StructTree_GetForPage",\n "_FPDF_VIEWERREF_GetDuplex",\n "_FPDF_VIEWERREF_GetName",\n "_FPDF_VIEWERREF_GetNumCopies",\n "_FPDF_VIEWERREF_GetPrintPageRange",\n "_FPDF_VIEWERREF_GetPrintPageRangeCount",\n "_FPDF_VIEWERREF_GetPrintPageRangeElement",\n "_FPDF_VIEWERREF_GetPrintScaling",\n "_FPDFAction_GetDest",\n "_FPDFAction_GetFilePath",\n "_FPDFAction_GetType",\n "_FPDFAction_GetURIPath",\n "_FPDFAnnot_AddFileAttachment",\n "_FPDFAnnot_AddInkStroke",\n "_FPDFAnnot_AppendAttachmentPoints",\n "_FPDFAnnot_AppendObject",\n "_FPDFAnnot_CountAttachmentPoints",\n "_FPDFAnnot_GetAP",\n "_FPDFAnnot_GetAttachmentPoints",\n "_FPDFAnnot_GetBorder",\n "_FPDFAnnot_GetColor",\n "_FPDFAnnot_GetFileAttachment",\n "_FPDFAnnot_GetFlags",\n "_FPDFAnnot_GetFocusableSubtypes",\n "_FPDFAnnot_GetFocusableSubtypesCount",\n "_FPDFAnnot_GetFontColor",\n "_FPDFAnnot_GetFontSize",\n "_FPDFAnnot_GetFormAdditionalActionJavaScript",\n "_FPDFAnnot_GetFormControlCount",\n "_FPDFAnnot_GetFormControlIndex",\n "_FPDFAnnot_GetFormFieldAlternateName",\n "_FPDFAnnot_GetFormFieldAtPoint",\n "_FPDFAnnot_GetFormFieldExportValue",\n "_FPDFAnnot_GetFormFieldFlags",\n "_FPDFAnnot_GetFormFieldName",\n "_FPDFAnnot_GetFormFieldType",\n "_FPDFAnnot_GetFormFieldValue",\n "_FPDFAnnot_GetInkListCount",\n "_FPDFAnnot_GetInkListPath",\n "_FPDFAnnot_GetLine",\n "_FPDFAnnot_GetLink",\n "_FPDFAnnot_GetLinkedAnnot",\n "_FPDFAnnot_GetNumberValue",\n "_FPDFAnnot_GetObject",\n "_FPDFAnnot_GetObjectCount",\n "_FPDFAnnot_GetOptionCount",\n "_FPDFAnnot_GetOptionLabel",\n "_FPDFAnnot_GetRect",\n "_FPDFAnnot_GetStringValue",\n "_FPDFAnnot_GetSubtype",\n "_FPDFAnnot_GetValueType",\n "_FPDFAnnot_GetVertices",\n "_FPDFAnnot_HasAttachmentPoints",\n "_FPDFAnnot_HasKey",\n "_FPDFAnnot_IsChecked",\n "_FPDFAnnot_IsObjectSupportedSubtype",\n "_FPDFAnnot_IsOptionSelected",\n "_FPDFAnnot_IsSupportedSubtype",\n "_FPDFAnnot_RemoveInkList",\n "_FPDFAnnot_RemoveObject",\n "_FPDFAnnot_SetAP",\n "_FPDFAnnot_SetAttachmentPoints",\n "_FPDFAnnot_SetBorder",\n "_FPDFAnnot_SetColor",\n "_FPDFAnnot_SetFlags",\n "_FPDFAnnot_SetFocusableSubtypes",\n "_FPDFAnnot_SetFontColor",\n "_FPDFAnnot_SetFormFieldFlags",\n "_FPDFAnnot_SetRect",\n "_FPDFAnnot_SetStringValue",\n "_FPDFAnnot_SetURI",\n "_FPDFAnnot_UpdateObject",\n "_FPDFAttachment_GetFile",\n "_FPDFAttachment_GetName",\n "_FPDFAttachment_GetStringValue",\n "_FPDFAttachment_GetSubtype",\n "_FPDFAttachment_GetValueType",\n "_FPDFAttachment_HasKey",\n "_FPDFAttachment_SetFile",\n "_FPDFAttachment_SetStringValue",\n "_FPDFAvail_Create",\n "_FPDFAvail_Destroy",\n "_FPDFAvail_GetDocument",\n "_FPDFAvail_GetFirstPageNum",\n "_FPDFAvail_IsDocAvail",\n "_FPDFAvail_IsFormAvail",\n "_FPDFAvail_IsLinearized",\n "_FPDFAvail_IsPageAvail",\n "_FPDFBitmap_Create",\n "_FPDFBitmap_CreateEx",\n "_FPDFBitmap_Destroy",\n "_FPDFBitmap_FillRect",\n "_FPDFBitmap_GetBuffer",\n "_FPDFBitmap_GetFormat",\n "_FPDFBitmap_GetHeight",\n "_FPDFBitmap_GetStride",\n "_FPDFBitmap_GetWidth",\n "_FPDFBookmark_Find",\n "_FPDFBookmark_GetAction",\n "_FPDFBookmark_GetCount",\n "_FPDFBookmark_GetDest",\n "_FPDFBookmark_GetFirstChild",\n "_FPDFBookmark_GetNextSibling",\n "_FPDFBookmark_GetTitle",\n "_FPDFCatalog_GetLanguage",\n "_FPDFCatalog_IsTagged",\n "_FPDFCatalog_SetLanguage",\n "_FPDFClipPath_CountPaths",\n "_FPDFClipPath_CountPathSegments",\n "_FPDFClipPath_GetPathSegment",\n "_FPDFDest_GetDestPageIndex",\n "_FPDFDest_GetLocationInPage",\n "_FPDFDest_GetView",\n "_FPDFDoc_AddAttachment",\n "_FPDFDoc_CloseJavaScriptAction",\n "_FPDFDoc_DeleteAttachment",\n "_FPDFDOC_ExitFormFillEnvironment",\n "_FPDFDoc_GetAttachment",\n "_FPDFDoc_GetAttachmentCount",\n "_FPDFDoc_GetJavaScriptAction",\n "_FPDFDoc_GetJavaScriptActionCount",\n "_FPDFDoc_GetPageMode",\n "_FPDFDOC_InitFormFillEnvironment",\n "_FPDFFont_Close",\n "_FPDFFont_GetAscent",\n "_FPDFFont_GetBaseFontName",\n "_FPDFFont_GetDescent",\n "_FPDFFont_GetFamilyName",\n "_FPDFFont_GetFlags",\n "_FPDFFont_GetFontData",\n "_FPDFFont_GetGlyphPath",\n "_FPDFFont_GetGlyphWidth",\n "_FPDFFont_GetIsEmbedded",\n "_FPDFFont_GetItalicAngle",\n "_FPDFFont_GetWeight",\n "_FPDFFormObj_CountObjects",\n "_FPDFFormObj_GetObject",\n "_FPDFFormObj_RemoveObject",\n "_FPDFGlyphPath_CountGlyphSegments",\n "_FPDFGlyphPath_GetGlyphPathSegment",\n "_FPDFImageObj_GetBitmap",\n "_FPDFImageObj_GetIccProfileDataDecoded",\n "_FPDFImageObj_GetImageDataDecoded",\n "_FPDFImageObj_GetImageDataRaw",\n "_FPDFImageObj_GetImageFilter",\n "_FPDFImageObj_GetImageFilterCount",\n "_FPDFImageObj_GetImageMetadata",\n "_FPDFImageObj_GetImagePixelSize",\n "_FPDFImageObj_GetRenderedBitmap",\n "_FPDFImageObj_LoadJpegFile",\n "_FPDFImageObj_LoadJpegFileInline",\n "_FPDFImageObj_SetBitmap",\n "_FPDFImageObj_SetMatrix",\n "_FPDFJavaScriptAction_GetName",\n "_FPDFJavaScriptAction_GetScript",\n "_FPDFLink_CloseWebLinks",\n "_FPDFLink_CountQuadPoints",\n "_FPDFLink_CountRects",\n "_FPDFLink_CountWebLinks",\n "_FPDFLink_Enumerate",\n "_FPDFLink_GetAction",\n "_FPDFLink_GetAnnot",\n "_FPDFLink_GetAnnotRect",\n "_FPDFLink_GetDest",\n "_FPDFLink_GetLinkAtPoint",\n "_FPDFLink_GetLinkZOrderAtPoint",\n "_FPDFLink_GetQuadPoints",\n "_FPDFLink_GetRect",\n "_FPDFLink_GetTextRange",\n "_FPDFLink_GetURL",\n "_FPDFLink_LoadWebLinks",\n "_FPDFPage_CloseAnnot",\n "_FPDFPage_CountObjects",\n "_FPDFPage_CreateAnnot",\n "_FPDFPage_Delete",\n "_FPDFPage_Flatten",\n "_FPDFPage_FormFieldZOrderAtPoint",\n "_FPDFPage_GenerateContent",\n "_FPDFPage_GetAnnot",\n "_FPDFPage_GetAnnotCount",\n "_FPDFPage_GetAnnotIndex",\n "_FPDFPage_GetArtBox",\n "_FPDFPage_GetBleedBox",\n "_FPDFPage_GetCropBox",\n "_FPDFPage_GetDecodedThumbnailData",\n "_FPDFPage_GetMediaBox",\n "_FPDFPage_GetObject",\n "_FPDFPage_GetRawThumbnailData",\n "_FPDFPage_GetRotation",\n "_FPDFPage_GetThumbnailAsBitmap",\n "_FPDFPage_GetTrimBox",\n "_FPDFPage_HasFormFieldAtPoint",\n "_FPDFPage_HasTransparency",\n "_FPDFPage_InsertClipPath",\n "_FPDFPage_InsertObject",\n "_FPDFPage_InsertObjectAtIndex",\n "_FPDFPage_New",\n "_FPDFPage_RemoveAnnot",\n "_FPDFPage_RemoveObject",\n "_FPDFPage_SetArtBox",\n "_FPDFPage_SetBleedBox",\n "_FPDFPage_SetCropBox",\n "_FPDFPage_SetMediaBox",\n "_FPDFPage_SetRotation",\n "_FPDFPage_SetTrimBox",\n "_FPDFPage_TransformAnnots",\n "_FPDFPage_TransFormWithClip",\n "_FPDFPageObj_AddMark",\n "_FPDFPageObj_CountMarks",\n "_FPDFPageObj_CreateNewPath",\n "_FPDFPageObj_CreateNewRect",\n "_FPDFPageObj_CreateTextObj",\n "_FPDFPageObj_Destroy",\n "_FPDFPageObj_GetBounds",\n "_FPDFPageObj_GetClipPath",\n "_FPDFPageObj_GetDashArray",\n "_FPDFPageObj_GetDashCount",\n "_FPDFPageObj_GetDashPhase",\n "_FPDFPageObj_GetFillColor",\n "_FPDFPageObj_GetIsActive",\n "_FPDFPageObj_GetLineCap",\n "_FPDFPageObj_GetLineJoin",\n "_FPDFPageObj_GetMark",\n "_FPDFPageObj_GetMarkedContentID",\n "_FPDFPageObj_GetMatrix",\n "_FPDFPageObj_GetRotatedBounds",\n "_FPDFPageObj_GetStrokeColor",\n "_FPDFPageObj_GetStrokeWidth",\n "_FPDFPageObj_GetType",\n "_FPDFPageObj_HasTransparency",\n "_FPDFPageObj_NewImageObj",\n "_FPDFPageObj_NewTextObj",\n "_FPDFPageObj_RemoveMark",\n "_FPDFPageObj_SetBlendMode",\n "_FPDFPageObj_SetDashArray",\n "_FPDFPageObj_SetDashPhase",\n "_FPDFPageObj_SetFillColor",\n "_FPDFPageObj_SetIsActive",\n "_FPDFPageObj_SetLineCap",\n "_FPDFPageObj_SetLineJoin",\n "_FPDFPageObj_SetMatrix",\n "_FPDFPageObj_SetStrokeColor",\n "_FPDFPageObj_SetStrokeWidth",\n "_FPDFPageObj_Transform",\n "_FPDFPageObj_TransformClipPath",\n "_FPDFPageObj_TransformF",\n "_FPDFPageObjMark_CountParams",\n "_FPDFPageObjMark_GetName",\n "_FPDFPageObjMark_GetParamBlobValue",\n "_FPDFPageObjMark_GetParamFloatValue",\n "_FPDFPageObjMark_GetParamIntValue",\n "_FPDFPageObjMark_GetParamKey",\n "_FPDFPageObjMark_GetParamStringValue",\n "_FPDFPageObjMark_GetParamValueType",\n "_FPDFPageObjMark_RemoveParam",\n "_FPDFPageObjMark_SetBlobParam",\n "_FPDFPageObjMark_SetFloatParam",\n "_FPDFPageObjMark_SetIntParam",\n "_FPDFPageObjMark_SetStringParam",\n "_FPDFPath_BezierTo",\n "_FPDFPath_Close",\n "_FPDFPath_CountSegments",\n "_FPDFPath_GetDrawMode",\n "_FPDFPath_GetPathSegment",\n "_FPDFPath_LineTo",\n "_FPDFPath_MoveTo",\n "_FPDFPath_SetDrawMode",\n "_FPDFPathSegment_GetClose",\n "_FPDFPathSegment_GetPoint",\n "_FPDFPathSegment_GetType",\n "_FPDFSignatureObj_GetByteRange",\n "_FPDFSignatureObj_GetContents",\n "_FPDFSignatureObj_GetDocMDPPermission",\n "_FPDFSignatureObj_GetReason",\n "_FPDFSignatureObj_GetSubFilter",\n "_FPDFSignatureObj_GetTime",\n "_FPDFText_ClosePage",\n "_FPDFText_CountChars",\n "_FPDFText_CountRects",\n "_FPDFText_FindClose",\n "_FPDFText_FindNext",\n "_FPDFText_FindPrev",\n "_FPDFText_FindStart",\n "_FPDFText_GetBoundedText",\n "_FPDFText_GetCharAngle",\n "_FPDFText_GetCharBox",\n "_FPDFText_GetCharIndexAtPos",\n "_FPDFText_GetCharIndexFromTextIndex",\n "_FPDFText_GetCharOrigin",\n "_FPDFText_GetFillColor",\n "_FPDFText_GetFontInfo",\n "_FPDFText_GetFontSize",\n "_FPDFText_GetFontWeight",\n "_FPDFText_GetLooseCharBox",\n "_FPDFText_GetMatrix",\n "_FPDFText_GetRect",\n "_FPDFText_GetSchCount",\n "_FPDFText_GetSchResultIndex",\n "_FPDFText_GetStrokeColor",\n "_FPDFText_GetText",\n "_FPDFText_GetTextIndexFromCharIndex",\n "_FPDFText_GetTextObject",\n "_FPDFText_GetUnicode",\n "_FPDFText_HasUnicodeMapError",\n "_FPDFText_IsGenerated",\n "_FPDFText_IsHyphen",\n "_FPDFText_LoadCidType2Font",\n "_FPDFText_LoadFont",\n "_FPDFText_LoadPage",\n "_FPDFText_LoadStandardFont",\n "_FPDFText_SetCharcodes",\n "_FPDFText_SetText",\n "_FPDFTextObj_GetFont",\n "_FPDFTextObj_GetFontSize",\n "_FPDFTextObj_GetRenderedBitmap",\n "_FPDFTextObj_GetText",\n "_FPDFTextObj_GetTextRenderMode",\n "_FPDFTextObj_SetTextRenderMode",\n "_PDFiumExt_CloseFileWriter",\n "_PDFiumExt_CloseFormFillInfo",\n "_PDFiumExt_ExitFormFillEnvironment",\n "_PDFiumExt_GetFileWriterData",\n "_PDFiumExt_GetFileWriterSize",\n "_PDFiumExt_Init",\n "_PDFiumExt_InitFormFillEnvironment",\n "_PDFiumExt_OpenFileWriter",\n "_PDFiumExt_OpenFormFillInfo",\n "_PDFiumExt_SaveAsCopy",\n "_malloc",\n "_free",\n "_memory",\n "___indirect_function_table",\n "onRuntimeInitialized"\n ].forEach((prop) => {\n if (!Object.getOwnPropertyDescriptor(readyPromise, prop)) {\n Object.defineProperty(readyPromise, prop, {\n get: () => abort(\n "You are getting " + prop + " on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js"\n ),\n set: () => abort(\n "You are setting " + prop + " on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js"\n )\n });\n }\n });\n var ENVIRONMENT_IS_WEB = typeof window == "object";\n var ENVIRONMENT_IS_WORKER = typeof importScripts == "function";\n typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string" && process.type != "renderer";\n var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && true && !ENVIRONMENT_IS_WORKER;\n var moduleOverrides = Object.assign({}, Module);\n var thisProgram = "./this.program";\n var scriptDirectory = "";\n function locateFile(path) {\n if (Module["locateFile"]) {\n return Module["locateFile"](path, scriptDirectory);\n }\n return scriptDirectory + path;\n }\n var readAsync, readBinary;\n if (ENVIRONMENT_IS_SHELL) {\n if (typeof window == "object" || typeof importScripts == "function")\n throw new Error(\n "not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)"\n );\n readBinary = (f) => {\n if (typeof readbuffer == "function") {\n return new Uint8Array(readbuffer(f));\n }\n let data = read(f, "binary");\n assert(typeof data == "object");\n return data;\n };\n readAsync = (f) => {\n return new Promise((resolve, reject) => {\n setTimeout(() => resolve(readBinary(f)));\n });\n };\n globalThis.clearTimeout ?? (globalThis.clearTimeout = (id) => {\n });\n globalThis.setTimeout ?? (globalThis.setTimeout = (f) => typeof f == "function" ? f() : abort());\n if (typeof print != "undefined") {\n globalThis.console ?? (globalThis.console = /** @type{!Console} */\n {});\n console.log = /** @type{!function(this:Console, ...*): undefined} */\n print;\n console.warn = console.error = /** @type{!function(this:Console, ...*): undefined} */\n globalThis.printErr ?? print;\n }\n } else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {\n if (ENVIRONMENT_IS_WORKER) {\n scriptDirectory = self.location.href;\n } else if (typeof document != "undefined" && document.currentScript) {\n scriptDirectory = document.currentScript.src;\n }\n if (_scriptName) {\n scriptDirectory = _scriptName;\n }\n if (scriptDirectory.startsWith("blob:")) {\n scriptDirectory = "";\n } else {\n scriptDirectory = scriptDirectory.substr(\n 0,\n scriptDirectory.replace(/[?#].*/, "").lastIndexOf("/") + 1\n );\n }\n if (!(typeof window == "object" || typeof importScripts == "function"))\n throw new Error(\n "not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)"\n );\n {\n if (ENVIRONMENT_IS_WORKER) {\n readBinary = (url) => {\n var xhr = new XMLHttpRequest();\n xhr.open("GET", url, false);\n xhr.responseType = "arraybuffer";\n xhr.send(null);\n return new Uint8Array(\n /** @type{!ArrayBuffer} */\n xhr.response\n );\n };\n }\n readAsync = (url) => {\n assert(!isFileURI(url), "readAsync does not work with file:// URLs");\n return fetch(url, { credentials: "same-origin" }).then((response) => {\n if (response.ok) {\n return response.arrayBuffer();\n }\n return Promise.reject(new Error(response.status + " : " + response.url));\n });\n };\n }\n } else {\n throw new Error("environment detection error");\n }\n var out = Module["print"] || console.log.bind(console);\n var err = Module["printErr"] || console.error.bind(console);\n Object.assign(Module, moduleOverrides);\n moduleOverrides = null;\n checkIncomingModuleAPI();\n if (Module["arguments"]) Module["arguments"];\n legacyModuleProp("arguments", "arguments_");\n if (Module["thisProgram"]) thisProgram = Module["thisProgram"];\n legacyModuleProp("thisProgram", "thisProgram");\n assert(\n typeof Module["memoryInitializerPrefixURL"] == "undefined",\n "Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead"\n );\n assert(\n typeof Module["pthreadMainPrefixURL"] == "undefined",\n "Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead"\n );\n assert(\n typeof Module["cdInitializerPrefixURL"] == "undefined",\n "Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead"\n );\n assert(\n typeof Module["filePackagePrefixURL"] == "undefined",\n "Module.filePackagePrefixURL option was removed, use Module.locateFile instead"\n );\n assert(typeof Module["read"] == "undefined", "Module.read option was removed");\n assert(\n typeof Module["readAsync"] == "undefined",\n "Module.readAsync option was removed (modify readAsync in JS)"\n );\n assert(\n typeof Module["readBinary"] == "undefined",\n "Module.readBinary option was removed (modify readBinary in JS)"\n );\n assert(\n typeof Module["setWindowTitle"] == "undefined",\n "Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)"\n );\n assert(\n typeof Module["TOTAL_MEMORY"] == "undefined",\n "Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY"\n );\n legacyModuleProp("asm", "wasmExports");\n legacyModuleProp("readAsync", "readAsync");\n legacyModuleProp("readBinary", "readBinary");\n legacyModuleProp("setWindowTitle", "setWindowTitle");\n var wasmBinary = Module["wasmBinary"];\n legacyModuleProp("wasmBinary", "wasmBinary");\n if (typeof WebAssembly != "object") {\n err("no native wasm support detected");\n }\n var wasmMemory;\n var ABORT = false;\n function assert(condition, text) {\n if (!condition) {\n abort("Assertion failed" + (text ? ": " + text : ""));\n }\n }\n var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64;\n function updateMemoryViews() {\n var b = wasmMemory.buffer;\n Module["HEAP8"] = HEAP8 = new Int8Array(b);\n Module["HEAP16"] = HEAP16 = new Int16Array(b);\n Module["HEAPU8"] = HEAPU8 = new Uint8Array(b);\n Module["HEAPU16"] = HEAPU16 = new Uint16Array(b);\n Module["HEAP32"] = HEAP32 = new Int32Array(b);\n Module["HEAPU32"] = HEAPU32 = new Uint32Array(b);\n Module["HEAPF32"] = HEAPF32 = new Float32Array(b);\n Module["HEAPF64"] = HEAPF64 = new Float64Array(b);\n }\n assert(\n !Module["STACK_SIZE"],\n "STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time"\n );\n assert(\n typeof Int32Array != "undefined" && typeof Float64Array !== "undefined" && Int32Array.prototype.subarray != void 0 && Int32Array.prototype.set != void 0,\n "JS engine does not provide full typed array support"\n );\n assert(\n !Module["wasmMemory"],\n "Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally"\n );\n assert(\n !Module["INITIAL_MEMORY"],\n "Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically"\n );\n function writeStackCookie() {\n var max = _emscripten_stack_get_end();\n assert((max & 3) == 0);\n if (max == 0) {\n max += 4;\n }\n HEAPU32[max >> 2] = 34821223;\n HEAPU32[max + 4 >> 2] = 2310721022;\n HEAPU32[0 >> 2] = 1668509029;\n }\n function checkStackCookie() {\n if (ABORT) return;\n var max = _emscripten_stack_get_end();\n if (max == 0) {\n max += 4;\n }\n var cookie1 = HEAPU32[max >> 2];\n var cookie2 = HEAPU32[max + 4 >> 2];\n if (cookie1 != 34821223 || cookie2 != 2310721022) {\n abort(\n `Stack overflow! Stack cookie has been overwritten at ${ptrToString(max)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${ptrToString(cookie2)} ${ptrToString(cookie1)}`\n );\n }\n if (HEAPU32[0 >> 2] != 1668509029) {\n abort("Runtime error: The application has corrupted its heap memory area (address zero)!");\n }\n }\n var __ATPRERUN__ = [];\n var __ATINIT__ = [];\n var __ATPOSTRUN__ = [];\n var runtimeInitialized = false;\n function preRun() {\n var preRuns = Module["preRun"];\n if (preRuns) {\n if (typeof preRuns == "function") preRuns = [preRuns];\n preRuns.forEach(addOnPreRun);\n }\n callRuntimeCallbacks(__ATPRERUN__);\n }\n function initRuntime() {\n assert(!runtimeInitialized);\n runtimeInitialized = true;\n checkStackCookie();\n if (!Module["noFSInit"] && !FS.initialized) FS.init();\n FS.ignorePermissions = false;\n callRuntimeCallbacks(__ATINIT__);\n }\n function postRun() {\n checkStackCookie();\n var postRuns = Module["postRun"];\n if (postRuns) {\n if (typeof postRuns == "function") postRuns = [postRuns];\n postRuns.forEach(addOnPostRun);\n }\n callRuntimeCallbacks(__ATPOSTRUN__);\n }\n function addOnPreRun(cb) {\n __ATPRERUN__.unshift(cb);\n }\n function addOnInit(cb) {\n __ATINIT__.unshift(cb);\n }\n function addOnPostRun(cb) {\n __ATPOSTRUN__.unshift(cb);\n }\n assert(\n Math.imul,\n "This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"\n );\n assert(\n Math.fround,\n "This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"\n );\n assert(\n Math.clz32,\n "This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"\n );\n assert(\n Math.trunc,\n "This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"\n );\n var runDependencies = 0;\n var runDependencyWatcher = null;\n var dependenciesFulfilled = null;\n var runDependencyTracking = {};\n function getUniqueRunDependency(id) {\n var orig = id;\n while (1) {\n if (!runDependencyTracking[id]) return id;\n id = orig + Math.random();\n }\n }\n function addRunDependency(id) {\n var _a;\n runDependencies++;\n (_a = Module["monitorRunDependencies"]) == null ? void 0 : _a.call(Module, runDependencies);\n if (id) {\n assert(!runDependencyTracking[id]);\n runDependencyTracking[id] = 1;\n if (runDependencyWatcher === null && typeof setInterval != "undefined") {\n runDependencyWatcher = setInterval(() => {\n if (ABORT) {\n clearInterval(runDependencyWatcher);\n runDependencyWatcher = null;\n return;\n }\n var shown = false;\n for (var dep in runDependencyTracking) {\n if (!shown) {\n shown = true;\n err("still waiting on run dependencies:");\n }\n err(`dependency: ${dep}`);\n }\n if (shown) {\n err("(end of list)");\n }\n }, 1e4);\n }\n } else {\n err("warning: run dependency added without ID");\n }\n }\n function removeRunDependency(id) {\n var _a;\n runDependencies--;\n (_a = Module["monitorRunDependencies"]) == null ? void 0 : _a.call(Module, runDependencies);\n if (id) {\n assert(runDependencyTracking[id]);\n delete runDependencyTracking[id];\n } else {\n err("warning: run dependency removed without ID");\n }\n if (runDependencies == 0) {\n if (runDependencyWatcher !== null) {\n clearInterval(runDependencyWatcher);\n runDependencyWatcher = null;\n }\n if (dependenciesFulfilled) {\n var callback = dependenciesFulfilled;\n dependenciesFulfilled = null;\n callback();\n }\n }\n }\n function abort(what) {\n var _a;\n (_a = Module["onAbort"]) == null ? void 0 : _a.call(Module, what);\n what = "Aborted(" + what + ")";\n err(what);\n ABORT = true;\n var e = new WebAssembly.RuntimeError(what);\n readyPromiseReject(e);\n throw e;\n }\n var dataURIPrefix = "data:application/octet-stream;base64,";\n var isDataURI = (filename) => filename.startsWith(dataURIPrefix);\n var isFileURI = (filename) => filename.startsWith("file://");\n function createExportWrapper(name, nargs) {\n return (...args) => {\n assert(\n runtimeInitialized,\n `native function \\`${name}\\` called before runtime initialization`\n );\n var f = wasmExports[name];\n assert(f, `exported native function \\`${name}\\` not found`);\n assert(\n args.length <= nargs,\n `native function \\`${name}\\` called with ${args.length} args but expects ${nargs}`\n );\n return f(...args);\n };\n }\n function findWasmBinary() {\n if (Module["locateFile"]) {\n var f = "pdfium.wasm";\n if (!isDataURI(f)) {\n return locateFile(f);\n }\n return f;\n }\n if (ENVIRONMENT_IS_SHELL) return "pdfium.wasm";\n return "pdfium.wasm";\n }\n var wasmBinaryFile;\n function getBinarySync(file) {\n if (file == wasmBinaryFile && wasmBinary) {\n return new Uint8Array(wasmBinary);\n }\n if (readBinary) {\n return readBinary(file);\n }\n throw "both async and sync fetching of the wasm failed";\n }\n function getBinaryPromise(binaryFile) {\n if (!wasmBinary) {\n return readAsync(binaryFile).then(\n (response) => new Uint8Array(\n /** @type{!ArrayBuffer} */\n response\n ),\n // Fall back to getBinarySync if readAsync fails\n () => getBinarySync(binaryFile)\n );\n }\n return Promise.resolve().then(() => getBinarySync(binaryFile));\n }\n function instantiateArrayBuffer(binaryFile, imports, receiver) {\n return getBinaryPromise(binaryFile).then((binary) => {\n return WebAssembly.instantiate(binary, imports);\n }).then(receiver, (reason) => {\n err(`failed to asynchronously prepare wasm: ${reason}`);\n if (isFileURI(wasmBinaryFile)) {\n err(\n `warning: Loading from a file URI (${wasmBinaryFile}) is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing`\n );\n }\n abort(reason);\n });\n }\n function instantiateAsync(binary, binaryFile, imports, callback) {\n if (!binary && typeof WebAssembly.instantiateStreaming == "function" && !isDataURI(binaryFile) && // Avoid instantiateStreaming() on Node.js environment for now, as while\n // Node.js v18.1.0 implements it, it does not have a full fetch()\n // implementation yet.\n //\n // Reference:\n // https://github.com/emscripten-core/emscripten/pull/16917\n true && typeof fetch == "function") {\n return fetch(binaryFile, { credentials: "same-origin" }).then((response) => {\n var result = WebAssembly.instantiateStreaming(response, imports);\n return result.then(callback, function(reason) {\n err(`wasm streaming compile failed: ${reason}`);\n err("falling back to ArrayBuffer instantiation");\n return instantiateArrayBuffer(binaryFile, imports, callback);\n });\n });\n }\n return instantiateArrayBuffer(binaryFile, imports, callback);\n }\n function getWasmImports() {\n return {\n env: wasmImports,\n wasi_snapshot_preview1: wasmImports\n };\n }\n function createWasm() {\n var info = getWasmImports();\n function receiveInstance(instance, module) {\n wasmExports = instance.exports;\n Module["wasmExports"] = wasmExports;\n wasmMemory = wasmExports["memory"];\n assert(wasmMemory, "memory not found in wasm exports");\n updateMemoryViews();\n wasmTable = wasmExports["__indirect_function_table"];\n assert(wasmTable, "table not found in wasm exports");\n addOnInit(wasmExports["__wasm_call_ctors"]);\n removeRunDependency("wasm-instantiate");\n return wasmExports;\n }\n addRunDependency("wasm-instantiate");\n var trueModule = Module;\n function receiveInstantiationResult(result) {\n assert(\n Module === trueModule,\n "the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?"\n );\n trueModule = null;\n receiveInstance(result["instance"]);\n }\n if (Module["instantiateWasm"]) {\n try {\n return Module["instantiateWasm"](info, receiveInstance);\n } catch (e) {\n err(`Module.instantiateWasm callback failed with error: ${e}`);\n readyPromiseReject(e);\n }\n }\n wasmBinaryFile ?? (wasmBinaryFile = findWasmBinary());\n instantiateAsync(wasmBinary, wasmBinaryFile, info, receiveInstantiationResult).catch(\n readyPromiseReject\n );\n return {};\n }\n var tempDouble;\n var tempI64;\n (() => {\n var h16 = new Int16Array(1);\n var h8 = new Int8Array(h16.buffer);\n h16[0] = 25459;\n if (h8[0] !== 115 || h8[1] !== 99)\n throw "Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)";\n })();\n if (Module["ENVIRONMENT"]) {\n throw new Error(\n "Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)"\n );\n }\n function legacyModuleProp(prop, newName, incoming = true) {\n if (!Object.getOwnPropertyDescriptor(Module, prop)) {\n Object.defineProperty(Module, prop, {\n configurable: true,\n get() {\n let extra = incoming ? " (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)" : "";\n abort(`\\`Module.${prop}\\` has been replaced by \\`${newName}\\`` + extra);\n }\n });\n }\n }\n function ignoredModuleProp(prop) {\n if (Object.getOwnPropertyDescriptor(Module, prop)) {\n abort(\n `\\`Module.${prop}\\` was supplied but \\`${prop}\\` not included in INCOMING_MODULE_JS_API`\n );\n }\n }\n function isExportedByForceFilesystem(name) {\n return name === "FS_createPath" || name === "FS_createDataFile" || name === "FS_createPreloadedFile" || name === "FS_unlink" || name === "addRunDependency" || // The old FS has some functionality that WasmFS lacks.\n name === "FS_createLazyFile" || name === "FS_createDevice" || name === "removeRunDependency";\n }\n function hookGlobalSymbolAccess(sym, func) {\n if (typeof globalThis != "undefined" && !Object.getOwnPropertyDescriptor(globalThis, sym)) {\n Object.defineProperty(globalThis, sym, {\n configurable: true,\n get() {\n func();\n return void 0;\n }\n });\n }\n }\n function missingGlobal(sym, msg) {\n hookGlobalSymbolAccess(sym, () => {\n warnOnce(`\\`${sym}\\` is not longer defined by emscripten. ${msg}`);\n });\n }\n missingGlobal("buffer", "Please use HEAP8.buffer or wasmMemory.buffer");\n missingGlobal("asm", "Please use wasmExports instead");\n function missingLibrarySymbol(sym) {\n hookGlobalSymbolAccess(sym, () => {\n var msg = `\\`${sym}\\` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line`;\n var librarySymbol = sym;\n if (!librarySymbol.startsWith("_")) {\n librarySymbol = "$" + sym;\n }\n msg += ` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE=\'${librarySymbol}\')`;\n if (isExportedByForceFilesystem(sym)) {\n msg += ". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you";\n }\n warnOnce(msg);\n });\n unexportedRuntimeSymbol(sym);\n }\n function unexportedRuntimeSymbol(sym) {\n if (!Object.getOwnPropertyDescriptor(Module, sym)) {\n Object.defineProperty(Module, sym, {\n configurable: true,\n get() {\n var msg = `\'${sym}\' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)`;\n if (isExportedByForceFilesystem(sym)) {\n msg += ". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you";\n }\n abort(msg);\n }\n });\n }\n }\n var callRuntimeCallbacks = (callbacks) => {\n callbacks.forEach((f) => f(Module));\n };\n function getValue(ptr, type = "i8") {\n if (type.endsWith("*")) type = "*";\n switch (type) {\n case "i1":\n return HEAP8[ptr];\n case "i8":\n return HEAP8[ptr];\n case "i16":\n return HEAP16[ptr >> 1];\n case "i32":\n return HEAP32[ptr >> 2];\n case "i64":\n abort("to do getValue(i64) use WASM_BIGINT");\n case "float":\n return HEAPF32[ptr >> 2];\n case "double":\n return HEAPF64[ptr >> 3];\n case "*":\n return HEAPU32[ptr >> 2];\n default:\n abort(`invalid type for getValue: ${type}`);\n }\n }\n Module["noExitRuntime"] || true;\n var ptrToString = (ptr) => {\n assert(typeof ptr === "number");\n ptr >>>= 0;\n return "0x" + ptr.toString(16).padStart(8, "0");\n };\n function setValue(ptr, value, type = "i8") {\n if (type.endsWith("*")) type = "*";\n switch (type) {\n case "i1":\n HEAP8[ptr] = value;\n break;\n case "i8":\n HEAP8[ptr] = value;\n break;\n case "i16":\n HEAP16[ptr >> 1] = value;\n break;\n case "i32":\n HEAP32[ptr >> 2] = value;\n break;\n case "i64":\n abort("to do setValue(i64) use WASM_BIGINT");\n case "float":\n HEAPF32[ptr >> 2] = value;\n break;\n case "double":\n HEAPF64[ptr >> 3] = value;\n break;\n case "*":\n HEAPU32[ptr >> 2] = value;\n break;\n default:\n abort(`invalid type for setValue: ${type}`);\n }\n }\n var stackRestore = (val) => __emscripten_stack_restore(val);\n var stackSave = () => _emscripten_stack_get_current();\n var warnOnce = (text) => {\n warnOnce.shown || (warnOnce.shown = {});\n if (!warnOnce.shown[text]) {\n warnOnce.shown[text] = 1;\n err(text);\n }\n };\n var UTF8Decoder = typeof TextDecoder != "undefined" ? new TextDecoder() : void 0;\n var UTF8ArrayToString = (heapOrArray, idx = 0, maxBytesToRead = NaN) => {\n var endIdx = idx + maxBytesToRead;\n var endPtr = idx;\n while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr;\n if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {\n return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));\n }\n var str = "";\n while (idx < endPtr) {\n var u0 = heapOrArray[idx++];\n if (!(u0 & 128)) {\n str += String.fromCharCode(u0);\n continue;\n }\n var u1 = heapOrArray[idx++] & 63;\n if ((u0 & 224) == 192) {\n str += String.fromCharCode((u0 & 31) << 6 | u1);\n continue;\n }\n var u2 = heapOrArray[idx++] & 63;\n if ((u0 & 240) == 224) {\n u0 = (u0 & 15) << 12 | u1 << 6 | u2;\n } else {\n if ((u0 & 248) != 240)\n warnOnce(\n "Invalid UTF-8 leading byte " + ptrToString(u0) + " encountered when deserializing a UTF-8 string in wasm memory to a JS string!"\n );\n u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heapOrArray[idx++] & 63;\n }\n if (u0 < 65536) {\n str += String.fromCharCode(u0);\n } else {\n var ch = u0 - 65536;\n str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023);\n }\n }\n return str;\n };\n var UTF8ToString = (ptr, maxBytesToRead) => {\n assert(typeof ptr == "number", `UTF8ToString expects a number (got ${typeof ptr})`);\n return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : "";\n };\n var ___assert_fail = (condition, filename, line, func) => {\n abort(\n `Assertion failed: ${UTF8ToString(condition)}, at: ` + [\n filename ? UTF8ToString(filename) : "unknown filename",\n line,\n func ? UTF8ToString(func) : "unknown function"\n ]\n );\n };\n function syscallGetVarargI() {\n assert(SYSCALLS.varargs != void 0);\n var ret = HEAP32[+SYSCALLS.varargs >> 2];\n SYSCALLS.varargs += 4;\n return ret;\n }\n var syscallGetVarargP = syscallGetVarargI;\n var PATH = {\n isAbs: (path) => path.charAt(0) === "/",\n splitPath: (filename) => {\n var splitPathRe = /^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^\\/]+?|)(\\.[^.\\/]*|))(?:[\\/]*)$/;\n return splitPathRe.exec(filename).slice(1);\n },\n normalizeArray: (parts, allowAboveRoot) => {\n var up = 0;\n for (var i = parts.length - 1; i >= 0; i--) {\n var last = parts[i];\n if (last === ".") {\n parts.splice(i, 1);\n } else if (last === "..") {\n parts.splice(i, 1);\n up++;\n } else if (up) {\n parts.splice(i, 1);\n up--;\n }\n }\n if (allowAboveRoot) {\n for (; up; up--) {\n parts.unshift("..");\n }\n }\n return parts;\n },\n normalize: (path) => {\n var isAbsolute = PATH.isAbs(path), trailingSlash = path.substr(-1) === "/";\n path = PATH.normalizeArray(\n path.split("/").filter((p) => !!p),\n !isAbsolute\n ).join("/");\n if (!path && !isAbsolute) {\n path = ".";\n }\n if (path && trailingSlash) {\n path += "/";\n }\n return (isAbsolute ? "/" : "") + path;\n },\n dirname: (path) => {\n var result = PATH.splitPath(path), root = result[0], dir = result[1];\n if (!root && !dir) {\n return ".";\n }\n if (dir) {\n dir = dir.substr(0, dir.length - 1);\n }\n return root + dir;\n },\n basename: (path) => {\n if (path === "/") return "/";\n path = PATH.normalize(path);\n path = path.replace(/\\/$/, "");\n var lastSlash = path.lastIndexOf("/");\n if (lastSlash === -1) return path;\n return path.substr(lastSlash + 1);\n },\n join: (...paths) => PATH.normalize(paths.join("/")),\n join2: (l, r) => PATH.normalize(l + "/" + r)\n };\n var initRandomFill = () => {\n if (typeof crypto == "object" && typeof crypto["getRandomValues"] == "function") {\n return (view) => crypto.getRandomValues(view);\n }\n abort(\n "no cryptographic support found for randomDevice. consider polyfilling it if you want to use something insecure like Math.random(), e.g. put this in a --pre-js: var crypto = { getRandomValues: (array) => { for (var i = 0; i < array.length; i++) array[i] = (Math.random()*256)|0 } };"\n );\n };\n var randomFill = (view) => {\n return (randomFill = initRandomFill())(view);\n };\n var PATH_FS = {\n resolve: (...args) => {\n var resolvedPath = "", resolvedAbsolute = false;\n for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n var path = i >= 0 ? args[i] : FS.cwd();\n if (typeof path != "string") {\n throw new TypeError("Arguments to path.resolve must be strings");\n } else if (!path) {\n return "";\n }\n resolvedPath = path + "/" + resolvedPath;\n resolvedAbsolute = PATH.isAbs(path);\n }\n resolvedPath = PATH.normalizeArray(\n resolvedPath.split("/").filter((p) => !!p),\n !resolvedAbsolute\n ).join("/");\n return (resolvedAbsolute ? "/" : "") + resolvedPath || ".";\n },\n relative: (from, to) => {\n from = PATH_FS.resolve(from).substr(1);\n to = PATH_FS.resolve(to).substr(1);\n function trim(arr) {\n var start = 0;\n for (; start < arr.length; start++) {\n if (arr[start] !== "") break;\n }\n var end = arr.length - 1;\n for (; end >= 0; end--) {\n if (arr[end] !== "") break;\n }\n if (start > end) return [];\n return arr.slice(start, end - start + 1);\n }\n var fromParts = trim(from.split("/"));\n var toParts = trim(to.split("/"));\n var length = Math.min(fromParts.length, toParts.length);\n var samePartsLength = length;\n for (var i = 0; i < length; i++) {\n if (fromParts[i] !== toParts[i]) {\n samePartsLength = i;\n break;\n }\n }\n var outputParts = [];\n for (var i = samePartsLength; i < fromParts.length; i++) {\n outputParts.push("..");\n }\n outputParts = outputParts.concat(toParts.slice(samePartsLength));\n return outputParts.join("/");\n }\n };\n var FS_stdin_getChar_buffer = [];\n var lengthBytesUTF8 = (str) => {\n var len = 0;\n for (var i = 0; i < str.length; ++i) {\n var c = str.charCodeAt(i);\n if (c <= 127) {\n len++;\n } else if (c <= 2047) {\n len += 2;\n } else if (c >= 55296 && c <= 57343) {\n len += 4;\n ++i;\n } else {\n len += 3;\n }\n }\n return len;\n };\n var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {\n assert(typeof str === "string", `stringToUTF8Array expects a string (got ${typeof str})`);\n if (!(maxBytesToWrite > 0)) return 0;\n var startIdx = outIdx;\n var endIdx = outIdx + maxBytesToWrite - 1;\n for (var i = 0; i < str.length; ++i) {\n var u = str.charCodeAt(i);\n if (u >= 55296 && u <= 57343) {\n var u1 = str.charCodeAt(++i);\n u = 65536 + ((u & 1023) << 10) | u1 & 1023;\n }\n if (u <= 127) {\n if (outIdx >= endIdx) break;\n heap[outIdx++] = u;\n } else if (u <= 2047) {\n if (outIdx + 1 >= endIdx) break;\n heap[outIdx++] = 192 | u >> 6;\n heap[outIdx++] = 128 | u & 63;\n } else if (u <= 65535) {\n if (outIdx + 2 >= endIdx) break;\n heap[outIdx++] = 224 | u >> 12;\n heap[outIdx++] = 128 | u >> 6 & 63;\n heap[outIdx++] = 128 | u & 63;\n } else {\n if (outIdx + 3 >= endIdx) break;\n if (u > 1114111)\n warnOnce(\n "Invalid Unicode code point " + ptrToString(u) + " encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF)."\n );\n heap[outIdx++] = 240 | u >> 18;\n heap[outIdx++] = 128 | u >> 12 & 63;\n heap[outIdx++] = 128 | u >> 6 & 63;\n heap[outIdx++] = 128 | u & 63;\n }\n }\n heap[outIdx] = 0;\n return outIdx - startIdx;\n };\n function intArrayFromString(stringy, dontAddNull, length) {\n var len = lengthBytesUTF8(stringy) + 1;\n var u8array = new Array(len);\n var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);\n u8array.length = numBytesWritten;\n return u8array;\n }\n var FS_stdin_getChar = () => {\n if (!FS_stdin_getChar_buffer.length) {\n var result = null;\n if (typeof window != "undefined" && typeof window.prompt == "function") {\n result = window.prompt("Input: ");\n if (result !== null) {\n result += "\\n";\n }\n } else if (typeof readline == "function") {\n result = readline();\n if (result) {\n result += "\\n";\n }\n } else ;\n if (!result) {\n return null;\n }\n FS_stdin_getChar_buffer = intArrayFromString(result);\n }\n return FS_stdin_getChar_buffer.shift();\n };\n var TTY = {\n ttys: [],\n init() {\n },\n shutdown() {\n },\n register(dev, ops) {\n TTY.ttys[dev] = { input: [], output: [], ops };\n FS.registerDevice(dev, TTY.stream_ops);\n },\n stream_ops: {\n open(stream) {\n var tty = TTY.ttys[stream.node.rdev];\n if (!tty) {\n throw new FS.ErrnoError(43);\n }\n stream.tty = tty;\n stream.seekable = false;\n },\n close(stream) {\n stream.tty.ops.fsync(stream.tty);\n },\n fsync(stream) {\n stream.tty.ops.fsync(stream.tty);\n },\n read(stream, buffer, offset, length, pos) {\n if (!stream.tty || !stream.tty.ops.get_char) {\n throw new FS.ErrnoError(60);\n }\n var bytesRead = 0;\n for (var i = 0; i < length; i++) {\n var result;\n try {\n result = stream.tty.ops.get_char(stream.tty);\n } catch (e) {\n throw new FS.ErrnoError(29);\n }\n if (result === void 0 && bytesRead === 0) {\n throw new FS.ErrnoError(6);\n }\n if (result === null || result === void 0) break;\n bytesRead++;\n buffer[offset + i] = result;\n }\n if (bytesRead) {\n stream.node.timestamp = Date.now();\n }\n return bytesRead;\n },\n write(stream, buffer, offset, length, pos) {\n if (!stream.tty || !stream.tty.ops.put_char) {\n throw new FS.ErrnoError(60);\n }\n try {\n for (var i = 0; i < length; i++) {\n stream.tty.ops.put_char(stream.tty, buffer[offset + i]);\n }\n } catch (e) {\n throw new FS.ErrnoError(29);\n }\n if (length) {\n stream.node.timestamp = Date.now();\n }\n return i;\n }\n },\n default_tty_ops: {\n get_char(tty) {\n return FS_stdin_getChar();\n },\n put_char(tty, val) {\n if (val === null || val === 10) {\n out(UTF8ArrayToString(tty.output));\n tty.output = [];\n } else {\n if (val != 0) tty.output.push(val);\n }\n },\n fsync(tty) {\n if (tty.output && tty.output.length > 0) {\n out(UTF8ArrayToString(tty.output));\n tty.output = [];\n }\n },\n ioctl_tcgets(tty) {\n return {\n c_iflag: 25856,\n c_oflag: 5,\n c_cflag: 191,\n c_lflag: 35387,\n c_cc: [\n 3,\n 28,\n 127,\n 21,\n 4,\n 0,\n 1,\n 0,\n 17,\n 19,\n 26,\n 0,\n 18,\n 15,\n 23,\n 22,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0\n ]\n };\n },\n ioctl_tcsets(tty, optional_actions, data) {\n return 0;\n },\n ioctl_tiocgwinsz(tty) {\n return [24, 80];\n }\n },\n default_tty1_ops: {\n put_char(tty, val) {\n if (val === null || val === 10) {\n err(UTF8ArrayToString(tty.output));\n tty.output = [];\n } else {\n if (val != 0) tty.output.push(val);\n }\n },\n fsync(tty) {\n if (tty.output && tty.output.length > 0) {\n err(UTF8ArrayToString(tty.output));\n tty.output = [];\n }\n }\n }\n };\n var zeroMemory = (address, size) => {\n HEAPU8.fill(0, address, address + size);\n };\n var alignMemory = (size, alignment) => {\n assert(alignment, "alignment argument is required");\n return Math.ceil(size / alignment) * alignment;\n };\n var mmapAlloc = (size) => {\n size = alignMemory(size, 65536);\n var ptr = _emscripten_builtin_memalign(65536, size);\n if (ptr) zeroMemory(ptr, size);\n return ptr;\n };\n var MEMFS = {\n ops_table: null,\n mount(mount) {\n return MEMFS.createNode(null, "/", 16384 | 511, 0);\n },\n createNode(parent, name, mode, dev) {\n if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {\n throw new FS.ErrnoError(63);\n }\n MEMFS.ops_table || (MEMFS.ops_table = {\n dir: {\n node: {\n getattr: MEMFS.node_ops.getattr,\n setattr: MEMFS.node_ops.setattr,\n lookup: MEMFS.node_ops.lookup,\n mknod: MEMFS.node_ops.mknod,\n rename: MEMFS.node_ops.rename,\n unlink: MEMFS.node_ops.unlink,\n rmdir: MEMFS.node_ops.rmdir,\n readdir: MEMFS.node_ops.readdir,\n symlink: MEMFS.node_ops.symlink\n },\n stream: {\n llseek: MEMFS.stream_ops.llseek\n }\n },\n file: {\n node: {\n getattr: MEMFS.node_ops.getattr,\n setattr: MEMFS.node_ops.setattr\n },\n stream: {\n llseek: MEMFS.stream_ops.llseek,\n read: MEMFS.stream_ops.read,\n write: MEMFS.stream_ops.write,\n allocate: MEMFS.stream_ops.allocate,\n mmap: MEMFS.stream_ops.mmap,\n msync: MEMFS.stream_ops.msync\n }\n },\n link: {\n node: {\n getattr: MEMFS.node_ops.getattr,\n setattr: MEMFS.node_ops.setattr,\n readlink: MEMFS.node_ops.readlink\n },\n stream: {}\n },\n chrdev: {\n node: {\n getattr: MEMFS.node_ops.getattr,\n setattr: MEMFS.node_ops.setattr\n },\n stream: FS.chrdev_stream_ops\n }\n });\n var node = FS.createNode(parent, name, mode, dev);\n if (FS.isDir(node.mode)) {\n node.node_ops = MEMFS.ops_table.dir.node;\n node.stream_ops = MEMFS.ops_table.dir.stream;\n node.contents = {};\n } else if (FS.isFile(node.mode)) {\n node.node_ops = MEMFS.ops_table.file.node;\n node.stream_ops = MEMFS.ops_table.file.stream;\n node.usedBytes = 0;\n node.contents = null;\n } else if (FS.isLink(node.mode)) {\n node.node_ops = MEMFS.ops_table.link.node;\n node.stream_ops = MEMFS.ops_table.link.stream;\n } else if (FS.isChrdev(node.mode)) {\n node.node_ops = MEMFS.ops_table.chrdev.node;\n node.stream_ops = MEMFS.ops_table.chrdev.stream;\n }\n node.timestamp = Date.now();\n if (parent) {\n parent.contents[name] = node;\n parent.timestamp = node.timestamp;\n }\n return node;\n },\n getFileDataAsTypedArray(node) {\n if (!node.contents) return new Uint8Array(0);\n if (node.contents.subarray) return node.contents.subarray(0, node.usedBytes);\n return new Uint8Array(node.contents);\n },\n expandFileStorage(node, newCapacity) {\n var prevCapacity = node.contents ? node.contents.length : 0;\n if (prevCapacity >= newCapacity) return;\n var CAPACITY_DOUBLING_MAX = 1024 * 1024;\n newCapacity = Math.max(\n newCapacity,\n prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2 : 1.125) >>> 0\n );\n if (prevCapacity != 0) newCapacity = Math.max(newCapacity, 256);\n var oldContents = node.contents;\n node.contents = new Uint8Array(newCapacity);\n if (node.usedBytes > 0) node.contents.set(oldContents.subarray(0, node.usedBytes), 0);\n },\n resizeFileStorage(node, newSize) {\n if (node.usedBytes == newSize) return;\n if (newSize == 0) {\n node.contents = null;\n node.usedBytes = 0;\n } else {\n var oldContents = node.contents;\n node.contents = new Uint8Array(newSize);\n if (oldContents) {\n node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes)));\n }\n node.usedBytes = newSize;\n }\n },\n node_ops: {\n getattr(node) {\n var attr = {};\n attr.dev = FS.isChrdev(node.mode) ? node.id : 1;\n attr.ino = node.id;\n attr.mode = node.mode;\n attr.nlink = 1;\n attr.uid = 0;\n attr.gid = 0;\n attr.rdev = node.rdev;\n if (FS.isDir(node.mode)) {\n attr.size = 4096;\n } else if (FS.isFile(node.mode)) {\n attr.size = node.usedBytes;\n } else if (FS.isLink(node.mode)) {\n attr.size = node.link.length;\n } else {\n attr.size = 0;\n }\n attr.atime = new Date(node.timestamp);\n attr.mtime = new Date(node.timestamp);\n attr.ctime = new Date(node.timestamp);\n attr.blksize = 4096;\n attr.blocks = Math.ceil(attr.size / attr.blksize);\n return attr;\n },\n setattr(node, attr) {\n if (attr.mode !== void 0) {\n node.mode = attr.mode;\n }\n if (attr.timestamp !== void 0) {\n node.timestamp = attr.timestamp;\n }\n if (attr.size !== void 0) {\n MEMFS.resizeFileStorage(node, attr.size);\n }\n },\n lookup(parent, name) {\n throw FS.genericErrors[44];\n },\n mknod(parent, name, mode, dev) {\n return MEMFS.createNode(parent, name, mode, dev);\n },\n rename(old_node, new_dir, new_name) {\n if (FS.isDir(old_node.mode)) {\n var new_node;\n try {\n new_node = FS.lookupNode(new_dir, new_name);\n } catch (e) {\n }\n if (new_node) {\n for (var i in new_node.contents) {\n throw new FS.ErrnoError(55);\n }\n }\n }\n delete old_node.parent.contents[old_node.name];\n old_node.parent.timestamp = Date.now();\n old_node.name = new_name;\n new_dir.contents[new_name] = old_node;\n new_dir.timestamp = old_node.parent.timestamp;\n },\n unlink(parent, name) {\n delete parent.contents[name];\n parent.timestamp = Date.now();\n },\n rmdir(parent, name) {\n var node = FS.lookupNode(parent, name);\n for (var i in node.contents) {\n throw new FS.ErrnoError(55);\n }\n delete parent.contents[name];\n parent.timestamp = Date.now();\n },\n readdir(node) {\n var entries = [".", ".."];\n for (var key of Object.keys(node.contents)) {\n entries.push(key);\n }\n return entries;\n },\n symlink(parent, newname, oldpath) {\n var node = MEMFS.createNode(parent, newname, 511 | 40960, 0);\n node.link = oldpath;\n return node;\n },\n readlink(node) {\n if (!FS.isLink(node.mode)) {\n throw new FS.ErrnoError(28);\n }\n return node.link;\n }\n },\n stream_ops: {\n read(stream, buffer, offset, length, position) {\n var contents = stream.node.contents;\n if (position >= stream.node.usedBytes) return 0;\n var size = Math.min(stream.node.usedBytes - position, length);\n assert(size >= 0);\n if (size > 8 && contents.subarray) {\n buffer.set(contents.subarray(position, position + size), offset);\n } else {\n for (var i = 0; i < size; i++) buffer[offset + i] = contents[position + i];\n }\n return size;\n },\n write(stream, buffer, offset, length, position, canOwn) {\n assert(!(buffer instanceof ArrayBuffer));\n if (buffer.buffer === HEAP8.buffer) {\n canOwn = false;\n }\n if (!length) return 0;\n var node = stream.node;\n node.timestamp = Date.now();\n if (buffer.subarray && (!node.contents || node.contents.subarray)) {\n if (canOwn) {\n assert(position === 0, "canOwn must imply no weird position inside the file");\n node.contents = buffer.subarray(offset, offset + length);\n node.usedBytes = length;\n return length;\n } else if (node.usedBytes === 0 && position === 0) {\n node.contents = buffer.slice(offset, offset + length);\n node.usedBytes = length;\n return length;\n } else if (position + length <= node.usedBytes) {\n node.contents.set(buffer.subarray(offset, offset + length), position);\n return length;\n }\n }\n MEMFS.expandFileStorage(node, position + length);\n if (node.contents.subarray && buffer.subarray) {\n node.contents.set(buffer.subarray(offset, offset + length), position);\n } else {\n for (var i = 0; i < length; i++) {\n node.contents[position + i] = buffer[offset + i];\n }\n }\n node.usedBytes = Math.max(node.usedBytes, position + length);\n return length;\n },\n llseek(stream, offset, whence) {\n var position = offset;\n if (whence === 1) {\n position += stream.position;\n } else if (whence === 2) {\n if (FS.isFile(stream.node.mode)) {\n position += stream.node.usedBytes;\n }\n }\n if (position < 0) {\n throw new FS.ErrnoError(28);\n }\n return position;\n },\n allocate(stream, offset, length) {\n MEMFS.expandFileStorage(stream.node, offset + length);\n stream.node.usedBytes = Math.max(stream.node.usedBytes, offset + length);\n },\n mmap(stream, length, position, prot, flags) {\n if (!FS.isFile(stream.node.mode)) {\n throw new FS.ErrnoError(43);\n }\n var ptr;\n var allocated;\n var contents = stream.node.contents;\n if (!(flags & 2) && contents && contents.buffer === HEAP8.buffer) {\n allocated = false;\n ptr = contents.byteOffset;\n } else {\n allocated = true;\n ptr = mmapAlloc(length);\n if (!ptr) {\n throw new FS.ErrnoError(48);\n }\n if (contents) {\n if (position > 0 || position + length < contents.length) {\n if (contents.subarray) {\n contents = contents.subarray(position, position + length);\n } else {\n contents = Array.prototype.slice.call(contents, position, position + length);\n }\n }\n HEAP8.set(contents, ptr);\n }\n }\n return { ptr, allocated };\n },\n msync(stream, buffer, offset, length, mmapFlags) {\n MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false);\n return 0;\n }\n }\n };\n var asyncLoad = (url, onload, onerror, noRunDep) => {\n var dep = getUniqueRunDependency(`al ${url}`);\n readAsync(url).then(\n (arrayBuffer) => {\n assert(arrayBuffer, `Loading data file "${url}" failed (no arrayBuffer).`);\n onload(new Uint8Array(arrayBuffer));\n if (dep) removeRunDependency(dep);\n },\n (err2) => {\n if (onerror) {\n onerror();\n } else {\n throw `Loading data file "${url}" failed.`;\n }\n }\n );\n if (dep) addRunDependency(dep);\n };\n var FS_createDataFile = (parent, name, fileData, canRead, canWrite, canOwn) => {\n FS.createDataFile(parent, name, fileData, canRead, canWrite, canOwn);\n };\n var preloadPlugins = Module["preloadPlugins"] || [];\n var FS_handledByPreloadPlugin = (byteArray, fullname, finish, onerror) => {\n if (typeof Browser != "undefined") Browser.init();\n var handled = false;\n preloadPlugins.forEach((plugin) => {\n if (handled) return;\n if (plugin["canHandle"](fullname)) {\n plugin["handle"](byteArray, fullname, finish, onerror);\n handled = true;\n }\n });\n return handled;\n };\n var FS_createPreloadedFile = (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) => {\n var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent;\n var dep = getUniqueRunDependency(`cp ${fullname}`);\n function processData(byteArray) {\n function finish(byteArray2) {\n preFinish == null ? void 0 : preFinish();\n if (!dontCreateFile) {\n FS_createDataFile(parent, name, byteArray2, canRead, canWrite, canOwn);\n }\n onload == null ? void 0 : onload();\n removeRunDependency(dep);\n }\n if (FS_handledByPreloadPlugin(byteArray, fullname, finish, () => {\n onerror == null ? void 0 : onerror();\n removeRunDependency(dep);\n })) {\n return;\n }\n finish(byteArray);\n }\n addRunDependency(dep);\n if (typeof url == "string") {\n asyncLoad(url, processData, onerror);\n } else {\n processData(url);\n }\n };\n var FS_modeStringToFlags = (str) => {\n var flagModes = {\n r: 0,\n "r+": 2,\n w: 512 | 64 | 1,\n "w+": 512 | 64 | 2,\n a: 1024 | 64 | 1,\n "a+": 1024 | 64 | 2\n };\n var flags = flagModes[str];\n if (typeof flags == "undefined") {\n throw new Error(`Unknown file open mode: ${str}`);\n }\n return flags;\n };\n var FS_getMode = (canRead, canWrite) => {\n var mode = 0;\n if (canRead) mode |= 292 | 73;\n if (canWrite) mode |= 146;\n return mode;\n };\n var strError = (errno) => {\n return UTF8ToString(_strerror(errno));\n };\n var ERRNO_CODES = {\n EPERM: 63,\n ENOENT: 44,\n ESRCH: 71,\n EINTR: 27,\n EIO: 29,\n ENXIO: 60,\n E2BIG: 1,\n ENOEXEC: 45,\n EBADF: 8,\n ECHILD: 12,\n EAGAIN: 6,\n EWOULDBLOCK: 6,\n ENOMEM: 48,\n EACCES: 2,\n EFAULT: 21,\n ENOTBLK: 105,\n EBUSY: 10,\n EEXIST: 20,\n EXDEV: 75,\n ENODEV: 43,\n ENOTDIR: 54,\n EISDIR: 31,\n EINVAL: 28,\n ENFILE: 41,\n EMFILE: 33,\n ENOTTY: 59,\n ETXTBSY: 74,\n EFBIG: 22,\n ENOSPC: 51,\n ESPIPE: 70,\n EROFS: 69,\n EMLINK: 34,\n EPIPE: 64,\n EDOM: 18,\n ERANGE: 68,\n ENOMSG: 49,\n EIDRM: 24,\n ECHRNG: 106,\n EL2NSYNC: 156,\n EL3HLT: 107,\n EL3RST: 108,\n ELNRNG: 109,\n EUNATCH: 110,\n ENOCSI: 111,\n EL2HLT: 112,\n EDEADLK: 16,\n ENOLCK: 46,\n EBADE: 113,\n EBADR: 114,\n EXFULL: 115,\n ENOANO: 104,\n EBADRQC: 103,\n EBADSLT: 102,\n EDEADLOCK: 16,\n EBFONT: 101,\n ENOSTR: 100,\n ENODATA: 116,\n ETIME: 117,\n ENOSR: 118,\n ENONET: 119,\n ENOPKG: 120,\n EREMOTE: 121,\n ENOLINK: 47,\n EADV: 122,\n ESRMNT: 123,\n ECOMM: 124,\n EPROTO: 65,\n EMULTIHOP: 36,\n EDOTDOT: 125,\n EBADMSG: 9,\n ENOTUNIQ: 126,\n EBADFD: 127,\n EREMCHG: 128,\n ELIBACC: 129,\n ELIBBAD: 130,\n ELIBSCN: 131,\n ELIBMAX: 132,\n ELIBEXEC: 133,\n ENOSYS: 52,\n ENOTEMPTY: 55,\n ENAMETOOLONG: 37,\n ELOOP: 32,\n EOPNOTSUPP: 138,\n EPFNOSUPPORT: 139,\n ECONNRESET: 15,\n ENOBUFS: 42,\n EAFNOSUPPORT: 5,\n EPROTOTYPE: 67,\n ENOTSOCK: 57,\n ENOPROTOOPT: 50,\n ESHUTDOWN: 140,\n ECONNREFUSED: 14,\n EADDRINUSE: 3,\n ECONNABORTED: 13,\n ENETUNREACH: 40,\n ENETDOWN: 38,\n ETIMEDOUT: 73,\n EHOSTDOWN: 142,\n EHOSTUNREACH: 23,\n EINPROGRESS: 26,\n EALREADY: 7,\n EDESTADDRREQ: 17,\n EMSGSIZE: 35,\n EPROTONOSUPPORT: 66,\n ESOCKTNOSUPPORT: 137,\n EADDRNOTAVAIL: 4,\n ENETRESET: 39,\n EISCONN: 30,\n ENOTCONN: 53,\n ETOOMANYREFS: 141,\n EUSERS: 136,\n EDQUOT: 19,\n ESTALE: 72,\n ENOTSUP: 138,\n ENOMEDIUM: 148,\n EILSEQ: 25,\n EOVERFLOW: 61,\n ECANCELED: 11,\n ENOTRECOVERABLE: 56,\n EOWNERDEAD: 62,\n ESTRPIPE: 135\n };\n var FS = {\n root: null,\n mounts: [],\n devices: {},\n streams: [],\n nextInode: 1,\n nameTable: null,\n currentPath: "/",\n initialized: false,\n ignorePermissions: true,\n ErrnoError: class extends Error {\n // We set the `name` property to be able to identify `FS.ErrnoError`\n // - the `name` is a standard ECMA-262 property of error objects. Kind of good to have it anyway.\n // - when using PROXYFS, an error can come from an underlying FS\n // as different FS objects have their own FS.ErrnoError each,\n // the test `err instanceof FS.ErrnoError` won\'t detect an error coming from another filesystem, causing bugs.\n // we\'ll use the reliable test `err.name == "ErrnoError"` instead\n constructor(errno) {\n super(runtimeInitialized ? strError(errno) : "");\n this.name = "ErrnoError";\n this.errno = errno;\n for (var key in ERRNO_CODES) {\n if (ERRNO_CODES[key] === errno) {\n this.code = key;\n break;\n }\n }\n }\n },\n genericErrors: {},\n filesystems: null,\n syncFSRequests: 0,\n readFiles: {},\n FSStream: class {\n constructor() {\n this.shared = {};\n }\n get object() {\n return this.node;\n }\n set object(val) {\n this.node = val;\n }\n get isRead() {\n return (this.flags & 2097155) !== 1;\n }\n get isWrite() {\n return (this.flags & 2097155) !== 0;\n }\n get isAppend() {\n return this.flags & 1024;\n }\n get flags() {\n return this.shared.flags;\n }\n set flags(val) {\n this.shared.flags = val;\n }\n get position() {\n return this.shared.position;\n }\n set position(val) {\n this.shared.position = val;\n }\n },\n FSNode: class {\n constructor(parent, name, mode, rdev) {\n if (!parent) {\n parent = this;\n }\n this.parent = parent;\n this.mount = parent.mount;\n this.mounted = null;\n this.id = FS.nextInode++;\n this.name = name;\n this.mode = mode;\n this.node_ops = {};\n this.stream_ops = {};\n this.rdev = rdev;\n this.readMode = 292 | 73;\n this.writeMode = 146;\n }\n get read() {\n return (this.mode & this.readMode) === this.readMode;\n }\n set read(val) {\n val ? this.mode |= this.readMode : this.mode &= ~this.readMode;\n }\n get write() {\n return (this.mode & this.writeMode) === this.writeMode;\n }\n set write(val) {\n val ? this.mode |= this.writeMode : this.mode &= ~this.writeMode;\n }\n get isFolder() {\n return FS.isDir(this.mode);\n }\n get isDevice() {\n return FS.isChrdev(this.mode);\n }\n },\n lookupPath(path, opts = {}) {\n path = PATH_FS.resolve(path);\n if (!path) return { path: "", node: null };\n var defaults = {\n follow_mount: true,\n recurse_count: 0\n };\n opts = Object.assign(defaults, opts);\n if (opts.recurse_count > 8) {\n throw new FS.ErrnoError(32);\n }\n var parts = path.split("/").filter((p) => !!p);\n var current = FS.root;\n var current_path = "/";\n for (var i = 0; i < parts.length; i++) {\n var islast = i === parts.length - 1;\n if (islast && opts.parent) {\n break;\n }\n current = FS.lookupNode(current, parts[i]);\n current_path = PATH.join2(current_path, parts[i]);\n if (FS.isMountpoint(current)) {\n if (!islast || islast && opts.follow_mount) {\n current = current.mounted.root;\n }\n }\n if (!islast || opts.follow) {\n var count = 0;\n while (FS.isLink(current.mode)) {\n var link = FS.readlink(current_path);\n current_path = PATH_FS.resolve(PATH.dirname(current_path), link);\n var lookup = FS.lookupPath(current_path, { recurse_count: opts.recurse_count + 1 });\n current = lookup.node;\n if (count++ > 40) {\n throw new FS.ErrnoError(32);\n }\n }\n }\n }\n return { path: current_path, node: current };\n },\n getPath(node) {\n var path;\n while (true) {\n if (FS.isRoot(node)) {\n var mount = node.mount.mountpoint;\n if (!path) return mount;\n return mount[mount.length - 1] !== "/" ? `${mount}/${path}` : mount + path;\n }\n path = path ? `${node.name}/${path}` : node.name;\n node = node.parent;\n }\n },\n hashName(parentid, name) {\n var hash = 0;\n for (var i = 0; i < name.length; i++) {\n hash = (hash << 5) - hash + name.charCodeAt(i) | 0;\n }\n return (parentid + hash >>> 0) % FS.nameTable.length;\n },\n hashAddNode(node) {\n var hash = FS.hashName(node.parent.id, node.name);\n node.name_next = FS.nameTable[hash];\n FS.nameTable[hash] = node;\n },\n hashRemoveNode(node) {\n var hash = FS.hashName(node.parent.id, node.name);\n if (FS.nameTable[hash] === node) {\n FS.nameTable[hash] = node.name_next;\n } else {\n var current = FS.nameTable[hash];\n while (current) {\n if (current.name_next === node) {\n current.name_next = node.name_next;\n break;\n }\n current = current.name_next;\n }\n }\n },\n lookupNode(parent, name) {\n var errCode = FS.mayLookup(parent);\n if (errCode) {\n throw new FS.ErrnoError(errCode);\n }\n var hash = FS.hashName(parent.id, name);\n for (var node = FS.nameTable[hash]; node; node = node.name_next) {\n var nodeName = node.name;\n if (node.parent.id === parent.id && nodeName === name) {\n return node;\n }\n }\n return FS.lookup(parent, name);\n },\n createNode(parent, name, mode, rdev) {\n assert(typeof parent == "object");\n var node = new FS.FSNode(parent, name, mode, rdev);\n FS.hashAddNode(node);\n return node;\n },\n destroyNode(node) {\n FS.hashRemoveNode(node);\n },\n isRoot(node) {\n return node === node.parent;\n },\n isMountpoint(node) {\n return !!node.mounted;\n },\n isFile(mode) {\n return (mode & 61440) === 32768;\n },\n isDir(mode) {\n return (mode & 61440) === 16384;\n },\n isLink(mode) {\n return (mode & 61440) === 40960;\n },\n isChrdev(mode) {\n return (mode & 61440) === 8192;\n },\n isBlkdev(mode) {\n return (mode & 61440) === 24576;\n },\n isFIFO(mode) {\n return (mode & 61440) === 4096;\n },\n isSocket(mode) {\n return (mode & 49152) === 49152;\n },\n flagsToPermissionString(flag) {\n var perms = ["r", "w", "rw"][flag & 3];\n if (flag & 512) {\n perms += "w";\n }\n return perms;\n },\n nodePermissions(node, perms) {\n if (FS.ignorePermissions) {\n return 0;\n }\n if (perms.includes("r") && !(node.mode & 292)) {\n return 2;\n } else if (perms.includes("w") && !(node.mode & 146)) {\n return 2;\n } else if (perms.includes("x") && !(node.mode & 73)) {\n return 2;\n }\n return 0;\n },\n mayLookup(dir) {\n if (!FS.isDir(dir.mode)) return 54;\n var errCode = FS.nodePermissions(dir, "x");\n if (errCode) return errCode;\n if (!dir.node_ops.lookup) return 2;\n return 0;\n },\n mayCreate(dir, name) {\n try {\n var node = FS.lookupNode(dir, name);\n return 20;\n } catch (e) {\n }\n return FS.nodePermissions(dir, "wx");\n },\n mayDelete(dir, name, isdir) {\n var node;\n try {\n node = FS.lookupNode(dir, name);\n } catch (e) {\n return e.errno;\n }\n var errCode = FS.nodePermissions(dir, "wx");\n if (errCode) {\n return errCode;\n }\n if (isdir) {\n if (!FS.isDir(node.mode)) {\n return 54;\n }\n if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {\n return 10;\n }\n } else {\n if (FS.isDir(node.mode)) {\n return 31;\n }\n }\n return 0;\n },\n mayOpen(node, flags) {\n if (!node) {\n return 44;\n }\n if (FS.isLink(node.mode)) {\n return 32;\n } else if (FS.isDir(node.mode)) {\n if (FS.flagsToPermissionString(flags) !== "r" || // opening for write\n flags & 512) {\n return 31;\n }\n }\n return FS.nodePermissions(node, FS.flagsToPermissionString(flags));\n },\n MAX_OPEN_FDS: 4096,\n nextfd() {\n for (var fd = 0; fd <= FS.MAX_OPEN_FDS; fd++) {\n if (!FS.streams[fd]) {\n return fd;\n }\n }\n throw new FS.ErrnoError(33);\n },\n getStreamChecked(fd) {\n var stream = FS.getStream(fd);\n if (!stream) {\n throw new FS.ErrnoError(8);\n }\n return stream;\n },\n getStream: (fd) => FS.streams[fd],\n createStream(stream, fd = -1) {\n assert(fd >= -1);\n stream = Object.assign(new FS.FSStream(), stream);\n if (fd == -1) {\n fd = FS.nextfd();\n }\n stream.fd = fd;\n FS.streams[fd] = stream;\n return stream;\n },\n closeStream(fd) {\n FS.streams[fd] = null;\n },\n dupStream(origStream, fd = -1) {\n var _a, _b;\n var stream = FS.createStream(origStream, fd);\n (_b = (_a = stream.stream_ops) == null ? void 0 : _a.dup) == null ? void 0 : _b.call(_a, stream);\n return stream;\n },\n chrdev_stream_ops: {\n open(stream) {\n var _a, _b;\n var device = FS.getDevice(stream.node.rdev);\n stream.stream_ops = device.stream_ops;\n (_b = (_a = stream.stream_ops).open) == null ? void 0 : _b.call(_a, stream);\n },\n llseek() {\n throw new FS.ErrnoError(70);\n }\n },\n major: (dev) => dev >> 8,\n minor: (dev) => dev & 255,\n makedev: (ma, mi) => ma << 8 | mi,\n registerDevice(dev, ops) {\n FS.devices[dev] = { stream_ops: ops };\n },\n getDevice: (dev) => FS.devices[dev],\n getMounts(mount) {\n var mounts = [];\n var check = [mount];\n while (check.length) {\n var m = check.pop();\n mounts.push(m);\n check.push(...m.mounts);\n }\n return mounts;\n },\n syncfs(populate, callback) {\n if (typeof populate == "function") {\n callback = populate;\n populate = false;\n }\n FS.syncFSRequests++;\n if (FS.syncFSRequests > 1) {\n err(\n `warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`\n );\n }\n var mounts = FS.getMounts(FS.root.mount);\n var completed = 0;\n function doCallback(errCode) {\n assert(FS.syncFSRequests > 0);\n FS.syncFSRequests--;\n return callback(errCode);\n }\n function done(errCode) {\n if (errCode) {\n if (!done.errored) {\n done.errored = true;\n return doCallback(errCode);\n }\n return;\n }\n if (++completed >= mounts.length) {\n doCallback(null);\n }\n }\n mounts.forEach((mount) => {\n if (!mount.type.syncfs) {\n return done(null);\n }\n mount.type.syncfs(mount, populate, done);\n });\n },\n mount(type, opts, mountpoint) {\n if (typeof type == "string") {\n throw type;\n }\n var root = mountpoint === "/";\n var pseudo = !mountpoint;\n var node;\n if (root && FS.root) {\n throw new FS.ErrnoError(10);\n } else if (!root && !pseudo) {\n var lookup = FS.lookupPath(mountpoint, { follow_mount: false });\n mountpoint = lookup.path;\n node = lookup.node;\n if (FS.isMountpoint(node)) {\n throw new FS.ErrnoError(10);\n }\n if (!FS.isDir(node.mode)) {\n throw new FS.ErrnoError(54);\n }\n }\n var mount = {\n type,\n opts,\n mountpoint,\n mounts: []\n };\n var mountRoot = type.mount(mount);\n mountRoot.mount = mount;\n mount.root = mountRoot;\n if (root) {\n FS.root = mountRoot;\n } else if (node) {\n node.mounted = mount;\n if (node.mount) {\n node.mount.mounts.push(mount);\n }\n }\n return mountRoot;\n },\n unmount(mountpoint) {\n var lookup = FS.lookupPath(mountpoint, { follow_mount: false });\n if (!FS.isMountpoint(lookup.node)) {\n throw new FS.ErrnoError(28);\n }\n var node = lookup.node;\n var mount = node.mounted;\n var mounts = FS.getMounts(mount);\n Object.keys(FS.nameTable).forEach((hash) => {\n var current = FS.nameTable[hash];\n while (current) {\n var next = current.name_next;\n if (mounts.includes(current.mount)) {\n FS.destroyNode(current);\n }\n current = next;\n }\n });\n node.mounted = null;\n var idx = node.mount.mounts.indexOf(mount);\n assert(idx !== -1);\n node.mount.mounts.splice(idx, 1);\n },\n lookup(parent, name) {\n return parent.node_ops.lookup(parent, name);\n },\n mknod(path, mode, dev) {\n var lookup = FS.lookupPath(path, { parent: true });\n var parent = lookup.node;\n var name = PATH.basename(path);\n if (!name || name === "." || name === "..") {\n throw new FS.ErrnoError(28);\n }\n var errCode = FS.mayCreate(parent, name);\n if (errCode) {\n throw new FS.ErrnoError(errCode);\n }\n if (!parent.node_ops.mknod) {\n throw new FS.ErrnoError(63);\n }\n return parent.node_ops.mknod(parent, name, mode, dev);\n },\n create(path, mode) {\n mode = mode !== void 0 ? mode : 438;\n mode &= 4095;\n mode |= 32768;\n return FS.mknod(path, mode, 0);\n },\n mkdir(path, mode) {\n mode = mode !== void 0 ? mode : 511;\n mode &= 511 | 512;\n mode |= 16384;\n return FS.mknod(path, mode, 0);\n },\n mkdirTree(path, mode) {\n var dirs = path.split("/");\n var d = "";\n for (var i = 0; i < dirs.length; ++i) {\n if (!dirs[i]) continue;\n d += "/" + dirs[i];\n try {\n FS.mkdir(d, mode);\n } catch (e) {\n if (e.errno != 20) throw e;\n }\n }\n },\n mkdev(path, mode, dev) {\n if (typeof dev == "undefined") {\n dev = mode;\n mode = 438;\n }\n mode |= 8192;\n return FS.mknod(path, mode, dev);\n },\n symlink(oldpath, newpath) {\n if (!PATH_FS.resolve(oldpath)) {\n throw new FS.ErrnoError(44);\n }\n var lookup = FS.lookupPath(newpath, { parent: true });\n var parent = lookup.node;\n if (!parent) {\n throw new FS.ErrnoError(44);\n }\n var newname = PATH.basename(newpath);\n var errCode = FS.mayCreate(parent, newname);\n if (errCode) {\n throw new FS.ErrnoError(errCode);\n }\n if (!parent.node_ops.symlink) {\n throw new FS.ErrnoError(63);\n }\n return parent.node_ops.symlink(parent, newname, oldpath);\n },\n rename(old_path, new_path) {\n var old_dirname = PATH.dirname(old_path);\n var new_dirname = PATH.dirname(new_path);\n var old_name = PATH.basename(old_path);\n var new_name = PATH.basename(new_path);\n var lookup, old_dir, new_dir;\n lookup = FS.lookupPath(old_path, { parent: true });\n old_dir = lookup.node;\n lookup = FS.lookupPath(new_path, { parent: true });\n new_dir = lookup.node;\n if (!old_dir || !new_dir) throw new FS.ErrnoError(44);\n if (old_dir.mount !== new_dir.mount) {\n throw new FS.ErrnoError(75);\n }\n var old_node = FS.lookupNode(old_dir, old_name);\n var relative = PATH_FS.relative(old_path, new_dirname);\n if (relative.charAt(0) !== ".") {\n throw new FS.ErrnoError(28);\n }\n relative = PATH_FS.relative(new_path, old_dirname);\n if (relative.charAt(0) !== ".") {\n throw new FS.ErrnoError(55);\n }\n var new_node;\n try {\n new_node = FS.lookupNode(new_dir, new_name);\n } catch (e) {\n }\n if (old_node === new_node) {\n return;\n }\n var isdir = FS.isDir(old_node.mode);\n var errCode = FS.mayDelete(old_dir, old_name, isdir);\n if (errCode) {\n throw new FS.ErrnoError(errCode);\n }\n errCode = new_node ? FS.mayDelete(new_dir, new_name, isdir) : FS.mayCreate(new_dir, new_name);\n if (errCode) {\n throw new FS.ErrnoError(errCode);\n }\n if (!old_dir.node_ops.rename) {\n throw new FS.ErrnoError(63);\n }\n if (FS.isMountpoint(old_node) || new_node && FS.isMountpoint(new_node)) {\n throw new FS.ErrnoError(10);\n }\n if (new_dir !== old_dir) {\n errCode = FS.nodePermissions(old_dir, "w");\n if (errCode) {\n throw new FS.ErrnoError(errCode);\n }\n }\n FS.hashRemoveNode(old_node);\n try {\n old_dir.node_ops.rename(old_node, new_dir, new_name);\n old_node.parent = new_dir;\n } catch (e) {\n throw e;\n } finally {\n FS.hashAddNode(old_node);\n }\n },\n rmdir(path) {\n var lookup = FS.lookupPath(path, { parent: true });\n var parent = lookup.node;\n var name = PATH.basename(path);\n var node = FS.lookupNode(parent, name);\n var errCode = FS.mayDelete(parent, name, true);\n if (errCode) {\n throw new FS.ErrnoError(errCode);\n }\n if (!parent.node_ops.rmdir) {\n throw new FS.ErrnoError(63);\n }\n if (FS.isMountpoint(node)) {\n throw new FS.ErrnoError(10);\n }\n parent.node_ops.rmdir(parent, name);\n FS.destroyNode(node);\n },\n readdir(path) {\n var lookup = FS.lookupPath(path, { follow: true });\n var node = lookup.node;\n if (!node.node_ops.readdir) {\n throw new FS.ErrnoError(54);\n }\n return node.node_ops.readdir(node);\n },\n unlink(path) {\n var lookup = FS.lookupPath(path, { parent: true });\n var parent = lookup.node;\n if (!parent) {\n throw new FS.ErrnoError(44);\n }\n var name = PATH.basename(path);\n var node = FS.lookupNode(parent, name);\n var errCode = FS.mayDelete(parent, name, false);\n if (errCode) {\n throw new FS.ErrnoError(errCode);\n }\n if (!parent.node_ops.unlink) {\n throw new FS.ErrnoError(63);\n }\n if (FS.isMountpoint(node)) {\n throw new FS.ErrnoError(10);\n }\n parent.node_ops.unlink(parent, name);\n FS.destroyNode(node);\n },\n readlink(path) {\n var lookup = FS.lookupPath(path);\n var link = lookup.node;\n if (!link) {\n throw new FS.ErrnoError(44);\n }\n if (!link.node_ops.readlink) {\n throw new FS.ErrnoError(28);\n }\n return PATH_FS.resolve(FS.getPath(link.parent), link.node_ops.readlink(link));\n },\n stat(path, dontFollow) {\n var lookup = FS.lookupPath(path, { follow: !dontFollow });\n var node = lookup.node;\n if (!node) {\n throw new FS.ErrnoError(44);\n }\n if (!node.node_ops.getattr) {\n throw new FS.ErrnoError(63);\n }\n return node.node_ops.getattr(node);\n },\n lstat(path) {\n return FS.stat(path, true);\n },\n chmod(path, mode, dontFollow) {\n var node;\n if (typeof path == "string") {\n var lookup = FS.lookupPath(path, { follow: !dontFollow });\n node = lookup.node;\n } else {\n node = path;\n }\n if (!node.node_ops.setattr) {\n throw new FS.ErrnoError(63);\n }\n node.node_ops.setattr(node, {\n mode: mode & 4095 | node.mode & -4096,\n timestamp: Date.now()\n });\n },\n lchmod(path, mode) {\n FS.chmod(path, mode, true);\n },\n fchmod(fd, mode) {\n var stream = FS.getStreamChecked(fd);\n FS.chmod(stream.node, mode);\n },\n chown(path, uid, gid, dontFollow) {\n var node;\n if (typeof path == "string") {\n var lookup = FS.lookupPath(path, { follow: !dontFollow });\n node = lookup.node;\n } else {\n node = path;\n }\n if (!node.node_ops.setattr) {\n throw new FS.ErrnoError(63);\n }\n node.node_ops.setattr(node, {\n timestamp: Date.now()\n // we ignore the uid / gid for now\n });\n },\n lchown(path, uid, gid) {\n FS.chown(path, uid, gid, true);\n },\n fchown(fd, uid, gid) {\n var stream = FS.getStreamChecked(fd);\n FS.chown(stream.node, uid, gid);\n },\n truncate(path, len) {\n if (len < 0) {\n throw new FS.ErrnoError(28);\n }\n var node;\n if (typeof path == "string") {\n var lookup = FS.lookupPath(path, { follow: true });\n node = lookup.node;\n } else {\n node = path;\n }\n if (!node.node_ops.setattr) {\n throw new FS.ErrnoError(63);\n }\n if (FS.isDir(node.mode)) {\n throw new FS.ErrnoError(31);\n }\n if (!FS.isFile(node.mode)) {\n throw new FS.ErrnoError(28);\n }\n var errCode = FS.nodePermissions(node, "w");\n if (errCode) {\n throw new FS.ErrnoError(errCode);\n }\n node.node_ops.setattr(node, {\n size: len,\n timestamp: Date.now()\n });\n },\n ftruncate(fd, len) {\n var stream = FS.getStreamChecked(fd);\n if ((stream.flags & 2097155) === 0) {\n throw new FS.ErrnoError(28);\n }\n FS.truncate(stream.node, len);\n },\n utime(path, atime, mtime) {\n var lookup = FS.lookupPath(path, { follow: true });\n var node = lookup.node;\n node.node_ops.setattr(node, {\n timestamp: Math.max(atime, mtime)\n });\n },\n open(path, flags, mode) {\n if (path === "") {\n throw new FS.ErrnoError(44);\n }\n flags = typeof flags == "string" ? FS_modeStringToFlags(flags) : flags;\n if (flags & 64) {\n mode = typeof mode == "undefined" ? 438 : mode;\n mode = mode & 4095 | 32768;\n } else {\n mode = 0;\n }\n var node;\n if (typeof path == "object") {\n node = path;\n } else {\n path = PATH.normalize(path);\n try {\n var lookup = FS.lookupPath(path, {\n follow: !(flags & 131072)\n });\n node = lookup.node;\n } catch (e) {\n }\n }\n var created = false;\n if (flags & 64) {\n if (node) {\n if (flags & 128) {\n throw new FS.ErrnoError(20);\n }\n } else {\n node = FS.mknod(path, mode, 0);\n created = true;\n }\n }\n if (!node) {\n throw new FS.ErrnoError(44);\n }\n if (FS.isChrdev(node.mode)) {\n flags &= -513;\n }\n if (flags & 65536 && !FS.isDir(node.mode)) {\n throw new FS.ErrnoError(54);\n }\n if (!created) {\n var errCode = FS.mayOpen(node, flags);\n if (errCode) {\n throw new FS.ErrnoError(errCode);\n }\n }\n if (flags & 512 && !created) {\n FS.truncate(node, 0);\n }\n flags &= -131713;\n var stream = FS.createStream({\n node,\n path: FS.getPath(node),\n // we want the absolute path to the node\n flags,\n seekable: true,\n position: 0,\n stream_ops: node.stream_ops,\n // used by the file family libc calls (fopen, fwrite, ferror, etc.)\n ungotten: [],\n error: false\n });\n if (stream.stream_ops.open) {\n stream.stream_ops.open(stream);\n }\n if (Module["logReadFiles"] && !(flags & 1)) {\n if (!(path in FS.readFiles)) {\n FS.readFiles[path] = 1;\n }\n }\n return stream;\n },\n close(stream) {\n if (FS.isClosed(stream)) {\n throw new FS.ErrnoError(8);\n }\n if (stream.getdents) stream.getdents = null;\n try {\n if (stream.stream_ops.close) {\n stream.stream_ops.close(stream);\n }\n } catch (e) {\n throw e;\n } finally {\n FS.closeStream(stream.fd);\n }\n stream.fd = null;\n },\n isClosed(stream) {\n return stream.fd === null;\n },\n llseek(stream, offset, whence) {\n if (FS.isClosed(stream)) {\n throw new FS.ErrnoError(8);\n }\n if (!stream.seekable || !stream.stream_ops.llseek) {\n throw new FS.ErrnoError(70);\n }\n if (whence != 0 && whence != 1 && whence != 2) {\n throw new FS.ErrnoError(28);\n }\n stream.position = stream.stream_ops.llseek(stream, offset, whence);\n stream.ungotten = [];\n return stream.position;\n },\n read(stream, buffer, offset, length, position) {\n assert(offset >= 0);\n if (length < 0 || position < 0) {\n throw new FS.ErrnoError(28);\n }\n if (FS.isClosed(stream)) {\n throw new FS.ErrnoError(8);\n }\n if ((stream.flags & 2097155) === 1) {\n throw new FS.ErrnoError(8);\n }\n if (FS.isDir(stream.node.mode)) {\n throw new FS.ErrnoError(31);\n }\n if (!stream.stream_ops.read) {\n throw new FS.ErrnoError(28);\n }\n var seeking = typeof position != "undefined";\n if (!seeking) {\n position = stream.position;\n } else if (!stream.seekable) {\n throw new FS.ErrnoError(70);\n }\n var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);\n if (!seeking) stream.position += bytesRead;\n return bytesRead;\n },\n write(stream, buffer, offset, length, position, canOwn) {\n assert(offset >= 0);\n if (length < 0 || position < 0) {\n throw new FS.ErrnoError(28);\n }\n if (FS.isClosed(stream)) {\n throw new FS.ErrnoError(8);\n }\n if ((stream.flags & 2097155) === 0) {\n throw new FS.ErrnoError(8);\n }\n if (FS.isDir(stream.node.mode)) {\n throw new FS.ErrnoError(31);\n }\n if (!stream.stream_ops.write) {\n throw new FS.ErrnoError(28);\n }\n if (stream.seekable && stream.flags & 1024) {\n FS.llseek(stream, 0, 2);\n }\n var seeking = typeof position != "undefined";\n if (!seeking) {\n position = stream.position;\n } else if (!stream.seekable) {\n throw new FS.ErrnoError(70);\n }\n var bytesWritten = stream.stream_ops.write(\n stream,\n buffer,\n offset,\n length,\n position,\n canOwn\n );\n if (!seeking) stream.position += bytesWritten;\n return bytesWritten;\n },\n allocate(stream, offset, length) {\n if (FS.isClosed(stream)) {\n throw new FS.ErrnoError(8);\n }\n if (offset < 0 || length <= 0) {\n throw new FS.ErrnoError(28);\n }\n if ((stream.flags & 2097155) === 0) {\n throw new FS.ErrnoError(8);\n }\n if (!FS.isFile(stream.node.mode) && !FS.isDir(stream.node.mode)) {\n throw new FS.ErrnoError(43);\n }\n if (!stream.stream_ops.allocate) {\n throw new FS.ErrnoError(138);\n }\n stream.stream_ops.allocate(stream, offset, length);\n },\n mmap(stream, length, position, prot, flags) {\n if ((prot & 2) !== 0 && (flags & 2) === 0 && (stream.flags & 2097155) !== 2) {\n throw new FS.ErrnoError(2);\n }\n if ((stream.flags & 2097155) === 1) {\n throw new FS.ErrnoError(2);\n }\n if (!stream.stream_ops.mmap) {\n throw new FS.ErrnoError(43);\n }\n if (!length) {\n throw new FS.ErrnoError(28);\n }\n return stream.stream_ops.mmap(stream, length, position, prot, flags);\n },\n msync(stream, buffer, offset, length, mmapFlags) {\n assert(offset >= 0);\n if (!stream.stream_ops.msync) {\n return 0;\n }\n return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags);\n },\n ioctl(stream, cmd, arg) {\n if (!stream.stream_ops.ioctl) {\n throw new FS.ErrnoError(59);\n }\n return stream.stream_ops.ioctl(stream, cmd, arg);\n },\n readFile(path, opts = {}) {\n opts.flags = opts.flags || 0;\n opts.encoding = opts.encoding || "binary";\n if (opts.encoding !== "utf8" && opts.encoding !== "binary") {\n throw new Error(`Invalid encoding type "${opts.encoding}"`);\n }\n var ret;\n var stream = FS.open(path, opts.flags);\n var stat = FS.stat(path);\n var length = stat.size;\n var buf = new Uint8Array(length);\n FS.read(stream, buf, 0, length, 0);\n if (opts.encoding === "utf8") {\n ret = UTF8ArrayToString(buf);\n } else if (opts.encoding === "binary") {\n ret = buf;\n }\n FS.close(stream);\n return ret;\n },\n writeFile(path, data, opts = {}) {\n opts.flags = opts.flags || 577;\n var stream = FS.open(path, opts.flags, opts.mode);\n if (typeof data == "string") {\n var buf = new Uint8Array(lengthBytesUTF8(data) + 1);\n var actualNumBytes = stringToUTF8Array(data, buf, 0, buf.length);\n FS.write(stream, buf, 0, actualNumBytes, void 0, opts.canOwn);\n } else if (ArrayBuffer.isView(data)) {\n FS.write(stream, data, 0, data.byteLength, void 0, opts.canOwn);\n } else {\n throw new Error("Unsupported data type");\n }\n FS.close(stream);\n },\n cwd: () => FS.currentPath,\n chdir(path) {\n var lookup = FS.lookupPath(path, { follow: true });\n if (lookup.node === null) {\n throw new FS.ErrnoError(44);\n }\n if (!FS.isDir(lookup.node.mode)) {\n throw new FS.ErrnoError(54);\n }\n var errCode = FS.nodePermissions(lookup.node, "x");\n if (errCode) {\n throw new FS.ErrnoError(errCode);\n }\n FS.currentPath = lookup.path;\n },\n createDefaultDirectories() {\n FS.mkdir("/tmp");\n FS.mkdir("/home");\n FS.mkdir("/home/web_user");\n },\n createDefaultDevices() {\n FS.mkdir("/dev");\n FS.registerDevice(FS.makedev(1, 3), {\n read: () => 0,\n write: (stream, buffer, offset, length, pos) => length\n });\n FS.mkdev("/dev/null", FS.makedev(1, 3));\n TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);\n TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);\n FS.mkdev("/dev/tty", FS.makedev(5, 0));\n FS.mkdev("/dev/tty1", FS.makedev(6, 0));\n var randomBuffer = new Uint8Array(1024), randomLeft = 0;\n var randomByte = () => {\n if (randomLeft === 0) {\n randomLeft = randomFill(randomBuffer).byteLength;\n }\n return randomBuffer[--randomLeft];\n };\n FS.createDevice("/dev", "random", randomByte);\n FS.createDevice("/dev", "urandom", randomByte);\n FS.mkdir("/dev/shm");\n FS.mkdir("/dev/shm/tmp");\n },\n createSpecialDirectories() {\n FS.mkdir("/proc");\n var proc_self = FS.mkdir("/proc/self");\n FS.mkdir("/proc/self/fd");\n FS.mount(\n {\n mount() {\n var node = FS.createNode(proc_self, "fd", 16384 | 511, 73);\n node.node_ops = {\n lookup(parent, name) {\n var fd = +name;\n var stream = FS.getStreamChecked(fd);\n var ret = {\n parent: null,\n mount: { mountpoint: "fake" },\n node_ops: { readlink: () => stream.path }\n };\n ret.parent = ret;\n return ret;\n }\n };\n return node;\n }\n },\n {},\n "/proc/self/fd"\n );\n },\n createStandardStreams(input, output, error) {\n if (input) {\n FS.createDevice("/dev", "stdin", input);\n } else {\n FS.symlink("/dev/tty", "/dev/stdin");\n }\n if (output) {\n FS.createDevice("/dev", "stdout", null, output);\n } else {\n FS.symlink("/dev/tty", "/dev/stdout");\n }\n if (error) {\n FS.createDevice("/dev", "stderr", null, error);\n } else {\n FS.symlink("/dev/tty1", "/dev/stderr");\n }\n var stdin = FS.open("/dev/stdin", 0);\n var stdout = FS.open("/dev/stdout", 1);\n var stderr = FS.open("/dev/stderr", 1);\n assert(stdin.fd === 0, `invalid handle for stdin (${stdin.fd})`);\n assert(stdout.fd === 1, `invalid handle for stdout (${stdout.fd})`);\n assert(stderr.fd === 2, `invalid handle for stderr (${stderr.fd})`);\n },\n staticInit() {\n [44].forEach((code) => {\n FS.genericErrors[code] = new FS.ErrnoError(code);\n FS.genericErrors[code].stack = "";\n });\n FS.nameTable = new Array(4096);\n FS.mount(MEMFS, {}, "/");\n FS.createDefaultDirectories();\n FS.createDefaultDevices();\n FS.createSpecialDirectories();\n FS.filesystems = {\n MEMFS\n };\n },\n init(input, output, error) {\n assert(\n !FS.initialized,\n "FS.init was previously called. If you want to initialize later with custom parameters, remove any earlier calls (note that one is automatically added to the generated code)"\n );\n FS.initialized = true;\n input ?? (input = Module["stdin"]);\n output ?? (output = Module["stdout"]);\n error ?? (error = Module["stderr"]);\n FS.createStandardStreams(input, output, error);\n },\n quit() {\n FS.initialized = false;\n _fflush(0);\n for (var i = 0; i < FS.streams.length; i++) {\n var stream = FS.streams[i];\n if (!stream) {\n continue;\n }\n FS.close(stream);\n }\n },\n findObject(path, dontResolveLastLink) {\n var ret = FS.analyzePath(path, dontResolveLastLink);\n if (!ret.exists) {\n return null;\n }\n return ret.object;\n },\n analyzePath(path, dontResolveLastLink) {\n try {\n var lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });\n path = lookup.path;\n } catch (e) {\n }\n var ret = {\n isRoot: false,\n exists: false,\n error: 0,\n name: null,\n path: null,\n object: null,\n parentExists: false,\n parentPath: null,\n parentObject: null\n };\n try {\n var lookup = FS.lookupPath(path, { parent: true });\n ret.parentExists = true;\n ret.parentPath = lookup.path;\n ret.parentObject = lookup.node;\n ret.name = PATH.basename(path);\n lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });\n ret.exists = true;\n ret.path = lookup.path;\n ret.object = lookup.node;\n ret.name = lookup.node.name;\n ret.isRoot = lookup.path === "/";\n } catch (e) {\n ret.error = e.errno;\n }\n return ret;\n },\n createPath(parent, path, canRead, canWrite) {\n parent = typeof parent == "string" ? parent : FS.getPath(parent);\n var parts = path.split("/").reverse();\n while (parts.length) {\n var part = parts.pop();\n if (!part) continue;\n var current = PATH.join2(parent, part);\n try {\n FS.mkdir(current);\n } catch (e) {\n }\n parent = current;\n }\n return current;\n },\n createFile(parent, name, properties, canRead, canWrite) {\n var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name);\n var mode = FS_getMode(canRead, canWrite);\n return FS.create(path, mode);\n },\n createDataFile(parent, name, data, canRead, canWrite, canOwn) {\n var path = name;\n if (parent) {\n parent = typeof parent == "string" ? parent : FS.getPath(parent);\n path = name ? PATH.join2(parent, name) : parent;\n }\n var mode = FS_getMode(canRead, canWrite);\n var node = FS.create(path, mode);\n if (data) {\n if (typeof data == "string") {\n var arr = new Array(data.length);\n for (var i = 0, len = data.length; i < len; ++i) arr[i] = data.charCodeAt(i);\n data = arr;\n }\n FS.chmod(node, mode | 146);\n var stream = FS.open(node, 577);\n FS.write(stream, data, 0, data.length, 0, canOwn);\n FS.close(stream);\n FS.chmod(node, mode);\n }\n },\n createDevice(parent, name, input, output) {\n var _a;\n var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name);\n var mode = FS_getMode(!!input, !!output);\n (_a = FS.createDevice).major ?? (_a.major = 64);\n var dev = FS.makedev(FS.createDevice.major++, 0);\n FS.registerDevice(dev, {\n open(stream) {\n stream.seekable = false;\n },\n close(stream) {\n var _a2;\n if ((_a2 = output == null ? void 0 : output.buffer) == null ? void 0 : _a2.length) {\n output(10);\n }\n },\n read(stream, buffer, offset, length, pos) {\n var bytesRead = 0;\n for (var i = 0; i < length; i++) {\n var result;\n try {\n result = input();\n } catch (e) {\n throw new FS.ErrnoError(29);\n }\n if (result === void 0 && bytesRead === 0) {\n throw new FS.ErrnoError(6);\n }\n if (result === null || result === void 0) break;\n bytesRead++;\n buffer[offset + i] = result;\n }\n if (bytesRead) {\n stream.node.timestamp = Date.now();\n }\n return bytesRead;\n },\n write(stream, buffer, offset, length, pos) {\n for (var i = 0; i < length; i++) {\n try {\n output(buffer[offset + i]);\n } catch (e) {\n throw new FS.ErrnoError(29);\n }\n }\n if (length) {\n stream.node.timestamp = Date.now();\n }\n return i;\n }\n });\n return FS.mkdev(path, mode, dev);\n },\n forceLoadFile(obj) {\n if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true;\n if (typeof XMLHttpRequest != "undefined") {\n throw new Error(\n "Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread."\n );\n } else {\n try {\n obj.contents = readBinary(obj.url);\n obj.usedBytes = obj.contents.length;\n } catch (e) {\n throw new FS.ErrnoError(29);\n }\n }\n },\n createLazyFile(parent, name, url, canRead, canWrite) {\n class LazyUint8Array {\n constructor() {\n this.lengthKnown = false;\n this.chunks = [];\n }\n get(idx) {\n if (idx > this.length - 1 || idx < 0) {\n return void 0;\n }\n var chunkOffset = idx % this.chunkSize;\n var chunkNum = idx / this.chunkSize | 0;\n return this.getter(chunkNum)[chunkOffset];\n }\n setDataGetter(getter) {\n this.getter = getter;\n }\n cacheLength() {\n var xhr = new XMLHttpRequest();\n xhr.open("HEAD", url, false);\n xhr.send(null);\n if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304))\n throw new Error("Couldn\'t load " + url + ". Status: " + xhr.status);\n var datalength = Number(xhr.getResponseHeader("Content-length"));\n var header;\n var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";\n var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip";\n var chunkSize = 1024 * 1024;\n if (!hasByteServing) chunkSize = datalength;\n var doXHR = (from, to) => {\n if (from > to)\n throw new Error("invalid range (" + from + ", " + to + ") or no bytes requested!");\n if (to > datalength - 1)\n throw new Error("only " + datalength + " bytes available! programmer error!");\n var xhr2 = new XMLHttpRequest();\n xhr2.open("GET", url, false);\n if (datalength !== chunkSize)\n xhr2.setRequestHeader("Range", "bytes=" + from + "-" + to);\n xhr2.responseType = "arraybuffer";\n if (xhr2.overrideMimeType) {\n xhr2.overrideMimeType("text/plain; charset=x-user-defined");\n }\n xhr2.send(null);\n if (!(xhr2.status >= 200 && xhr2.status < 300 || xhr2.status === 304))\n throw new Error("Couldn\'t load " + url + ". Status: " + xhr2.status);\n if (xhr2.response !== void 0) {\n return new Uint8Array(\n /** @type{Array} */\n xhr2.response || []\n );\n }\n return intArrayFromString(xhr2.responseText || "");\n };\n var lazyArray2 = this;\n lazyArray2.setDataGetter((chunkNum) => {\n var start = chunkNum * chunkSize;\n var end = (chunkNum + 1) * chunkSize - 1;\n end = Math.min(end, datalength - 1);\n if (typeof lazyArray2.chunks[chunkNum] == "undefined") {\n lazyArray2.chunks[chunkNum] = doXHR(start, end);\n }\n if (typeof lazyArray2.chunks[chunkNum] == "undefined")\n throw new Error("doXHR failed!");\n return lazyArray2.chunks[chunkNum];\n });\n if (usesGzip || !datalength) {\n chunkSize = datalength = 1;\n datalength = this.getter(0).length;\n chunkSize = datalength;\n out("LazyFiles on gzip forces download of the whole file when length is accessed");\n }\n this._length = datalength;\n this._chunkSize = chunkSize;\n this.lengthKnown = true;\n }\n get length() {\n if (!this.lengthKnown) {\n this.cacheLength();\n }\n return this._length;\n }\n get chunkSize() {\n if (!this.lengthKnown) {\n this.cacheLength();\n }\n return this._chunkSize;\n }\n }\n if (typeof XMLHttpRequest != "undefined") {\n if (!ENVIRONMENT_IS_WORKER)\n throw "Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";\n var lazyArray = new LazyUint8Array();\n var properties = { isDevice: false, contents: lazyArray };\n } else {\n var properties = { isDevice: false, url };\n }\n var node = FS.createFile(parent, name, properties, canRead, canWrite);\n if (properties.contents) {\n node.contents = properties.contents;\n } else if (properties.url) {\n node.contents = null;\n node.url = properties.url;\n }\n Object.defineProperties(node, {\n usedBytes: {\n get: function() {\n return this.contents.length;\n }\n }\n });\n var stream_ops = {};\n var keys = Object.keys(node.stream_ops);\n keys.forEach((key) => {\n var fn = node.stream_ops[key];\n stream_ops[key] = (...args) => {\n FS.forceLoadFile(node);\n return fn(...args);\n };\n });\n function writeChunks(stream, buffer, offset, length, position) {\n var contents = stream.node.contents;\n if (position >= contents.length) return 0;\n var size = Math.min(contents.length - position, length);\n assert(size >= 0);\n if (contents.slice) {\n for (var i = 0; i < size; i++) {\n buffer[offset + i] = contents[position + i];\n }\n } else {\n for (var i = 0; i < size; i++) {\n buffer[offset + i] = contents.get(position + i);\n }\n }\n return size;\n }\n stream_ops.read = (stream, buffer, offset, length, position) => {\n FS.forceLoadFile(node);\n return writeChunks(stream, buffer, offset, length, position);\n };\n stream_ops.mmap = (stream, length, position, prot, flags) => {\n FS.forceLoadFile(node);\n var ptr = mmapAlloc(length);\n if (!ptr) {\n throw new FS.ErrnoError(48);\n }\n writeChunks(stream, HEAP8, ptr, length, position);\n return { ptr, allocated: true };\n };\n node.stream_ops = stream_ops;\n return node;\n },\n absolutePath() {\n abort("FS.absolutePath has been removed; use PATH_FS.resolve instead");\n },\n createFolder() {\n abort("FS.createFolder has been removed; use FS.mkdir instead");\n },\n createLink() {\n abort("FS.createLink has been removed; use FS.symlink instead");\n },\n joinPath() {\n abort("FS.joinPath has been removed; use PATH.join instead");\n },\n mmapAlloc() {\n abort("FS.mmapAlloc has been replaced by the top level function mmapAlloc");\n },\n standardizePath() {\n abort("FS.standardizePath has been removed; use PATH.normalize instead");\n }\n };\n var SYSCALLS = {\n DEFAULT_POLLMASK: 5,\n calculateAt(dirfd, path, allowEmpty) {\n if (PATH.isAbs(path)) {\n return path;\n }\n var dir;\n if (dirfd === -100) {\n dir = FS.cwd();\n } else {\n var dirstream = SYSCALLS.getStreamFromFD(dirfd);\n dir = dirstream.path;\n }\n if (path.length == 0) {\n if (!allowEmpty) {\n throw new FS.ErrnoError(44);\n }\n return dir;\n }\n return PATH.join2(dir, path);\n },\n doStat(func, path, buf) {\n var stat = func(path);\n HEAP32[buf >> 2] = stat.dev;\n HEAP32[buf + 4 >> 2] = stat.mode;\n HEAPU32[buf + 8 >> 2] = stat.nlink;\n HEAP32[buf + 12 >> 2] = stat.uid;\n HEAP32[buf + 16 >> 2] = stat.gid;\n HEAP32[buf + 20 >> 2] = stat.rdev;\n tempI64 = [\n stat.size >>> 0,\n (tempDouble = stat.size, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)\n ], HEAP32[buf + 24 >> 2] = tempI64[0], HEAP32[buf + 28 >> 2] = tempI64[1];\n HEAP32[buf + 32 >> 2] = 4096;\n HEAP32[buf + 36 >> 2] = stat.blocks;\n var atime = stat.atime.getTime();\n var mtime = stat.mtime.getTime();\n var ctime = stat.ctime.getTime();\n tempI64 = [\n Math.floor(atime / 1e3) >>> 0,\n (tempDouble = Math.floor(atime / 1e3), +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)\n ], HEAP32[buf + 40 >> 2] = tempI64[0], HEAP32[buf + 44 >> 2] = tempI64[1];\n HEAPU32[buf + 48 >> 2] = atime % 1e3 * 1e3 * 1e3;\n tempI64 = [\n Math.floor(mtime / 1e3) >>> 0,\n (tempDouble = Math.floor(mtime / 1e3), +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)\n ], HEAP32[buf + 56 >> 2] = tempI64[0], HEAP32[buf + 60 >> 2] = tempI64[1];\n HEAPU32[buf + 64 >> 2] = mtime % 1e3 * 1e3 * 1e3;\n tempI64 = [\n Math.floor(ctime / 1e3) >>> 0,\n (tempDouble = Math.floor(ctime / 1e3), +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)\n ], HEAP32[buf + 72 >> 2] = tempI64[0], HEAP32[buf + 76 >> 2] = tempI64[1];\n HEAPU32[buf + 80 >> 2] = ctime % 1e3 * 1e3 * 1e3;\n tempI64 = [\n stat.ino >>> 0,\n (tempDouble = stat.ino, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)\n ], HEAP32[buf + 88 >> 2] = tempI64[0], HEAP32[buf + 92 >> 2] = tempI64[1];\n return 0;\n },\n doMsync(addr, stream, len, flags, offset) {\n if (!FS.isFile(stream.node.mode)) {\n throw new FS.ErrnoError(43);\n }\n if (flags & 2) {\n return 0;\n }\n var buffer = HEAPU8.slice(addr, addr + len);\n FS.msync(stream, buffer, offset, len, flags);\n },\n getStreamFromFD(fd) {\n var stream = FS.getStreamChecked(fd);\n return stream;\n },\n varargs: void 0,\n getStr(ptr) {\n var ret = UTF8ToString(ptr);\n return ret;\n }\n };\n function ___syscall_fcntl64(fd, cmd, varargs) {\n SYSCALLS.varargs = varargs;\n try {\n var stream = SYSCALLS.getStreamFromFD(fd);\n switch (cmd) {\n case 0: {\n var arg = syscallGetVarargI();\n if (arg < 0) {\n return -28;\n }\n while (FS.streams[arg]) {\n arg++;\n }\n var newStream;\n newStream = FS.dupStream(stream, arg);\n return newStream.fd;\n }\n case 1:\n case 2:\n return 0;\n // FD_CLOEXEC makes no sense for a single process.\n case 3:\n return stream.flags;\n case 4: {\n var arg = syscallGetVarargI();\n stream.flags |= arg;\n return 0;\n }\n case 12: {\n var arg = syscallGetVarargP();\n var offset = 0;\n HEAP16[arg + offset >> 1] = 2;\n return 0;\n }\n case 13:\n case 14:\n return 0;\n }\n return -28;\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return -e.errno;\n }\n }\n function ___syscall_fstat64(fd, buf) {\n try {\n var stream = SYSCALLS.getStreamFromFD(fd);\n return SYSCALLS.doStat(FS.stat, stream.path, buf);\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return -e.errno;\n }\n }\n var convertI32PairToI53Checked = (lo, hi) => {\n assert(lo == lo >>> 0 || lo == (lo | 0));\n assert(hi === (hi | 0));\n return hi + 2097152 >>> 0 < 4194305 - !!lo ? (lo >>> 0) + hi * 4294967296 : NaN;\n };\n function ___syscall_ftruncate64(fd, length_low, length_high) {\n var length = convertI32PairToI53Checked(length_low, length_high);\n try {\n if (isNaN(length)) return 61;\n FS.ftruncate(fd, length);\n return 0;\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return -e.errno;\n }\n }\n var stringToUTF8 = (str, outPtr, maxBytesToWrite) => {\n assert(\n typeof maxBytesToWrite == "number",\n "stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!"\n );\n return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);\n };\n function ___syscall_getdents64(fd, dirp, count) {\n try {\n var stream = SYSCALLS.getStreamFromFD(fd);\n stream.getdents || (stream.getdents = FS.readdir(stream.path));\n var struct_size = 280;\n var pos = 0;\n var off = FS.llseek(stream, 0, 1);\n var idx = Math.floor(off / struct_size);\n while (idx < stream.getdents.length && pos + struct_size <= count) {\n var id;\n var type;\n var name = stream.getdents[idx];\n if (name === ".") {\n id = stream.node.id;\n type = 4;\n } else if (name === "..") {\n var lookup = FS.lookupPath(stream.path, { parent: true });\n id = lookup.node.id;\n type = 4;\n } else {\n var child = FS.lookupNode(stream.node, name);\n id = child.id;\n type = FS.isChrdev(child.mode) ? 2 : FS.isDir(child.mode) ? 4 : FS.isLink(child.mode) ? 10 : 8;\n }\n assert(id);\n tempI64 = [\n id >>> 0,\n (tempDouble = id, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)\n ], HEAP32[dirp + pos >> 2] = tempI64[0], HEAP32[dirp + pos + 4 >> 2] = tempI64[1];\n tempI64 = [\n (idx + 1) * struct_size >>> 0,\n (tempDouble = (idx + 1) * struct_size, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)\n ], HEAP32[dirp + pos + 8 >> 2] = tempI64[0], HEAP32[dirp + pos + 12 >> 2] = tempI64[1];\n HEAP16[dirp + pos + 16 >> 1] = 280;\n HEAP8[dirp + pos + 18] = type;\n stringToUTF8(name, dirp + pos + 19, 256);\n pos += struct_size;\n idx += 1;\n }\n FS.llseek(stream, idx * struct_size, 0);\n return pos;\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return -e.errno;\n }\n }\n function ___syscall_ioctl(fd, op, varargs) {\n SYSCALLS.varargs = varargs;\n try {\n var stream = SYSCALLS.getStreamFromFD(fd);\n switch (op) {\n case 21509: {\n if (!stream.tty) return -59;\n return 0;\n }\n case 21505: {\n if (!stream.tty) return -59;\n if (stream.tty.ops.ioctl_tcgets) {\n var termios = stream.tty.ops.ioctl_tcgets(stream);\n var argp = syscallGetVarargP();\n HEAP32[argp >> 2] = termios.c_iflag || 0;\n HEAP32[argp + 4 >> 2] = termios.c_oflag || 0;\n HEAP32[argp + 8 >> 2] = termios.c_cflag || 0;\n HEAP32[argp + 12 >> 2] = termios.c_lflag || 0;\n for (var i = 0; i < 32; i++) {\n HEAP8[argp + i + 17] = termios.c_cc[i] || 0;\n }\n return 0;\n }\n return 0;\n }\n case 21510:\n case 21511:\n case 21512: {\n if (!stream.tty) return -59;\n return 0;\n }\n case 21506:\n case 21507:\n case 21508: {\n if (!stream.tty) return -59;\n if (stream.tty.ops.ioctl_tcsets) {\n var argp = syscallGetVarargP();\n var c_iflag = HEAP32[argp >> 2];\n var c_oflag = HEAP32[argp + 4 >> 2];\n var c_cflag = HEAP32[argp + 8 >> 2];\n var c_lflag = HEAP32[argp + 12 >> 2];\n var c_cc = [];\n for (var i = 0; i < 32; i++) {\n c_cc.push(HEAP8[argp + i + 17]);\n }\n return stream.tty.ops.ioctl_tcsets(stream.tty, op, {\n c_iflag,\n c_oflag,\n c_cflag,\n c_lflag,\n c_cc\n });\n }\n return 0;\n }\n case 21519: {\n if (!stream.tty) return -59;\n var argp = syscallGetVarargP();\n HEAP32[argp >> 2] = 0;\n return 0;\n }\n case 21520: {\n if (!stream.tty) return -59;\n return -28;\n }\n case 21531: {\n var argp = syscallGetVarargP();\n return FS.ioctl(stream, op, argp);\n }\n case 21523: {\n if (!stream.tty) return -59;\n if (stream.tty.ops.ioctl_tiocgwinsz) {\n var winsize = stream.tty.ops.ioctl_tiocgwinsz(stream.tty);\n var argp = syscallGetVarargP();\n HEAP16[argp >> 1] = winsize[0];\n HEAP16[argp + 2 >> 1] = winsize[1];\n }\n return 0;\n }\n case 21524: {\n if (!stream.tty) return -59;\n return 0;\n }\n case 21515: {\n if (!stream.tty) return -59;\n return 0;\n }\n default:\n return -28;\n }\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return -e.errno;\n }\n }\n function ___syscall_lstat64(path, buf) {\n try {\n path = SYSCALLS.getStr(path);\n return SYSCALLS.doStat(FS.lstat, path, buf);\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return -e.errno;\n }\n }\n function ___syscall_newfstatat(dirfd, path, buf, flags) {\n try {\n path = SYSCALLS.getStr(path);\n var nofollow = flags & 256;\n var allowEmpty = flags & 4096;\n flags = flags & ~6400;\n assert(!flags, `unknown flags in __syscall_newfstatat: ${flags}`);\n path = SYSCALLS.calculateAt(dirfd, path, allowEmpty);\n return SYSCALLS.doStat(nofollow ? FS.lstat : FS.stat, path, buf);\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return -e.errno;\n }\n }\n function ___syscall_openat(dirfd, path, flags, varargs) {\n SYSCALLS.varargs = varargs;\n try {\n path = SYSCALLS.getStr(path);\n path = SYSCALLS.calculateAt(dirfd, path);\n var mode = varargs ? syscallGetVarargI() : 0;\n return FS.open(path, flags, mode).fd;\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return -e.errno;\n }\n }\n function ___syscall_rmdir(path) {\n try {\n path = SYSCALLS.getStr(path);\n FS.rmdir(path);\n return 0;\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return -e.errno;\n }\n }\n function ___syscall_stat64(path, buf) {\n try {\n path = SYSCALLS.getStr(path);\n return SYSCALLS.doStat(FS.stat, path, buf);\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return -e.errno;\n }\n }\n function ___syscall_unlinkat(dirfd, path, flags) {\n try {\n path = SYSCALLS.getStr(path);\n path = SYSCALLS.calculateAt(dirfd, path);\n if (flags === 0) {\n FS.unlink(path);\n } else if (flags === 512) {\n FS.rmdir(path);\n } else {\n abort("Invalid flags passed to unlinkat");\n }\n return 0;\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return -e.errno;\n }\n }\n var __abort_js = () => {\n abort("native code called abort()");\n };\n var __emscripten_memcpy_js = (dest, src, num) => HEAPU8.copyWithin(dest, src, src + num);\n var __emscripten_throw_longjmp = () => {\n throw Infinity;\n };\n function __gmtime_js(time_low, time_high, tmPtr) {\n var time = convertI32PairToI53Checked(time_low, time_high);\n var date = new Date(time * 1e3);\n HEAP32[tmPtr >> 2] = date.getUTCSeconds();\n HEAP32[tmPtr + 4 >> 2] = date.getUTCMinutes();\n HEAP32[tmPtr + 8 >> 2] = date.getUTCHours();\n HEAP32[tmPtr + 12 >> 2] = date.getUTCDate();\n HEAP32[tmPtr + 16 >> 2] = date.getUTCMonth();\n HEAP32[tmPtr + 20 >> 2] = date.getUTCFullYear() - 1900;\n HEAP32[tmPtr + 24 >> 2] = date.getUTCDay();\n var start = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0);\n var yday = (date.getTime() - start) / (1e3 * 60 * 60 * 24) | 0;\n HEAP32[tmPtr + 28 >> 2] = yday;\n }\n var isLeapYear = (year) => year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n var MONTH_DAYS_LEAP_CUMULATIVE = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];\n var MONTH_DAYS_REGULAR_CUMULATIVE = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];\n var ydayFromDate = (date) => {\n var leap = isLeapYear(date.getFullYear());\n var monthDaysCumulative = leap ? MONTH_DAYS_LEAP_CUMULATIVE : MONTH_DAYS_REGULAR_CUMULATIVE;\n var yday = monthDaysCumulative[date.getMonth()] + date.getDate() - 1;\n return yday;\n };\n function __localtime_js(time_low, time_high, tmPtr) {\n var time = convertI32PairToI53Checked(time_low, time_high);\n var date = new Date(time * 1e3);\n HEAP32[tmPtr >> 2] = date.getSeconds();\n HEAP32[tmPtr + 4 >> 2] = date.getMinutes();\n HEAP32[tmPtr + 8 >> 2] = date.getHours();\n HEAP32[tmPtr + 12 >> 2] = date.getDate();\n HEAP32[tmPtr + 16 >> 2] = date.getMonth();\n HEAP32[tmPtr + 20 >> 2] = date.getFullYear() - 1900;\n HEAP32[tmPtr + 24 >> 2] = date.getDay();\n var yday = ydayFromDate(date) | 0;\n HEAP32[tmPtr + 28 >> 2] = yday;\n HEAP32[tmPtr + 36 >> 2] = -(date.getTimezoneOffset() * 60);\n var start = new Date(date.getFullYear(), 0, 1);\n var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();\n var winterOffset = start.getTimezoneOffset();\n var dst = (summerOffset != winterOffset && date.getTimezoneOffset() == Math.min(winterOffset, summerOffset)) | 0;\n HEAP32[tmPtr + 32 >> 2] = dst;\n }\n var __tzset_js = (timezone, daylight, std_name, dst_name) => {\n var currentYear = (/* @__PURE__ */ new Date()).getFullYear();\n var winter = new Date(currentYear, 0, 1);\n var summer = new Date(currentYear, 6, 1);\n var winterOffset = winter.getTimezoneOffset();\n var summerOffset = summer.getTimezoneOffset();\n var stdTimezoneOffset = Math.max(winterOffset, summerOffset);\n HEAPU32[timezone >> 2] = stdTimezoneOffset * 60;\n HEAP32[daylight >> 2] = Number(winterOffset != summerOffset);\n var extractZone = (timezoneOffset) => {\n var sign = timezoneOffset >= 0 ? "-" : "+";\n var absOffset = Math.abs(timezoneOffset);\n var hours = String(Math.floor(absOffset / 60)).padStart(2, "0");\n var minutes = String(absOffset % 60).padStart(2, "0");\n return `UTC${sign}${hours}${minutes}`;\n };\n var winterName = extractZone(winterOffset);\n var summerName = extractZone(summerOffset);\n assert(winterName);\n assert(summerName);\n assert(\n lengthBytesUTF8(winterName) <= 16,\n `timezone name truncated to fit in TZNAME_MAX (${winterName})`\n );\n assert(\n lengthBytesUTF8(summerName) <= 16,\n `timezone name truncated to fit in TZNAME_MAX (${summerName})`\n );\n if (summerOffset < winterOffset) {\n stringToUTF8(winterName, std_name, 17);\n stringToUTF8(summerName, dst_name, 17);\n } else {\n stringToUTF8(winterName, dst_name, 17);\n stringToUTF8(summerName, std_name, 17);\n }\n };\n var _emscripten_date_now = () => Date.now();\n var getHeapMax = () => (\n // Stay one Wasm page short of 4GB: while e.g. Chrome is able to allocate\n // full 4GB Wasm memories, the size will wrap back to 0 bytes in Wasm side\n // for any code that deals with heap sizes, which would require special\n // casing all heap size related code to treat 0 specially.\n 2147483648\n );\n var growMemory = (size) => {\n var b = wasmMemory.buffer;\n var pages = (size - b.byteLength + 65535) / 65536 | 0;\n try {\n wasmMemory.grow(pages);\n updateMemoryViews();\n return 1;\n } catch (e) {\n err(\n `growMemory: Attempted to grow heap from ${b.byteLength} bytes to ${size} bytes, but got error: ${e}`\n );\n }\n };\n var _emscripten_resize_heap = (requestedSize) => {\n var oldSize = HEAPU8.length;\n requestedSize >>>= 0;\n assert(requestedSize > oldSize);\n var maxHeapSize = getHeapMax();\n if (requestedSize > maxHeapSize) {\n err(\n `Cannot enlarge memory, requested ${requestedSize} bytes, but the limit is ${maxHeapSize} bytes!`\n );\n return false;\n }\n for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {\n var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);\n overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);\n var newSize = Math.min(\n maxHeapSize,\n alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536)\n );\n var replacement = growMemory(newSize);\n if (replacement) {\n return true;\n }\n }\n err(`Failed to grow the heap from ${oldSize} bytes to ${newSize} bytes, not enough memory!`);\n return false;\n };\n var ENV = {};\n var getExecutableName = () => {\n return thisProgram || "./this.program";\n };\n var getEnvStrings = () => {\n if (!getEnvStrings.strings) {\n var lang = (typeof navigator == "object" && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8";\n var env = {\n USER: "web_user",\n LOGNAME: "web_user",\n PATH: "/",\n PWD: "/",\n HOME: "/home/web_user",\n LANG: lang,\n _: getExecutableName()\n };\n for (var x in ENV) {\n if (ENV[x] === void 0) delete env[x];\n else env[x] = ENV[x];\n }\n var strings = [];\n for (var x in env) {\n strings.push(`${x}=${env[x]}`);\n }\n getEnvStrings.strings = strings;\n }\n return getEnvStrings.strings;\n };\n var stringToAscii = (str, buffer) => {\n for (var i = 0; i < str.length; ++i) {\n assert(str.charCodeAt(i) === (str.charCodeAt(i) & 255));\n HEAP8[buffer++] = str.charCodeAt(i);\n }\n HEAP8[buffer] = 0;\n };\n var _environ_get = (__environ, environ_buf) => {\n var bufSize = 0;\n getEnvStrings().forEach((string, i) => {\n var ptr = environ_buf + bufSize;\n HEAPU32[__environ + i * 4 >> 2] = ptr;\n stringToAscii(string, ptr);\n bufSize += string.length + 1;\n });\n return 0;\n };\n var _environ_sizes_get = (penviron_count, penviron_buf_size) => {\n var strings = getEnvStrings();\n HEAPU32[penviron_count >> 2] = strings.length;\n var bufSize = 0;\n strings.forEach((string) => bufSize += string.length + 1);\n HEAPU32[penviron_buf_size >> 2] = bufSize;\n return 0;\n };\n function _fd_close(fd) {\n try {\n var stream = SYSCALLS.getStreamFromFD(fd);\n FS.close(stream);\n return 0;\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return e.errno;\n }\n }\n var doReadv = (stream, iov, iovcnt, offset) => {\n var ret = 0;\n for (var i = 0; i < iovcnt; i++) {\n var ptr = HEAPU32[iov >> 2];\n var len = HEAPU32[iov + 4 >> 2];\n iov += 8;\n var curr = FS.read(stream, HEAP8, ptr, len, offset);\n if (curr < 0) return -1;\n ret += curr;\n if (curr < len) break;\n }\n return ret;\n };\n function _fd_read(fd, iov, iovcnt, pnum) {\n try {\n var stream = SYSCALLS.getStreamFromFD(fd);\n var num = doReadv(stream, iov, iovcnt);\n HEAPU32[pnum >> 2] = num;\n return 0;\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return e.errno;\n }\n }\n function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {\n var offset = convertI32PairToI53Checked(offset_low, offset_high);\n try {\n if (isNaN(offset)) return 61;\n var stream = SYSCALLS.getStreamFromFD(fd);\n FS.llseek(stream, offset, whence);\n tempI64 = [\n stream.position >>> 0,\n (tempDouble = stream.position, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)\n ], HEAP32[newOffset >> 2] = tempI64[0], HEAP32[newOffset + 4 >> 2] = tempI64[1];\n if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null;\n return 0;\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return e.errno;\n }\n }\n function _fd_sync(fd) {\n var _a;\n try {\n var stream = SYSCALLS.getStreamFromFD(fd);\n if ((_a = stream.stream_ops) == null ? void 0 : _a.fsync) {\n return stream.stream_ops.fsync(stream);\n }\n return 0;\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return e.errno;\n }\n }\n var doWritev = (stream, iov, iovcnt, offset) => {\n var ret = 0;\n for (var i = 0; i < iovcnt; i++) {\n var ptr = HEAPU32[iov >> 2];\n var len = HEAPU32[iov + 4 >> 2];\n iov += 8;\n var curr = FS.write(stream, HEAP8, ptr, len, offset);\n if (curr < 0) return -1;\n ret += curr;\n if (curr < len) {\n break;\n }\n }\n return ret;\n };\n function _fd_write(fd, iov, iovcnt, pnum) {\n try {\n var stream = SYSCALLS.getStreamFromFD(fd);\n var num = doWritev(stream, iov, iovcnt);\n HEAPU32[pnum >> 2] = num;\n return 0;\n } catch (e) {\n if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;\n return e.errno;\n }\n }\n var wasmTableMirror = [];\n var wasmTable;\n var getWasmTableEntry = (funcPtr) => {\n var func = wasmTableMirror[funcPtr];\n if (!func) {\n if (funcPtr >= wasmTableMirror.length) wasmTableMirror.length = funcPtr + 1;\n wasmTableMirror[funcPtr] = func = wasmTable.get(funcPtr);\n }\n assert(\n wasmTable.get(funcPtr) == func,\n "JavaScript-side Wasm function table mirror is out of date!"\n );\n return func;\n };\n var UTF16Decoder = typeof TextDecoder != "undefined" ? new TextDecoder("utf-16le") : void 0;\n var UTF16ToString = (ptr, maxBytesToRead) => {\n assert(ptr % 2 == 0, "Pointer passed to UTF16ToString must be aligned to two bytes!");\n var endPtr = ptr;\n var idx = endPtr >> 1;\n var maxIdx = idx + maxBytesToRead / 2;\n while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx;\n endPtr = idx << 1;\n if (endPtr - ptr > 32 && UTF16Decoder)\n return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr));\n var str = "";\n for (var i = 0; !(i >= maxBytesToRead / 2); ++i) {\n var codeUnit = HEAP16[ptr + i * 2 >> 1];\n if (codeUnit == 0) break;\n str += String.fromCharCode(codeUnit);\n }\n return str;\n };\n var uleb128Encode = (n, target) => {\n assert(n < 16384);\n if (n < 128) {\n target.push(n);\n } else {\n target.push(n % 128 | 128, n >> 7);\n }\n };\n var sigToWasmTypes = (sig) => {\n assert(\n !sig.includes("j"),\n "i64 not permitted in function signatures when WASM_BIGINT is disabled"\n );\n var typeNames = {\n i: "i32",\n j: "i64",\n f: "f32",\n d: "f64",\n e: "externref",\n p: "i32"\n };\n var type = {\n parameters: [],\n results: sig[0] == "v" ? [] : [typeNames[sig[0]]]\n };\n for (var i = 1; i < sig.length; ++i) {\n assert(sig[i] in typeNames, "invalid signature char: " + sig[i]);\n type.parameters.push(typeNames[sig[i]]);\n }\n return type;\n };\n var generateFuncType = (sig, target) => {\n var sigRet = sig.slice(0, 1);\n var sigParam = sig.slice(1);\n var typeCodes = {\n i: 127,\n // i32\n p: 127,\n // i32\n j: 126,\n // i64\n f: 125,\n // f32\n d: 124,\n // f64\n e: 111\n // externref\n };\n target.push(\n 96\n /* form: func */\n );\n uleb128Encode(sigParam.length, target);\n for (var i = 0; i < sigParam.length; ++i) {\n assert(sigParam[i] in typeCodes, "invalid signature char: " + sigParam[i]);\n target.push(typeCodes[sigParam[i]]);\n }\n if (sigRet == "v") {\n target.push(0);\n } else {\n target.push(1, typeCodes[sigRet]);\n }\n };\n var convertJsFunctionToWasm = (func, sig) => {\n assert(\n !sig.includes("j"),\n "i64 not permitted in function signatures when WASM_BIGINT is disabled"\n );\n if (typeof WebAssembly.Function == "function") {\n return new WebAssembly.Function(sigToWasmTypes(sig), func);\n }\n var typeSectionBody = [\n 1\n // count: 1\n ];\n generateFuncType(sig, typeSectionBody);\n var bytes = [\n 0,\n 97,\n 115,\n 109,\n // magic ("\\0asm")\n 1,\n 0,\n 0,\n 0,\n // version: 1\n 1\n // Type section code\n ];\n uleb128Encode(typeSectionBody.length, bytes);\n bytes.push(...typeSectionBody);\n bytes.push(\n 2,\n 7,\n // import section\n // (import "e" "f" (func 0 (type 0)))\n 1,\n 1,\n 101,\n 1,\n 102,\n 0,\n 0,\n 7,\n 5,\n // export section\n // (export "f" (func 0 (type 0)))\n 1,\n 1,\n 102,\n 0,\n 0\n );\n var module = new WebAssembly.Module(new Uint8Array(bytes));\n var instance = new WebAssembly.Instance(module, { e: { f: func } });\n var wrappedFunc = instance.exports["f"];\n return wrappedFunc;\n };\n var updateTableMap = (offset, count) => {\n if (functionsInTableMap) {\n for (var i = offset; i < offset + count; i++) {\n var item = getWasmTableEntry(i);\n if (item) {\n functionsInTableMap.set(item, i);\n }\n }\n }\n };\n var functionsInTableMap;\n var getFunctionAddress = (func) => {\n if (!functionsInTableMap) {\n functionsInTableMap = /* @__PURE__ */ new WeakMap();\n updateTableMap(0, wasmTable.length);\n }\n return functionsInTableMap.get(func) || 0;\n };\n var freeTableIndexes = [];\n var getEmptyTableSlot = () => {\n if (freeTableIndexes.length) {\n return freeTableIndexes.pop();\n }\n try {\n wasmTable.grow(1);\n } catch (err2) {\n if (!(err2 instanceof RangeError)) {\n throw err2;\n }\n throw "Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.";\n }\n return wasmTable.length - 1;\n };\n var setWasmTableEntry = (idx, func) => {\n wasmTable.set(idx, func);\n wasmTableMirror[idx] = wasmTable.get(idx);\n };\n var addFunction = (func, sig) => {\n assert(typeof func != "undefined");\n var rtn = getFunctionAddress(func);\n if (rtn) {\n return rtn;\n }\n var ret = getEmptyTableSlot();\n try {\n setWasmTableEntry(ret, func);\n } catch (err2) {\n if (!(err2 instanceof TypeError)) {\n throw err2;\n }\n assert(typeof sig != "undefined", "Missing signature argument to addFunction: " + func);\n var wrapped = convertJsFunctionToWasm(func, sig);\n setWasmTableEntry(ret, wrapped);\n }\n functionsInTableMap.set(func, ret);\n return ret;\n };\n var getCFunc = (ident) => {\n var func = Module["_" + ident];\n assert(func, "Cannot call unknown function " + ident + ", make sure it is exported");\n return func;\n };\n var writeArrayToMemory = (array, buffer) => {\n assert(\n array.length >= 0,\n "writeArrayToMemory array must have a length (should be an array or typed array)"\n );\n HEAP8.set(array, buffer);\n };\n var stackAlloc = (sz) => __emscripten_stack_alloc(sz);\n var stringToUTF8OnStack = (str) => {\n var size = lengthBytesUTF8(str) + 1;\n var ret = stackAlloc(size);\n stringToUTF8(str, ret, size);\n return ret;\n };\n var ccall = (ident, returnType, argTypes, args, opts) => {\n var toC = {\n string: (str) => {\n var ret2 = 0;\n if (str !== null && str !== void 0 && str !== 0) {\n ret2 = stringToUTF8OnStack(str);\n }\n return ret2;\n },\n array: (arr) => {\n var ret2 = stackAlloc(arr.length);\n writeArrayToMemory(arr, ret2);\n return ret2;\n }\n };\n function convertReturnValue(ret2) {\n if (returnType === "string") {\n return UTF8ToString(ret2);\n }\n if (returnType === "boolean") return Boolean(ret2);\n return ret2;\n }\n var func = getCFunc(ident);\n var cArgs = [];\n var stack = 0;\n assert(returnType !== "array", \'Return type should not be "array".\');\n if (args) {\n for (var i = 0; i < args.length; i++) {\n var converter = toC[argTypes[i]];\n if (converter) {\n if (stack === 0) stack = stackSave();\n cArgs[i] = converter(args[i]);\n } else {\n cArgs[i] = args[i];\n }\n }\n }\n var ret = func(...cArgs);\n function onDone(ret2) {\n if (stack !== 0) stackRestore(stack);\n return convertReturnValue(ret2);\n }\n ret = onDone(ret);\n return ret;\n };\n var cwrap = (ident, returnType, argTypes, opts) => {\n return (...args) => ccall(ident, returnType, argTypes, args);\n };\n var removeFunction = (index) => {\n functionsInTableMap.delete(getWasmTableEntry(index));\n setWasmTableEntry(index, null);\n freeTableIndexes.push(index);\n };\n var stringToUTF16 = (str, outPtr, maxBytesToWrite) => {\n assert(outPtr % 2 == 0, "Pointer passed to stringToUTF16 must be aligned to two bytes!");\n assert(\n typeof maxBytesToWrite == "number",\n "stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!"\n );\n maxBytesToWrite ?? (maxBytesToWrite = 2147483647);\n if (maxBytesToWrite < 2) return 0;\n maxBytesToWrite -= 2;\n var startPtr = outPtr;\n var numCharsToWrite = maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length;\n for (var i = 0; i < numCharsToWrite; ++i) {\n var codeUnit = str.charCodeAt(i);\n HEAP16[outPtr >> 1] = codeUnit;\n outPtr += 2;\n }\n HEAP16[outPtr >> 1] = 0;\n return outPtr - startPtr;\n };\n FS.createPreloadedFile = FS_createPreloadedFile;\n FS.staticInit();\n function checkIncomingModuleAPI() {\n ignoredModuleProp("fetchSettings");\n }\n var wasmImports = {\n /** @export */\n __assert_fail: ___assert_fail,\n /** @export */\n __syscall_fcntl64: ___syscall_fcntl64,\n /** @export */\n __syscall_fstat64: ___syscall_fstat64,\n /** @export */\n __syscall_ftruncate64: ___syscall_ftruncate64,\n /** @export */\n __syscall_getdents64: ___syscall_getdents64,\n /** @export */\n __syscall_ioctl: ___syscall_ioctl,\n /** @export */\n __syscall_lstat64: ___syscall_lstat64,\n /** @export */\n __syscall_newfstatat: ___syscall_newfstatat,\n /** @export */\n __syscall_openat: ___syscall_openat,\n /** @export */\n __syscall_rmdir: ___syscall_rmdir,\n /** @export */\n __syscall_stat64: ___syscall_stat64,\n /** @export */\n __syscall_unlinkat: ___syscall_unlinkat,\n /** @export */\n _abort_js: __abort_js,\n /** @export */\n _emscripten_memcpy_js: __emscripten_memcpy_js,\n /** @export */\n _emscripten_throw_longjmp: __emscripten_throw_longjmp,\n /** @export */\n _gmtime_js: __gmtime_js,\n /** @export */\n _localtime_js: __localtime_js,\n /** @export */\n _tzset_js: __tzset_js,\n /** @export */\n emscripten_date_now: _emscripten_date_now,\n /** @export */\n emscripten_resize_heap: _emscripten_resize_heap,\n /** @export */\n environ_get: _environ_get,\n /** @export */\n environ_sizes_get: _environ_sizes_get,\n /** @export */\n fd_close: _fd_close,\n /** @export */\n fd_read: _fd_read,\n /** @export */\n fd_seek: _fd_seek,\n /** @export */\n fd_sync: _fd_sync,\n /** @export */\n fd_write: _fd_write,\n /** @export */\n invoke_ii,\n /** @export */\n invoke_iii,\n /** @export */\n invoke_iiii,\n /** @export */\n invoke_iiiii,\n /** @export */\n invoke_v,\n /** @export */\n invoke_vii,\n /** @export */\n invoke_viii,\n /** @export */\n invoke_viiii,\n /** @export */\n invoke_viiiiiiiii\n };\n var wasmExports = createWasm();\n Module["_PDFiumExt_Init"] = createExportWrapper("PDFiumExt_Init", 0);\n Module["_FPDF_InitLibraryWithConfig"] = createExportWrapper(\n "FPDF_InitLibraryWithConfig",\n 1\n );\n Module["_PDFiumExt_OpenFileWriter"] = createExportWrapper(\n "PDFiumExt_OpenFileWriter",\n 0\n );\n Module["_PDFiumExt_GetFileWriterSize"] = createExportWrapper("PDFiumExt_GetFileWriterSize", 1);\n Module["_PDFiumExt_GetFileWriterData"] = createExportWrapper("PDFiumExt_GetFileWriterData", 3);\n Module["_PDFiumExt_CloseFileWriter"] = createExportWrapper(\n "PDFiumExt_CloseFileWriter",\n 1\n );\n Module["_PDFiumExt_SaveAsCopy"] = createExportWrapper(\n "PDFiumExt_SaveAsCopy",\n 2\n );\n Module["_FPDF_SaveAsCopy"] = createExportWrapper("FPDF_SaveAsCopy", 3);\n Module["_PDFiumExt_OpenFormFillInfo"] = createExportWrapper(\n "PDFiumExt_OpenFormFillInfo",\n 0\n );\n Module["_PDFiumExt_CloseFormFillInfo"] = createExportWrapper("PDFiumExt_CloseFormFillInfo", 1);\n Module["_PDFiumExt_InitFormFillEnvironment"] = createExportWrapper("PDFiumExt_InitFormFillEnvironment", 2);\n Module["_FPDFDOC_InitFormFillEnvironment"] = createExportWrapper("FPDFDOC_InitFormFillEnvironment", 2);\n Module["_PDFiumExt_ExitFormFillEnvironment"] = createExportWrapper("PDFiumExt_ExitFormFillEnvironment", 1);\n Module["_FPDFDOC_ExitFormFillEnvironment"] = createExportWrapper("FPDFDOC_ExitFormFillEnvironment", 1);\n Module["_EPDFNamedDest_SetDest"] = createExportWrapper(\n "EPDFNamedDest_SetDest",\n 3\n );\n Module["_EPDFNamedDest_Remove"] = createExportWrapper(\n "EPDFNamedDest_Remove",\n 2\n );\n Module["_EPDFDest_CreateView"] = createExportWrapper(\n "EPDFDest_CreateView",\n 4\n );\n Module["_EPDFDest_CreateXYZ"] = createExportWrapper(\n "EPDFDest_CreateXYZ",\n 7\n );\n Module["_EPDFDest_CreateRemoteView"] = createExportWrapper(\n "EPDFDest_CreateRemoteView",\n 5\n );\n Module["_EPDFDest_CreateRemoteXYZ"] = createExportWrapper(\n "EPDFDest_CreateRemoteXYZ",\n 8\n );\n Module["_EPDFAction_CreateGoTo"] = createExportWrapper(\n "EPDFAction_CreateGoTo",\n 2\n );\n Module["_EPDFAction_CreateGoToNamed"] = createExportWrapper(\n "EPDFAction_CreateGoToNamed",\n 2\n );\n Module["_EPDFAction_CreateLaunch"] = createExportWrapper(\n "EPDFAction_CreateLaunch",\n 2\n );\n Module["_EPDFAction_CreateRemoteGoToByName"] = createExportWrapper("EPDFAction_CreateRemoteGoToByName", 3);\n Module["_EPDFAction_CreateRemoteGoToDest"] = createExportWrapper("EPDFAction_CreateRemoteGoToDest", 3);\n Module["_EPDFAction_CreateURI"] = createExportWrapper(\n "EPDFAction_CreateURI",\n 2\n );\n Module["_EPDFBookmark_Create"] = createExportWrapper(\n "EPDFBookmark_Create",\n 2\n );\n Module["_EPDFBookmark_Delete"] = createExportWrapper(\n "EPDFBookmark_Delete",\n 2\n );\n Module["_EPDFBookmark_AppendChild"] = createExportWrapper(\n "EPDFBookmark_AppendChild",\n 3\n );\n Module["_EPDFBookmark_InsertAfter"] = createExportWrapper(\n "EPDFBookmark_InsertAfter",\n 4\n );\n Module["_EPDFBookmark_Clear"] = createExportWrapper(\n "EPDFBookmark_Clear",\n 1\n );\n Module["_EPDFBookmark_SetTitle"] = createExportWrapper(\n "EPDFBookmark_SetTitle",\n 2\n );\n Module["_EPDFBookmark_SetDest"] = createExportWrapper(\n "EPDFBookmark_SetDest",\n 3\n );\n Module["_EPDFBookmark_SetAction"] = createExportWrapper(\n "EPDFBookmark_SetAction",\n 3\n );\n Module["_EPDFBookmark_ClearTarget"] = createExportWrapper(\n "EPDFBookmark_ClearTarget",\n 1\n );\n Module["_EPDF_PNG_EncodeRGBA"] = createExportWrapper(\n "EPDF_PNG_EncodeRGBA",\n 6\n );\n Module["_FPDFAnnot_IsSupportedSubtype"] = createExportWrapper("FPDFAnnot_IsSupportedSubtype", 1);\n Module["_FPDFPage_CreateAnnot"] = createExportWrapper(\n "FPDFPage_CreateAnnot",\n 2\n );\n Module["_FPDFPage_GetAnnotCount"] = createExportWrapper(\n "FPDFPage_GetAnnotCount",\n 1\n );\n Module["_FPDFPage_GetAnnot"] = createExportWrapper(\n "FPDFPage_GetAnnot",\n 2\n );\n Module["_FPDFPage_GetAnnotIndex"] = createExportWrapper(\n "FPDFPage_GetAnnotIndex",\n 2\n );\n Module["_FPDFPage_CloseAnnot"] = createExportWrapper(\n "FPDFPage_CloseAnnot",\n 1\n );\n Module["_FPDFPage_RemoveAnnot"] = createExportWrapper(\n "FPDFPage_RemoveAnnot",\n 2\n );\n Module["_FPDFAnnot_GetSubtype"] = createExportWrapper(\n "FPDFAnnot_GetSubtype",\n 1\n );\n Module["_FPDFAnnot_IsObjectSupportedSubtype"] = createExportWrapper("FPDFAnnot_IsObjectSupportedSubtype", 1);\n Module["_FPDFAnnot_UpdateObject"] = createExportWrapper(\n "FPDFAnnot_UpdateObject",\n 2\n );\n Module["_FPDFAnnot_AddInkStroke"] = createExportWrapper(\n "FPDFAnnot_AddInkStroke",\n 3\n );\n Module["_FPDFAnnot_RemoveInkList"] = createExportWrapper(\n "FPDFAnnot_RemoveInkList",\n 1\n );\n Module["_FPDFAnnot_AppendObject"] = createExportWrapper(\n "FPDFAnnot_AppendObject",\n 2\n );\n Module["_FPDFAnnot_GetObjectCount"] = createExportWrapper(\n "FPDFAnnot_GetObjectCount",\n 1\n );\n Module["_FPDFAnnot_GetObject"] = createExportWrapper(\n "FPDFAnnot_GetObject",\n 2\n );\n Module["_FPDFAnnot_RemoveObject"] = createExportWrapper(\n "FPDFAnnot_RemoveObject",\n 2\n );\n Module["_FPDFAnnot_SetColor"] = createExportWrapper(\n "FPDFAnnot_SetColor",\n 6\n );\n Module["_FPDFAnnot_GetColor"] = createExportWrapper(\n "FPDFAnnot_GetColor",\n 6\n );\n Module["_FPDFAnnot_HasAttachmentPoints"] = createExportWrapper("FPDFAnnot_HasAttachmentPoints", 1);\n Module["_FPDFAnnot_SetAttachmentPoints"] = createExportWrapper("FPDFAnnot_SetAttachmentPoints", 3);\n Module["_FPDFAnnot_AppendAttachmentPoints"] = createExportWrapper("FPDFAnnot_AppendAttachmentPoints", 2);\n Module["_FPDFAnnot_CountAttachmentPoints"] = createExportWrapper("FPDFAnnot_CountAttachmentPoints", 1);\n Module["_FPDFAnnot_GetAttachmentPoints"] = createExportWrapper("FPDFAnnot_GetAttachmentPoints", 3);\n Module["_FPDFAnnot_SetRect"] = createExportWrapper(\n "FPDFAnnot_SetRect",\n 2\n );\n Module["_FPDFAnnot_GetRect"] = createExportWrapper(\n "FPDFAnnot_GetRect",\n 2\n );\n Module["_FPDFAnnot_GetVertices"] = createExportWrapper(\n "FPDFAnnot_GetVertices",\n 3\n );\n Module["_FPDFAnnot_GetInkListCount"] = createExportWrapper(\n "FPDFAnnot_GetInkListCount",\n 1\n );\n Module["_FPDFAnnot_GetInkListPath"] = createExportWrapper(\n "FPDFAnnot_GetInkListPath",\n 4\n );\n Module["_FPDFAnnot_GetLine"] = createExportWrapper(\n "FPDFAnnot_GetLine",\n 3\n );\n Module["_FPDFAnnot_SetBorder"] = createExportWrapper(\n "FPDFAnnot_SetBorder",\n 4\n );\n Module["_FPDFAnnot_GetBorder"] = createExportWrapper(\n "FPDFAnnot_GetBorder",\n 4\n );\n Module["_FPDFAnnot_HasKey"] = createExportWrapper(\n "FPDFAnnot_HasKey",\n 2\n );\n Module["_FPDFAnnot_GetValueType"] = createExportWrapper(\n "FPDFAnnot_GetValueType",\n 2\n );\n Module["_FPDFAnnot_SetStringValue"] = createExportWrapper(\n "FPDFAnnot_SetStringValue",\n 3\n );\n Module["_FPDFAnnot_GetStringValue"] = createExportWrapper(\n "FPDFAnnot_GetStringValue",\n 4\n );\n Module["_FPDFAnnot_GetNumberValue"] = createExportWrapper(\n "FPDFAnnot_GetNumberValue",\n 3\n );\n Module["_FPDFAnnot_SetAP"] = createExportWrapper("FPDFAnnot_SetAP", 3);\n Module["_FPDFAnnot_GetAP"] = createExportWrapper("FPDFAnnot_GetAP", 4);\n Module["_FPDFAnnot_GetLinkedAnnot"] = createExportWrapper(\n "FPDFAnnot_GetLinkedAnnot",\n 2\n );\n Module["_FPDFAnnot_GetFlags"] = createExportWrapper(\n "FPDFAnnot_GetFlags",\n 1\n );\n Module["_FPDFAnnot_SetFlags"] = createExportWrapper(\n "FPDFAnnot_SetFlags",\n 2\n );\n Module["_FPDFAnnot_GetFormFieldFlags"] = createExportWrapper("FPDFAnnot_GetFormFieldFlags", 2);\n Module["_FPDFAnnot_SetFormFieldFlags"] = createExportWrapper("FPDFAnnot_SetFormFieldFlags", 3);\n Module["_FPDFAnnot_GetFormFieldAtPoint"] = createExportWrapper("FPDFAnnot_GetFormFieldAtPoint", 3);\n Module["_FPDFAnnot_GetFormFieldName"] = createExportWrapper(\n "FPDFAnnot_GetFormFieldName",\n 4\n );\n Module["_FPDFAnnot_GetFormFieldType"] = createExportWrapper(\n "FPDFAnnot_GetFormFieldType",\n 2\n );\n Module["_FPDFAnnot_GetFormAdditionalActionJavaScript"] = createExportWrapper("FPDFAnnot_GetFormAdditionalActionJavaScript", 5);\n Module["_FPDFAnnot_GetFormFieldAlternateName"] = createExportWrapper("FPDFAnnot_GetFormFieldAlternateName", 4);\n Module["_FPDFAnnot_GetFormFieldValue"] = createExportWrapper("FPDFAnnot_GetFormFieldValue", 4);\n Module["_FPDFAnnot_GetOptionCount"] = createExportWrapper(\n "FPDFAnnot_GetOptionCount",\n 2\n );\n Module["_FPDFAnnot_GetOptionLabel"] = createExportWrapper(\n "FPDFAnnot_GetOptionLabel",\n 5\n );\n Module["_FPDFAnnot_IsOptionSelected"] = createExportWrapper(\n "FPDFAnnot_IsOptionSelected",\n 3\n );\n Module["_FPDFAnnot_GetFontSize"] = createExportWrapper(\n "FPDFAnnot_GetFontSize",\n 3\n );\n Module["_FPDFAnnot_SetFontColor"] = createExportWrapper(\n "FPDFAnnot_SetFontColor",\n 5\n );\n Module["_FPDFAnnot_GetFontColor"] = createExportWrapper(\n "FPDFAnnot_GetFontColor",\n 5\n );\n Module["_FPDFAnnot_IsChecked"] = createExportWrapper(\n "FPDFAnnot_IsChecked",\n 2\n );\n Module["_FPDFAnnot_SetFocusableSubtypes"] = createExportWrapper("FPDFAnnot_SetFocusableSubtypes", 3);\n Module["_FPDFAnnot_GetFocusableSubtypesCount"] = createExportWrapper("FPDFAnnot_GetFocusableSubtypesCount", 1);\n Module["_FPDFAnnot_GetFocusableSubtypes"] = createExportWrapper("FPDFAnnot_GetFocusableSubtypes", 3);\n Module["_FPDFAnnot_GetLink"] = createExportWrapper(\n "FPDFAnnot_GetLink",\n 1\n );\n Module["_FPDFAnnot_GetFormControlCount"] = createExportWrapper("FPDFAnnot_GetFormControlCount", 2);\n Module["_FPDFAnnot_GetFormControlIndex"] = createExportWrapper("FPDFAnnot_GetFormControlIndex", 2);\n Module["_FPDFAnnot_GetFormFieldExportValue"] = createExportWrapper("FPDFAnnot_GetFormFieldExportValue", 4);\n Module["_FPDFAnnot_SetURI"] = createExportWrapper(\n "FPDFAnnot_SetURI",\n 2\n );\n Module["_EPDFAnnot_SetAction"] = createExportWrapper(\n "EPDFAnnot_SetAction",\n 2\n );\n Module["_FPDFAnnot_GetFileAttachment"] = createExportWrapper("FPDFAnnot_GetFileAttachment", 1);\n Module["_FPDFAnnot_AddFileAttachment"] = createExportWrapper("FPDFAnnot_AddFileAttachment", 2);\n Module["_EPDFAnnot_SetColor"] = createExportWrapper(\n "EPDFAnnot_SetColor",\n 5\n );\n Module["_EPDFAnnot_GetColor"] = createExportWrapper(\n "EPDFAnnot_GetColor",\n 5\n );\n Module["_EPDFAnnot_ClearColor"] = createExportWrapper(\n "EPDFAnnot_ClearColor",\n 2\n );\n Module["_EPDFAnnot_SetOpacity"] = createExportWrapper(\n "EPDFAnnot_SetOpacity",\n 2\n );\n Module["_EPDFAnnot_GetOpacity"] = createExportWrapper(\n "EPDFAnnot_GetOpacity",\n 2\n );\n Module["_EPDFAnnot_GetBorderEffect"] = createExportWrapper(\n "EPDFAnnot_GetBorderEffect",\n 2\n );\n Module["_EPDFAnnot_GetRectangleDifferences"] = createExportWrapper("EPDFAnnot_GetRectangleDifferences", 5);\n Module["_EPDFAnnot_GetBorderDashPatternCount"] = createExportWrapper("EPDFAnnot_GetBorderDashPatternCount", 1);\n Module["_EPDFAnnot_GetBorderDashPattern"] = createExportWrapper("EPDFAnnot_GetBorderDashPattern", 3);\n Module["_EPDFAnnot_SetBorderDashPattern"] = createExportWrapper("EPDFAnnot_SetBorderDashPattern", 3);\n Module["_EPDFAnnot_GetBorderStyle"] = createExportWrapper(\n "EPDFAnnot_GetBorderStyle",\n 2\n );\n Module["_EPDFAnnot_SetBorderStyle"] = createExportWrapper(\n "EPDFAnnot_SetBorderStyle",\n 3\n );\n Module["_EPDFAnnot_GenerateAppearance"] = createExportWrapper("EPDFAnnot_GenerateAppearance", 1);\n Module["_EPDFAnnot_GenerateAppearanceWithBlend"] = createExportWrapper("EPDFAnnot_GenerateAppearanceWithBlend", 2);\n Module["_EPDFAnnot_GetBlendMode"] = createExportWrapper(\n "EPDFAnnot_GetBlendMode",\n 1\n );\n Module["_EPDFAnnot_SetIntent"] = createExportWrapper(\n "EPDFAnnot_SetIntent",\n 2\n );\n Module["_EPDFAnnot_GetIntent"] = createExportWrapper(\n "EPDFAnnot_GetIntent",\n 3\n );\n Module["_EPDFAnnot_GetRichContent"] = createExportWrapper(\n "EPDFAnnot_GetRichContent",\n 3\n );\n Module["_EPDFAnnot_SetLineEndings"] = createExportWrapper(\n "EPDFAnnot_SetLineEndings",\n 3\n );\n Module["_EPDFAnnot_GetLineEndings"] = createExportWrapper(\n "EPDFAnnot_GetLineEndings",\n 3\n );\n Module["_EPDFAnnot_SetVertices"] = createExportWrapper(\n "EPDFAnnot_SetVertices",\n 3\n );\n Module["_EPDFAnnot_SetLine"] = createExportWrapper(\n "EPDFAnnot_SetLine",\n 3\n );\n Module["_EPDFAnnot_SetDefaultAppearance"] = createExportWrapper("EPDFAnnot_SetDefaultAppearance", 6);\n Module["_EPDFAnnot_GetDefaultAppearance"] = createExportWrapper("EPDFAnnot_GetDefaultAppearance", 6);\n Module["_EPDFAnnot_SetTextAlignment"] = createExportWrapper(\n "EPDFAnnot_SetTextAlignment",\n 2\n );\n Module["_EPDFAnnot_GetTextAlignment"] = createExportWrapper(\n "EPDFAnnot_GetTextAlignment",\n 1\n );\n Module["_EPDFAnnot_SetVerticalAlignment"] = createExportWrapper("EPDFAnnot_SetVerticalAlignment", 2);\n Module["_EPDFAnnot_GetVerticalAlignment"] = createExportWrapper("EPDFAnnot_GetVerticalAlignment", 1);\n Module["_EPDFPage_GetAnnotByName"] = createExportWrapper(\n "EPDFPage_GetAnnotByName",\n 2\n );\n Module["_EPDFPage_RemoveAnnotByName"] = createExportWrapper(\n "EPDFPage_RemoveAnnotByName",\n 2\n );\n Module["_EPDFAnnot_SetLinkedAnnot"] = createExportWrapper(\n "EPDFAnnot_SetLinkedAnnot",\n 3\n );\n Module["_EPDFPage_GetAnnotCountRaw"] = createExportWrapper(\n "EPDFPage_GetAnnotCountRaw",\n 2\n );\n Module["_EPDFPage_GetAnnotRaw"] = createExportWrapper(\n "EPDFPage_GetAnnotRaw",\n 3\n );\n Module["_EPDFPage_RemoveAnnotRaw"] = createExportWrapper(\n "EPDFPage_RemoveAnnotRaw",\n 3\n );\n Module["_EPDFAnnot_SetIcon"] = createExportWrapper(\n "EPDFAnnot_SetIcon",\n 2\n );\n Module["_EPDFAnnot_GetIcon"] = createExportWrapper(\n "EPDFAnnot_GetIcon",\n 1\n );\n Module["_EPDFAnnot_UpdateAppearanceToRect"] = createExportWrapper("EPDFAnnot_UpdateAppearanceToRect", 2);\n Module["_EPDFPage_CreateAnnot"] = createExportWrapper(\n "EPDFPage_CreateAnnot",\n 2\n );\n Module["_EPDFAnnot_SetRotate"] = createExportWrapper(\n "EPDFAnnot_SetRotate",\n 2\n );\n Module["_EPDFAnnot_GetRotate"] = createExportWrapper(\n "EPDFAnnot_GetRotate",\n 2\n );\n Module["_EPDFAnnot_GetReplyType"] = createExportWrapper(\n "EPDFAnnot_GetReplyType",\n 1\n );\n Module["_EPDFAnnot_SetReplyType"] = createExportWrapper(\n "EPDFAnnot_SetReplyType",\n 2\n );\n Module["_EPDFAnnot_SetOverlayText"] = createExportWrapper(\n "EPDFAnnot_SetOverlayText",\n 2\n );\n Module["_EPDFAnnot_GetOverlayText"] = createExportWrapper(\n "EPDFAnnot_GetOverlayText",\n 3\n );\n Module["_EPDFAnnot_SetOverlayTextRepeat"] = createExportWrapper("EPDFAnnot_SetOverlayTextRepeat", 2);\n Module["_EPDFAnnot_GetOverlayTextRepeat"] = createExportWrapper("EPDFAnnot_GetOverlayTextRepeat", 1);\n Module["_EPDFAnnot_ApplyRedaction"] = createExportWrapper(\n "EPDFAnnot_ApplyRedaction",\n 2\n );\n Module["_EPDFPage_ApplyRedactions"] = createExportWrapper(\n "EPDFPage_ApplyRedactions",\n 1\n );\n Module["_EPDFAnnot_Flatten"] = createExportWrapper(\n "EPDFAnnot_Flatten",\n 2\n );\n Module["_EPDFAnnot_SetExtendedRotation"] = createExportWrapper("EPDFAnnot_SetExtendedRotation", 2);\n Module["_EPDFAnnot_GetExtendedRotation"] = createExportWrapper("EPDFAnnot_GetExtendedRotation", 2);\n Module["_EPDFAnnot_SetUnrotatedRect"] = createExportWrapper(\n "EPDFAnnot_SetUnrotatedRect",\n 2\n );\n Module["_EPDFAnnot_GetUnrotatedRect"] = createExportWrapper(\n "EPDFAnnot_GetUnrotatedRect",\n 2\n );\n Module["_EPDFAnnot_GetRect"] = createExportWrapper(\n "EPDFAnnot_GetRect",\n 2\n );\n Module["_EPDFAnnot_SetAPMatrix"] = createExportWrapper(\n "EPDFAnnot_SetAPMatrix",\n 3\n );\n Module["_EPDFAnnot_GetAPMatrix"] = createExportWrapper(\n "EPDFAnnot_GetAPMatrix",\n 3\n );\n Module["_EPDFAnnot_GetAvailableAppearanceModes"] = createExportWrapper("EPDFAnnot_GetAvailableAppearanceModes", 1);\n Module["_FPDFDoc_GetAttachmentCount"] = createExportWrapper(\n "FPDFDoc_GetAttachmentCount",\n 1\n );\n Module["_FPDFDoc_AddAttachment"] = createExportWrapper(\n "FPDFDoc_AddAttachment",\n 2\n );\n Module["_FPDFDoc_GetAttachment"] = createExportWrapper(\n "FPDFDoc_GetAttachment",\n 2\n );\n Module["_FPDFDoc_DeleteAttachment"] = createExportWrapper(\n "FPDFDoc_DeleteAttachment",\n 2\n );\n Module["_FPDFAttachment_GetName"] = createExportWrapper(\n "FPDFAttachment_GetName",\n 3\n );\n Module["_FPDFAttachment_HasKey"] = createExportWrapper(\n "FPDFAttachment_HasKey",\n 2\n );\n Module["_FPDFAttachment_GetValueType"] = createExportWrapper("FPDFAttachment_GetValueType", 2);\n Module["_FPDFAttachment_SetStringValue"] = createExportWrapper("FPDFAttachment_SetStringValue", 3);\n Module["_FPDFAttachment_GetStringValue"] = createExportWrapper("FPDFAttachment_GetStringValue", 4);\n Module["_FPDFAttachment_SetFile"] = createExportWrapper(\n "FPDFAttachment_SetFile",\n 4\n );\n Module["_FPDFAttachment_GetFile"] = createExportWrapper(\n "FPDFAttachment_GetFile",\n 4\n );\n Module["_FPDFAttachment_GetSubtype"] = createExportWrapper(\n "FPDFAttachment_GetSubtype",\n 3\n );\n Module["_EPDFAttachment_SetSubtype"] = createExportWrapper(\n "EPDFAttachment_SetSubtype",\n 2\n );\n Module["_EPDFAttachment_SetDescription"] = createExportWrapper("EPDFAttachment_SetDescription", 2);\n Module["_EPDFAttachment_GetDescription"] = createExportWrapper("EPDFAttachment_GetDescription", 3);\n Module["_EPDFAttachment_GetIntegerValue"] = createExportWrapper("EPDFAttachment_GetIntegerValue", 3);\n Module["_FPDFCatalog_IsTagged"] = createExportWrapper(\n "FPDFCatalog_IsTagged",\n 1\n );\n Module["_FPDFCatalog_GetLanguage"] = createExportWrapper(\n "FPDFCatalog_GetLanguage",\n 3\n );\n Module["_FPDFCatalog_SetLanguage"] = createExportWrapper(\n "FPDFCatalog_SetLanguage",\n 2\n );\n Module["_EPDFCatalog_GetLanguage"] = createExportWrapper(\n "EPDFCatalog_GetLanguage",\n 3\n );\n Module["_FPDFAvail_Create"] = createExportWrapper(\n "FPDFAvail_Create",\n 2\n );\n Module["_FPDFAvail_Destroy"] = createExportWrapper(\n "FPDFAvail_Destroy",\n 1\n );\n Module["_FPDFAvail_IsDocAvail"] = createExportWrapper(\n "FPDFAvail_IsDocAvail",\n 2\n );\n Module["_FPDFAvail_GetDocument"] = createExportWrapper(\n "FPDFAvail_GetDocument",\n 2\n );\n Module["_FPDFAvail_GetFirstPageNum"] = createExportWrapper(\n "FPDFAvail_GetFirstPageNum",\n 1\n );\n Module["_FPDFAvail_IsPageAvail"] = createExportWrapper(\n "FPDFAvail_IsPageAvail",\n 3\n );\n Module["_FPDFAvail_IsFormAvail"] = createExportWrapper(\n "FPDFAvail_IsFormAvail",\n 2\n );\n Module["_FPDFAvail_IsLinearized"] = createExportWrapper(\n "FPDFAvail_IsLinearized",\n 1\n );\n Module["_FPDFBookmark_GetFirstChild"] = createExportWrapper(\n "FPDFBookmark_GetFirstChild",\n 2\n );\n Module["_FPDFBookmark_GetNextSibling"] = createExportWrapper("FPDFBookmark_GetNextSibling", 2);\n Module["_FPDFBookmark_GetTitle"] = createExportWrapper(\n "FPDFBookmark_GetTitle",\n 3\n );\n Module["_FPDFBookmark_GetCount"] = createExportWrapper(\n "FPDFBookmark_GetCount",\n 1\n );\n Module["_FPDFBookmark_Find"] = createExportWrapper(\n "FPDFBookmark_Find",\n 2\n );\n Module["_FPDFBookmark_GetDest"] = createExportWrapper(\n "FPDFBookmark_GetDest",\n 2\n );\n Module["_FPDFBookmark_GetAction"] = createExportWrapper(\n "FPDFBookmark_GetAction",\n 1\n );\n Module["_FPDFAction_GetType"] = createExportWrapper(\n "FPDFAction_GetType",\n 1\n );\n Module["_FPDFAction_GetDest"] = createExportWrapper(\n "FPDFAction_GetDest",\n 2\n );\n Module["_FPDFAction_GetFilePath"] = createExportWrapper(\n "FPDFAction_GetFilePath",\n 3\n );\n Module["_FPDFAction_GetURIPath"] = createExportWrapper(\n "FPDFAction_GetURIPath",\n 4\n );\n Module["_FPDFDest_GetDestPageIndex"] = createExportWrapper(\n "FPDFDest_GetDestPageIndex",\n 2\n );\n Module["_FPDFDest_GetView"] = createExportWrapper(\n "FPDFDest_GetView",\n 3\n );\n Module["_FPDFDest_GetLocationInPage"] = createExportWrapper(\n "FPDFDest_GetLocationInPage",\n 7\n );\n Module["_FPDFLink_GetLinkAtPoint"] = createExportWrapper(\n "FPDFLink_GetLinkAtPoint",\n 3\n );\n Module["_FPDFLink_GetLinkZOrderAtPoint"] = createExportWrapper("FPDFLink_GetLinkZOrderAtPoint", 3);\n Module["_FPDFLink_GetDest"] = createExportWrapper(\n "FPDFLink_GetDest",\n 2\n );\n Module["_FPDFLink_GetAction"] = createExportWrapper(\n "FPDFLink_GetAction",\n 1\n );\n Module["_FPDFLink_Enumerate"] = createExportWrapper(\n "FPDFLink_Enumerate",\n 3\n );\n Module["_FPDFLink_GetAnnot"] = createExportWrapper(\n "FPDFLink_GetAnnot",\n 2\n );\n Module["_FPDFLink_GetAnnotRect"] = createExportWrapper(\n "FPDFLink_GetAnnotRect",\n 2\n );\n Module["_FPDFLink_CountQuadPoints"] = createExportWrapper(\n "FPDFLink_CountQuadPoints",\n 1\n );\n Module["_FPDFLink_GetQuadPoints"] = createExportWrapper(\n "FPDFLink_GetQuadPoints",\n 3\n );\n Module["_FPDF_GetPageAAction"] = createExportWrapper(\n "FPDF_GetPageAAction",\n 2\n );\n Module["_FPDF_GetFileIdentifier"] = createExportWrapper(\n "FPDF_GetFileIdentifier",\n 4\n );\n Module["_FPDF_GetMetaText"] = createExportWrapper(\n "FPDF_GetMetaText",\n 4\n );\n Module["_FPDF_GetPageLabel"] = createExportWrapper(\n "FPDF_GetPageLabel",\n 4\n );\n Module["_EPDF_SetMetaText"] = createExportWrapper(\n "EPDF_SetMetaText",\n 3\n );\n Module["_EPDF_HasMetaText"] = createExportWrapper(\n "EPDF_HasMetaText",\n 2\n );\n Module["_EPDF_GetMetaTrapped"] = createExportWrapper(\n "EPDF_GetMetaTrapped",\n 1\n );\n Module["_EPDF_SetMetaTrapped"] = createExportWrapper(\n "EPDF_SetMetaTrapped",\n 2\n );\n Module["_EPDF_GetMetaKeyCount"] = createExportWrapper(\n "EPDF_GetMetaKeyCount",\n 2\n );\n Module["_EPDF_GetMetaKeyName"] = createExportWrapper(\n "EPDF_GetMetaKeyName",\n 5\n );\n Module["_FPDFPageObj_NewImageObj"] = createExportWrapper(\n "FPDFPageObj_NewImageObj",\n 1\n );\n Module["_FPDFImageObj_LoadJpegFile"] = createExportWrapper(\n "FPDFImageObj_LoadJpegFile",\n 4\n );\n Module["_FPDFImageObj_LoadJpegFileInline"] = createExportWrapper("FPDFImageObj_LoadJpegFileInline", 4);\n Module["_FPDFImageObj_SetMatrix"] = createExportWrapper(\n "FPDFImageObj_SetMatrix",\n 7\n );\n Module["_FPDFImageObj_SetBitmap"] = createExportWrapper(\n "FPDFImageObj_SetBitmap",\n 4\n );\n Module["_FPDFImageObj_GetBitmap"] = createExportWrapper(\n "FPDFImageObj_GetBitmap",\n 1\n );\n Module["_FPDFImageObj_GetRenderedBitmap"] = createExportWrapper("FPDFImageObj_GetRenderedBitmap", 3);\n Module["_FPDFImageObj_GetImageDataDecoded"] = createExportWrapper("FPDFImageObj_GetImageDataDecoded", 3);\n Module["_FPDFImageObj_GetImageDataRaw"] = createExportWrapper("FPDFImageObj_GetImageDataRaw", 3);\n Module["_FPDFImageObj_GetImageFilterCount"] = createExportWrapper("FPDFImageObj_GetImageFilterCount", 1);\n Module["_FPDFImageObj_GetImageFilter"] = createExportWrapper("FPDFImageObj_GetImageFilter", 4);\n Module["_FPDFImageObj_GetImageMetadata"] = createExportWrapper("FPDFImageObj_GetImageMetadata", 3);\n Module["_FPDFImageObj_GetImagePixelSize"] = createExportWrapper("FPDFImageObj_GetImagePixelSize", 3);\n Module["_FPDFImageObj_GetIccProfileDataDecoded"] = createExportWrapper("FPDFImageObj_GetIccProfileDataDecoded", 5);\n Module["_FPDF_CreateNewDocument"] = createExportWrapper(\n "FPDF_CreateNewDocument",\n 0\n );\n Module["_FPDFPage_Delete"] = createExportWrapper("FPDFPage_Delete", 2);\n Module["_FPDF_MovePages"] = createExportWrapper("FPDF_MovePages", 4);\n Module["_FPDFPage_New"] = createExportWrapper("FPDFPage_New", 4);\n Module["_FPDFPage_GetRotation"] = createExportWrapper(\n "FPDFPage_GetRotation",\n 1\n );\n Module["_FPDFPage_InsertObject"] = createExportWrapper(\n "FPDFPage_InsertObject",\n 2\n );\n Module["_FPDFPage_InsertObjectAtIndex"] = createExportWrapper("FPDFPage_InsertObjectAtIndex", 3);\n Module["_FPDFPage_RemoveObject"] = createExportWrapper(\n "FPDFPage_RemoveObject",\n 2\n );\n Module["_FPDFPage_CountObjects"] = createExportWrapper(\n "FPDFPage_CountObjects",\n 1\n );\n Module["_FPDFPage_GetObject"] = createExportWrapper(\n "FPDFPage_GetObject",\n 2\n );\n Module["_FPDFPage_HasTransparency"] = createExportWrapper(\n "FPDFPage_HasTransparency",\n 1\n );\n Module["_FPDFPageObj_Destroy"] = createExportWrapper(\n "FPDFPageObj_Destroy",\n 1\n );\n Module["_FPDFPageObj_GetMarkedContentID"] = createExportWrapper("FPDFPageObj_GetMarkedContentID", 1);\n Module["_FPDFPageObj_CountMarks"] = createExportWrapper(\n "FPDFPageObj_CountMarks",\n 1\n );\n Module["_FPDFPageObj_GetMark"] = createExportWrapper(\n "FPDFPageObj_GetMark",\n 2\n );\n Module["_FPDFPageObj_AddMark"] = createExportWrapper(\n "FPDFPageObj_AddMark",\n 2\n );\n Module["_FPDFPageObj_RemoveMark"] = createExportWrapper(\n "FPDFPageObj_RemoveMark",\n 2\n );\n Module["_FPDFPageObjMark_GetName"] = createExportWrapper(\n "FPDFPageObjMark_GetName",\n 4\n );\n Module["_FPDFPageObjMark_CountParams"] = createExportWrapper("FPDFPageObjMark_CountParams", 1);\n Module["_FPDFPageObjMark_GetParamKey"] = createExportWrapper("FPDFPageObjMark_GetParamKey", 5);\n Module["_FPDFPageObjMark_GetParamValueType"] = createExportWrapper("FPDFPageObjMark_GetParamValueType", 2);\n Module["_FPDFPageObjMark_GetParamIntValue"] = createExportWrapper("FPDFPageObjMark_GetParamIntValue", 3);\n Module["_FPDFPageObjMark_GetParamFloatValue"] = createExportWrapper("FPDFPageObjMark_GetParamFloatValue", 3);\n Module["_FPDFPageObjMark_GetParamStringValue"] = createExportWrapper("FPDFPageObjMark_GetParamStringValue", 5);\n Module["_FPDFPageObjMark_GetParamBlobValue"] = createExportWrapper("FPDFPageObjMark_GetParamBlobValue", 5);\n Module["_FPDFPageObj_HasTransparency"] = createExportWrapper("FPDFPageObj_HasTransparency", 1);\n Module["_FPDFPageObjMark_SetIntParam"] = createExportWrapper("FPDFPageObjMark_SetIntParam", 5);\n Module["_FPDFPageObjMark_SetFloatParam"] = createExportWrapper("FPDFPageObjMark_SetFloatParam", 5);\n Module["_FPDFPageObjMark_SetStringParam"] = createExportWrapper("FPDFPageObjMark_SetStringParam", 5);\n Module["_FPDFPageObjMark_SetBlobParam"] = createExportWrapper("FPDFPageObjMark_SetBlobParam", 6);\n Module["_FPDFPageObjMark_RemoveParam"] = createExportWrapper("FPDFPageObjMark_RemoveParam", 3);\n Module["_FPDFPageObj_GetType"] = createExportWrapper(\n "FPDFPageObj_GetType",\n 1\n );\n Module["_FPDFPageObj_GetIsActive"] = createExportWrapper(\n "FPDFPageObj_GetIsActive",\n 2\n );\n Module["_FPDFPageObj_SetIsActive"] = createExportWrapper(\n "FPDFPageObj_SetIsActive",\n 2\n );\n Module["_FPDFPage_GenerateContent"] = createExportWrapper(\n "FPDFPage_GenerateContent",\n 1\n );\n Module["_FPDFPageObj_Transform"] = createExportWrapper(\n "FPDFPageObj_Transform",\n 7\n );\n Module["_FPDFPageObj_TransformF"] = createExportWrapper(\n "FPDFPageObj_TransformF",\n 2\n );\n Module["_FPDFPageObj_GetMatrix"] = createExportWrapper(\n "FPDFPageObj_GetMatrix",\n 2\n );\n Module["_FPDFPageObj_SetMatrix"] = createExportWrapper(\n "FPDFPageObj_SetMatrix",\n 2\n );\n Module["_FPDFPageObj_SetBlendMode"] = createExportWrapper(\n "FPDFPageObj_SetBlendMode",\n 2\n );\n Module["_FPDFPage_TransformAnnots"] = createExportWrapper(\n "FPDFPage_TransformAnnots",\n 7\n );\n Module["_FPDFPage_SetRotation"] = createExportWrapper(\n "FPDFPage_SetRotation",\n 2\n );\n Module["_FPDFPageObj_SetFillColor"] = createExportWrapper(\n "FPDFPageObj_SetFillColor",\n 5\n );\n Module["_FPDFPageObj_GetFillColor"] = createExportWrapper(\n "FPDFPageObj_GetFillColor",\n 5\n );\n Module["_FPDFPageObj_GetBounds"] = createExportWrapper(\n "FPDFPageObj_GetBounds",\n 5\n );\n Module["_FPDFPageObj_GetRotatedBounds"] = createExportWrapper("FPDFPageObj_GetRotatedBounds", 2);\n Module["_FPDFPageObj_SetStrokeColor"] = createExportWrapper(\n "FPDFPageObj_SetStrokeColor",\n 5\n );\n Module["_FPDFPageObj_GetStrokeColor"] = createExportWrapper(\n "FPDFPageObj_GetStrokeColor",\n 5\n );\n Module["_FPDFPageObj_SetStrokeWidth"] = createExportWrapper(\n "FPDFPageObj_SetStrokeWidth",\n 2\n );\n Module["_FPDFPageObj_GetStrokeWidth"] = createExportWrapper(\n "FPDFPageObj_GetStrokeWidth",\n 2\n );\n Module["_FPDFPageObj_GetLineJoin"] = createExportWrapper(\n "FPDFPageObj_GetLineJoin",\n 1\n );\n Module["_FPDFPageObj_SetLineJoin"] = createExportWrapper(\n "FPDFPageObj_SetLineJoin",\n 2\n );\n Module["_FPDFPageObj_GetLineCap"] = createExportWrapper(\n "FPDFPageObj_GetLineCap",\n 1\n );\n Module["_FPDFPageObj_SetLineCap"] = createExportWrapper(\n "FPDFPageObj_SetLineCap",\n 2\n );\n Module["_FPDFPageObj_GetDashPhase"] = createExportWrapper(\n "FPDFPageObj_GetDashPhase",\n 2\n );\n Module["_FPDFPageObj_SetDashPhase"] = createExportWrapper(\n "FPDFPageObj_SetDashPhase",\n 2\n );\n Module["_FPDFPageObj_GetDashCount"] = createExportWrapper(\n "FPDFPageObj_GetDashCount",\n 1\n );\n Module["_FPDFPageObj_GetDashArray"] = createExportWrapper(\n "FPDFPageObj_GetDashArray",\n 3\n );\n Module["_FPDFPageObj_SetDashArray"] = createExportWrapper(\n "FPDFPageObj_SetDashArray",\n 4\n );\n Module["_FPDFFormObj_CountObjects"] = createExportWrapper(\n "FPDFFormObj_CountObjects",\n 1\n );\n Module["_FPDFFormObj_GetObject"] = createExportWrapper(\n "FPDFFormObj_GetObject",\n 2\n );\n Module["_FPDFFormObj_RemoveObject"] = createExportWrapper(\n "FPDFFormObj_RemoveObject",\n 2\n );\n Module["_FPDFPageObj_CreateNewPath"] = createExportWrapper(\n "FPDFPageObj_CreateNewPath",\n 2\n );\n Module["_FPDFPageObj_CreateNewRect"] = createExportWrapper(\n "FPDFPageObj_CreateNewRect",\n 4\n );\n Module["_FPDFPath_CountSegments"] = createExportWrapper(\n "FPDFPath_CountSegments",\n 1\n );\n Module["_FPDFPath_GetPathSegment"] = createExportWrapper(\n "FPDFPath_GetPathSegment",\n 2\n );\n Module["_FPDFPath_MoveTo"] = createExportWrapper("FPDFPath_MoveTo", 3);\n Module["_FPDFPath_LineTo"] = createExportWrapper("FPDFPath_LineTo", 3);\n Module["_FPDFPath_BezierTo"] = createExportWrapper(\n "FPDFPath_BezierTo",\n 7\n );\n Module["_FPDFPath_Close"] = createExportWrapper("FPDFPath_Close", 1);\n Module["_FPDFPath_SetDrawMode"] = createExportWrapper(\n "FPDFPath_SetDrawMode",\n 3\n );\n Module["_FPDFPath_GetDrawMode"] = createExportWrapper(\n "FPDFPath_GetDrawMode",\n 3\n );\n Module["_FPDFPathSegment_GetPoint"] = createExportWrapper(\n "FPDFPathSegment_GetPoint",\n 3\n );\n Module["_FPDFPathSegment_GetType"] = createExportWrapper(\n "FPDFPathSegment_GetType",\n 1\n );\n Module["_FPDFPathSegment_GetClose"] = createExportWrapper(\n "FPDFPathSegment_GetClose",\n 1\n );\n Module["_FPDFPageObj_NewTextObj"] = createExportWrapper(\n "FPDFPageObj_NewTextObj",\n 3\n );\n Module["_FPDFText_SetText"] = createExportWrapper(\n "FPDFText_SetText",\n 2\n );\n Module["_FPDFText_SetCharcodes"] = createExportWrapper(\n "FPDFText_SetCharcodes",\n 3\n );\n Module["_FPDFText_LoadFont"] = createExportWrapper(\n "FPDFText_LoadFont",\n 5\n );\n Module["_FPDFText_LoadStandardFont"] = createExportWrapper(\n "FPDFText_LoadStandardFont",\n 2\n );\n Module["_FPDFText_LoadCidType2Font"] = createExportWrapper(\n "FPDFText_LoadCidType2Font",\n 6\n );\n Module["_FPDFTextObj_GetFontSize"] = createExportWrapper(\n "FPDFTextObj_GetFontSize",\n 2\n );\n Module["_FPDFTextObj_GetText"] = createExportWrapper(\n "FPDFTextObj_GetText",\n 4\n );\n Module["_FPDFTextObj_GetRenderedBitmap"] = createExportWrapper("FPDFTextObj_GetRenderedBitmap", 4);\n Module["_FPDFFont_Close"] = createExportWrapper("FPDFFont_Close", 1);\n Module["_FPDFPageObj_CreateTextObj"] = createExportWrapper(\n "FPDFPageObj_CreateTextObj",\n 3\n );\n Module["_FPDFTextObj_GetTextRenderMode"] = createExportWrapper("FPDFTextObj_GetTextRenderMode", 1);\n Module["_FPDFTextObj_SetTextRenderMode"] = createExportWrapper("FPDFTextObj_SetTextRenderMode", 2);\n Module["_FPDFTextObj_GetFont"] = createExportWrapper(\n "FPDFTextObj_GetFont",\n 1\n );\n Module["_FPDFFont_GetBaseFontName"] = createExportWrapper(\n "FPDFFont_GetBaseFontName",\n 3\n );\n Module["_FPDFFont_GetFamilyName"] = createExportWrapper(\n "FPDFFont_GetFamilyName",\n 3\n );\n Module["_FPDFFont_GetFontData"] = createExportWrapper(\n "FPDFFont_GetFontData",\n 4\n );\n Module["_FPDFFont_GetIsEmbedded"] = createExportWrapper(\n "FPDFFont_GetIsEmbedded",\n 1\n );\n Module["_FPDFFont_GetFlags"] = createExportWrapper(\n "FPDFFont_GetFlags",\n 1\n );\n Module["_FPDFFont_GetWeight"] = createExportWrapper(\n "FPDFFont_GetWeight",\n 1\n );\n Module["_FPDFFont_GetItalicAngle"] = createExportWrapper(\n "FPDFFont_GetItalicAngle",\n 2\n );\n Module["_FPDFFont_GetAscent"] = createExportWrapper(\n "FPDFFont_GetAscent",\n 3\n );\n Module["_FPDFFont_GetDescent"] = createExportWrapper(\n "FPDFFont_GetDescent",\n 3\n );\n Module["_FPDFFont_GetGlyphWidth"] = createExportWrapper(\n "FPDFFont_GetGlyphWidth",\n 4\n );\n Module["_FPDFFont_GetGlyphPath"] = createExportWrapper(\n "FPDFFont_GetGlyphPath",\n 3\n );\n Module["_FPDFGlyphPath_CountGlyphSegments"] = createExportWrapper("FPDFGlyphPath_CountGlyphSegments", 1);\n Module["_FPDFGlyphPath_GetGlyphPathSegment"] = createExportWrapper("FPDFGlyphPath_GetGlyphPathSegment", 2);\n Module["_EPDFText_RedactInRect"] = createExportWrapper(\n "EPDFText_RedactInRect",\n 4\n );\n Module["_EPDFText_RedactInQuads"] = createExportWrapper(\n "EPDFText_RedactInQuads",\n 5\n );\n Module["_FPDFDoc_GetPageMode"] = createExportWrapper(\n "FPDFDoc_GetPageMode",\n 1\n );\n Module["_FPDFPage_Flatten"] = createExportWrapper(\n "FPDFPage_Flatten",\n 2\n );\n Module["_FPDFPage_HasFormFieldAtPoint"] = createExportWrapper("FPDFPage_HasFormFieldAtPoint", 4);\n Module["_FPDFPage_FormFieldZOrderAtPoint"] = createExportWrapper("FPDFPage_FormFieldZOrderAtPoint", 4);\n Module["_malloc"] = createExportWrapper("malloc", 1);\n Module["_free"] = createExportWrapper("free", 1);\n Module["_FORM_OnMouseMove"] = createExportWrapper(\n "FORM_OnMouseMove",\n 5\n );\n Module["_FORM_OnMouseWheel"] = createExportWrapper(\n "FORM_OnMouseWheel",\n 6\n );\n Module["_FORM_OnFocus"] = createExportWrapper("FORM_OnFocus", 5);\n Module["_FORM_OnLButtonDown"] = createExportWrapper(\n "FORM_OnLButtonDown",\n 5\n );\n Module["_FORM_OnLButtonUp"] = createExportWrapper(\n "FORM_OnLButtonUp",\n 5\n );\n Module["_FORM_OnLButtonDoubleClick"] = createExportWrapper(\n "FORM_OnLButtonDoubleClick",\n 5\n );\n Module["_FORM_OnRButtonDown"] = createExportWrapper(\n "FORM_OnRButtonDown",\n 5\n );\n Module["_FORM_OnRButtonUp"] = createExportWrapper(\n "FORM_OnRButtonUp",\n 5\n );\n Module["_FORM_OnKeyDown"] = createExportWrapper("FORM_OnKeyDown", 4);\n Module["_FORM_OnKeyUp"] = createExportWrapper("FORM_OnKeyUp", 4);\n Module["_FORM_OnChar"] = createExportWrapper("FORM_OnChar", 4);\n Module["_FORM_GetFocusedText"] = createExportWrapper(\n "FORM_GetFocusedText",\n 4\n );\n Module["_FORM_GetSelectedText"] = createExportWrapper(\n "FORM_GetSelectedText",\n 4\n );\n Module["_FORM_ReplaceAndKeepSelection"] = createExportWrapper("FORM_ReplaceAndKeepSelection", 3);\n Module["_FORM_ReplaceSelection"] = createExportWrapper(\n "FORM_ReplaceSelection",\n 3\n );\n Module["_FORM_SelectAllText"] = createExportWrapper(\n "FORM_SelectAllText",\n 2\n );\n Module["_FORM_CanUndo"] = createExportWrapper("FORM_CanUndo", 2);\n Module["_FORM_CanRedo"] = createExportWrapper("FORM_CanRedo", 2);\n Module["_FORM_Undo"] = createExportWrapper("FORM_Undo", 2);\n Module["_FORM_Redo"] = createExportWrapper("FORM_Redo", 2);\n Module["_FORM_ForceToKillFocus"] = createExportWrapper(\n "FORM_ForceToKillFocus",\n 1\n );\n Module["_FORM_GetFocusedAnnot"] = createExportWrapper(\n "FORM_GetFocusedAnnot",\n 3\n );\n Module["_FORM_SetFocusedAnnot"] = createExportWrapper(\n "FORM_SetFocusedAnnot",\n 2\n );\n Module["_FPDF_FFLDraw"] = createExportWrapper("FPDF_FFLDraw", 9);\n Module["_FPDF_SetFormFieldHighlightColor"] = createExportWrapper("FPDF_SetFormFieldHighlightColor", 3);\n Module["_FPDF_SetFormFieldHighlightAlpha"] = createExportWrapper("FPDF_SetFormFieldHighlightAlpha", 2);\n Module["_FPDF_RemoveFormFieldHighlight"] = createExportWrapper("FPDF_RemoveFormFieldHighlight", 1);\n Module["_FORM_OnAfterLoadPage"] = createExportWrapper(\n "FORM_OnAfterLoadPage",\n 2\n );\n Module["_FORM_OnBeforeClosePage"] = createExportWrapper(\n "FORM_OnBeforeClosePage",\n 2\n );\n Module["_FORM_DoDocumentJSAction"] = createExportWrapper(\n "FORM_DoDocumentJSAction",\n 1\n );\n Module["_FORM_DoDocumentOpenAction"] = createExportWrapper(\n "FORM_DoDocumentOpenAction",\n 1\n );\n Module["_FORM_DoDocumentAAction"] = createExportWrapper(\n "FORM_DoDocumentAAction",\n 2\n );\n Module["_FORM_DoPageAAction"] = createExportWrapper(\n "FORM_DoPageAAction",\n 3\n );\n Module["_FORM_SetIndexSelected"] = createExportWrapper(\n "FORM_SetIndexSelected",\n 4\n );\n Module["_FORM_IsIndexSelected"] = createExportWrapper(\n "FORM_IsIndexSelected",\n 3\n );\n Module["_FPDFDoc_GetJavaScriptActionCount"] = createExportWrapper("FPDFDoc_GetJavaScriptActionCount", 1);\n Module["_FPDFDoc_GetJavaScriptAction"] = createExportWrapper("FPDFDoc_GetJavaScriptAction", 2);\n Module["_FPDFDoc_CloseJavaScriptAction"] = createExportWrapper("FPDFDoc_CloseJavaScriptAction", 1);\n Module["_FPDFJavaScriptAction_GetName"] = createExportWrapper("FPDFJavaScriptAction_GetName", 3);\n Module["_FPDFJavaScriptAction_GetScript"] = createExportWrapper("FPDFJavaScriptAction_GetScript", 3);\n Module["_FPDF_ImportPagesByIndex"] = createExportWrapper(\n "FPDF_ImportPagesByIndex",\n 5\n );\n Module["_FPDF_ImportPages"] = createExportWrapper(\n "FPDF_ImportPages",\n 4\n );\n Module["_FPDF_ImportNPagesToOne"] = createExportWrapper(\n "FPDF_ImportNPagesToOne",\n 5\n );\n Module["_FPDF_NewXObjectFromPage"] = createExportWrapper(\n "FPDF_NewXObjectFromPage",\n 3\n );\n Module["_FPDF_CloseXObject"] = createExportWrapper(\n "FPDF_CloseXObject",\n 1\n );\n Module["_FPDF_NewFormObjectFromXObject"] = createExportWrapper("FPDF_NewFormObjectFromXObject", 1);\n Module["_FPDF_CopyViewerPreferences"] = createExportWrapper(\n "FPDF_CopyViewerPreferences",\n 2\n );\n Module["_FPDF_RenderPageBitmapWithColorScheme_Start"] = createExportWrapper("FPDF_RenderPageBitmapWithColorScheme_Start", 10);\n Module["_FPDF_RenderPageBitmap_Start"] = createExportWrapper("FPDF_RenderPageBitmap_Start", 9);\n Module["_FPDF_RenderPage_Continue"] = createExportWrapper(\n "FPDF_RenderPage_Continue",\n 2\n );\n Module["_FPDF_RenderPage_Close"] = createExportWrapper(\n "FPDF_RenderPage_Close",\n 1\n );\n Module["_FPDF_SaveWithVersion"] = createExportWrapper(\n "FPDF_SaveWithVersion",\n 4\n );\n Module["_FPDFText_GetCharIndexFromTextIndex"] = createExportWrapper("FPDFText_GetCharIndexFromTextIndex", 2);\n Module["_FPDFText_GetTextIndexFromCharIndex"] = createExportWrapper("FPDFText_GetTextIndexFromCharIndex", 2);\n Module["_FPDF_GetSignatureCount"] = createExportWrapper(\n "FPDF_GetSignatureCount",\n 1\n );\n Module["_FPDF_GetSignatureObject"] = createExportWrapper(\n "FPDF_GetSignatureObject",\n 2\n );\n Module["_FPDFSignatureObj_GetContents"] = createExportWrapper("FPDFSignatureObj_GetContents", 3);\n Module["_FPDFSignatureObj_GetByteRange"] = createExportWrapper("FPDFSignatureObj_GetByteRange", 3);\n Module["_FPDFSignatureObj_GetSubFilter"] = createExportWrapper("FPDFSignatureObj_GetSubFilter", 3);\n Module["_FPDFSignatureObj_GetReason"] = createExportWrapper(\n "FPDFSignatureObj_GetReason",\n 3\n );\n Module["_FPDFSignatureObj_GetTime"] = createExportWrapper(\n "FPDFSignatureObj_GetTime",\n 3\n );\n Module["_FPDFSignatureObj_GetDocMDPPermission"] = createExportWrapper("FPDFSignatureObj_GetDocMDPPermission", 1);\n Module["_FPDF_StructTree_GetForPage"] = createExportWrapper(\n "FPDF_StructTree_GetForPage",\n 1\n );\n Module["_FPDF_StructTree_Close"] = createExportWrapper(\n "FPDF_StructTree_Close",\n 1\n );\n Module["_FPDF_StructTree_CountChildren"] = createExportWrapper("FPDF_StructTree_CountChildren", 1);\n Module["_FPDF_StructTree_GetChildAtIndex"] = createExportWrapper("FPDF_StructTree_GetChildAtIndex", 2);\n Module["_FPDF_StructElement_GetAltText"] = createExportWrapper("FPDF_StructElement_GetAltText", 3);\n Module["_FPDF_StructElement_GetActualText"] = createExportWrapper("FPDF_StructElement_GetActualText", 3);\n Module["_FPDF_StructElement_GetID"] = createExportWrapper(\n "FPDF_StructElement_GetID",\n 3\n );\n Module["_FPDF_StructElement_GetLang"] = createExportWrapper(\n "FPDF_StructElement_GetLang",\n 3\n );\n Module["_FPDF_StructElement_GetAttributeCount"] = createExportWrapper("FPDF_StructElement_GetAttributeCount", 1);\n Module["_FPDF_StructElement_GetAttributeAtIndex"] = createExportWrapper("FPDF_StructElement_GetAttributeAtIndex", 2);\n Module["_FPDF_StructElement_GetStringAttribute"] = createExportWrapper("FPDF_StructElement_GetStringAttribute", 4);\n Module["_FPDF_StructElement_GetMarkedContentID"] = createExportWrapper("FPDF_StructElement_GetMarkedContentID", 1);\n Module["_FPDF_StructElement_GetType"] = createExportWrapper(\n "FPDF_StructElement_GetType",\n 3\n );\n Module["_FPDF_StructElement_GetObjType"] = createExportWrapper("FPDF_StructElement_GetObjType", 3);\n Module["_FPDF_StructElement_GetTitle"] = createExportWrapper("FPDF_StructElement_GetTitle", 3);\n Module["_FPDF_StructElement_CountChildren"] = createExportWrapper("FPDF_StructElement_CountChildren", 1);\n Module["_FPDF_StructElement_GetChildAtIndex"] = createExportWrapper("FPDF_StructElement_GetChildAtIndex", 2);\n Module["_FPDF_StructElement_GetChildMarkedContentID"] = createExportWrapper("FPDF_StructElement_GetChildMarkedContentID", 2);\n Module["_FPDF_StructElement_GetParent"] = createExportWrapper("FPDF_StructElement_GetParent", 1);\n Module["_FPDF_StructElement_Attr_GetCount"] = createExportWrapper("FPDF_StructElement_Attr_GetCount", 1);\n Module["_FPDF_StructElement_Attr_GetName"] = createExportWrapper("FPDF_StructElement_Attr_GetName", 5);\n Module["_FPDF_StructElement_Attr_GetValue"] = createExportWrapper("FPDF_StructElement_Attr_GetValue", 2);\n Module["_FPDF_StructElement_Attr_GetType"] = createExportWrapper("FPDF_StructElement_Attr_GetType", 1);\n Module["_FPDF_StructElement_Attr_GetBooleanValue"] = createExportWrapper("FPDF_StructElement_Attr_GetBooleanValue", 2);\n Module["_FPDF_StructElement_Attr_GetNumberValue"] = createExportWrapper("FPDF_StructElement_Attr_GetNumberValue", 2);\n Module["_FPDF_StructElement_Attr_GetStringValue"] = createExportWrapper("FPDF_StructElement_Attr_GetStringValue", 4);\n Module["_FPDF_StructElement_Attr_GetBlobValue"] = createExportWrapper("FPDF_StructElement_Attr_GetBlobValue", 4);\n Module["_FPDF_StructElement_Attr_CountChildren"] = createExportWrapper("FPDF_StructElement_Attr_CountChildren", 1);\n Module["_FPDF_StructElement_Attr_GetChildAtIndex"] = createExportWrapper("FPDF_StructElement_Attr_GetChildAtIndex", 2);\n Module["_FPDF_StructElement_GetMarkedContentIdCount"] = createExportWrapper("FPDF_StructElement_GetMarkedContentIdCount", 1);\n Module["_FPDF_StructElement_GetMarkedContentIdAtIndex"] = createExportWrapper("FPDF_StructElement_GetMarkedContentIdAtIndex", 2);\n Module["_FPDF_AddInstalledFont"] = createExportWrapper(\n "FPDF_AddInstalledFont",\n 3\n );\n Module["_FPDF_SetSystemFontInfo"] = createExportWrapper(\n "FPDF_SetSystemFontInfo",\n 1\n );\n Module["_FPDF_GetDefaultTTFMap"] = createExportWrapper(\n "FPDF_GetDefaultTTFMap",\n 0\n );\n Module["_FPDF_GetDefaultTTFMapCount"] = createExportWrapper(\n "FPDF_GetDefaultTTFMapCount",\n 0\n );\n Module["_FPDF_GetDefaultTTFMapEntry"] = createExportWrapper(\n "FPDF_GetDefaultTTFMapEntry",\n 1\n );\n Module["_FPDF_GetDefaultSystemFontInfo"] = createExportWrapper("FPDF_GetDefaultSystemFontInfo", 0);\n Module["_FPDF_FreeDefaultSystemFontInfo"] = createExportWrapper("FPDF_FreeDefaultSystemFontInfo", 1);\n Module["_FPDFText_LoadPage"] = createExportWrapper(\n "FPDFText_LoadPage",\n 1\n );\n Module["_FPDFText_ClosePage"] = createExportWrapper(\n "FPDFText_ClosePage",\n 1\n );\n Module["_FPDFText_CountChars"] = createExportWrapper(\n "FPDFText_CountChars",\n 1\n );\n Module["_FPDFText_GetUnicode"] = createExportWrapper(\n "FPDFText_GetUnicode",\n 2\n );\n Module["_FPDFText_GetTextObject"] = createExportWrapper(\n "FPDFText_GetTextObject",\n 2\n );\n Module["_FPDFText_IsGenerated"] = createExportWrapper(\n "FPDFText_IsGenerated",\n 2\n );\n Module["_FPDFText_IsHyphen"] = createExportWrapper(\n "FPDFText_IsHyphen",\n 2\n );\n Module["_FPDFText_HasUnicodeMapError"] = createExportWrapper("FPDFText_HasUnicodeMapError", 2);\n Module["_FPDFText_GetFontSize"] = createExportWrapper(\n "FPDFText_GetFontSize",\n 2\n );\n Module["_FPDFText_GetFontInfo"] = createExportWrapper(\n "FPDFText_GetFontInfo",\n 5\n );\n Module["_FPDFText_GetFontWeight"] = createExportWrapper(\n "FPDFText_GetFontWeight",\n 2\n );\n Module["_FPDFText_GetFillColor"] = createExportWrapper(\n "FPDFText_GetFillColor",\n 6\n );\n Module["_FPDFText_GetStrokeColor"] = createExportWrapper(\n "FPDFText_GetStrokeColor",\n 6\n );\n Module["_FPDFText_GetCharAngle"] = createExportWrapper(\n "FPDFText_GetCharAngle",\n 2\n );\n Module["_FPDFText_GetCharBox"] = createExportWrapper(\n "FPDFText_GetCharBox",\n 6\n );\n Module["_FPDFText_GetLooseCharBox"] = createExportWrapper(\n "FPDFText_GetLooseCharBox",\n 3\n );\n Module["_FPDFText_GetMatrix"] = createExportWrapper(\n "FPDFText_GetMatrix",\n 3\n );\n Module["_FPDFText_GetCharOrigin"] = createExportWrapper(\n "FPDFText_GetCharOrigin",\n 4\n );\n Module["_FPDFText_GetCharIndexAtPos"] = createExportWrapper(\n "FPDFText_GetCharIndexAtPos",\n 5\n );\n Module["_FPDFText_GetText"] = createExportWrapper(\n "FPDFText_GetText",\n 4\n );\n Module["_FPDFText_CountRects"] = createExportWrapper(\n "FPDFText_CountRects",\n 3\n );\n Module["_FPDFText_GetRect"] = createExportWrapper(\n "FPDFText_GetRect",\n 6\n );\n Module["_FPDFText_GetBoundedText"] = createExportWrapper(\n "FPDFText_GetBoundedText",\n 7\n );\n Module["_FPDFText_FindStart"] = createExportWrapper(\n "FPDFText_FindStart",\n 4\n );\n Module["_FPDFText_FindNext"] = createExportWrapper(\n "FPDFText_FindNext",\n 1\n );\n Module["_FPDFText_FindPrev"] = createExportWrapper(\n "FPDFText_FindPrev",\n 1\n );\n Module["_FPDFText_GetSchResultIndex"] = createExportWrapper(\n "FPDFText_GetSchResultIndex",\n 1\n );\n Module["_FPDFText_GetSchCount"] = createExportWrapper(\n "FPDFText_GetSchCount",\n 1\n );\n Module["_FPDFText_FindClose"] = createExportWrapper(\n "FPDFText_FindClose",\n 1\n );\n Module["_FPDFLink_LoadWebLinks"] = createExportWrapper(\n "FPDFLink_LoadWebLinks",\n 1\n );\n Module["_FPDFLink_CountWebLinks"] = createExportWrapper(\n "FPDFLink_CountWebLinks",\n 1\n );\n Module["_FPDFLink_GetURL"] = createExportWrapper("FPDFLink_GetURL", 4);\n Module["_FPDFLink_CountRects"] = createExportWrapper(\n "FPDFLink_CountRects",\n 2\n );\n Module["_FPDFLink_GetRect"] = createExportWrapper(\n "FPDFLink_GetRect",\n 7\n );\n Module["_FPDFLink_GetTextRange"] = createExportWrapper(\n "FPDFLink_GetTextRange",\n 4\n );\n Module["_FPDFLink_CloseWebLinks"] = createExportWrapper(\n "FPDFLink_CloseWebLinks",\n 1\n );\n Module["_FPDFPage_GetDecodedThumbnailData"] = createExportWrapper("FPDFPage_GetDecodedThumbnailData", 3);\n Module["_FPDFPage_GetRawThumbnailData"] = createExportWrapper("FPDFPage_GetRawThumbnailData", 3);\n Module["_FPDFPage_GetThumbnailAsBitmap"] = createExportWrapper("FPDFPage_GetThumbnailAsBitmap", 1);\n Module["_FPDFPage_SetMediaBox"] = createExportWrapper(\n "FPDFPage_SetMediaBox",\n 5\n );\n Module["_FPDFPage_SetCropBox"] = createExportWrapper(\n "FPDFPage_SetCropBox",\n 5\n );\n Module["_FPDFPage_SetBleedBox"] = createExportWrapper(\n "FPDFPage_SetBleedBox",\n 5\n );\n Module["_FPDFPage_SetTrimBox"] = createExportWrapper(\n "FPDFPage_SetTrimBox",\n 5\n );\n Module["_FPDFPage_SetArtBox"] = createExportWrapper(\n "FPDFPage_SetArtBox",\n 5\n );\n Module["_FPDFPage_GetMediaBox"] = createExportWrapper(\n "FPDFPage_GetMediaBox",\n 5\n );\n Module["_FPDFPage_GetCropBox"] = createExportWrapper(\n "FPDFPage_GetCropBox",\n 5\n );\n Module["_FPDFPage_GetBleedBox"] = createExportWrapper(\n "FPDFPage_GetBleedBox",\n 5\n );\n Module["_FPDFPage_GetTrimBox"] = createExportWrapper(\n "FPDFPage_GetTrimBox",\n 5\n );\n Module["_FPDFPage_GetArtBox"] = createExportWrapper(\n "FPDFPage_GetArtBox",\n 5\n );\n Module["_FPDFPage_TransFormWithClip"] = createExportWrapper(\n "FPDFPage_TransFormWithClip",\n 3\n );\n Module["_FPDFPageObj_TransformClipPath"] = createExportWrapper("FPDFPageObj_TransformClipPath", 7);\n Module["_FPDFPageObj_GetClipPath"] = createExportWrapper(\n "FPDFPageObj_GetClipPath",\n 1\n );\n Module["_FPDFClipPath_CountPaths"] = createExportWrapper(\n "FPDFClipPath_CountPaths",\n 1\n );\n Module["_FPDFClipPath_CountPathSegments"] = createExportWrapper("FPDFClipPath_CountPathSegments", 2);\n Module["_FPDFClipPath_GetPathSegment"] = createExportWrapper("FPDFClipPath_GetPathSegment", 3);\n Module["_FPDF_CreateClipPath"] = createExportWrapper(\n "FPDF_CreateClipPath",\n 4\n );\n Module["_FPDF_DestroyClipPath"] = createExportWrapper(\n "FPDF_DestroyClipPath",\n 1\n );\n Module["_FPDFPage_InsertClipPath"] = createExportWrapper(\n "FPDFPage_InsertClipPath",\n 2\n );\n Module["_FPDF_InitLibrary"] = createExportWrapper(\n "FPDF_InitLibrary",\n 0\n );\n Module["_FPDF_DestroyLibrary"] = createExportWrapper(\n "FPDF_DestroyLibrary",\n 0\n );\n Module["_FPDF_SetSandBoxPolicy"] = createExportWrapper(\n "FPDF_SetSandBoxPolicy",\n 2\n );\n Module["_FPDF_LoadDocument"] = createExportWrapper(\n "FPDF_LoadDocument",\n 2\n );\n Module["_FPDF_GetFormType"] = createExportWrapper(\n "FPDF_GetFormType",\n 1\n );\n Module["_FPDF_LoadXFA"] = createExportWrapper("FPDF_LoadXFA", 1);\n Module["_FPDF_LoadMemDocument"] = createExportWrapper(\n "FPDF_LoadMemDocument",\n 3\n );\n Module["_FPDF_LoadMemDocument64"] = createExportWrapper(\n "FPDF_LoadMemDocument64",\n 3\n );\n Module["_FPDF_LoadCustomDocument"] = createExportWrapper(\n "FPDF_LoadCustomDocument",\n 2\n );\n Module["_FPDF_GetFileVersion"] = createExportWrapper(\n "FPDF_GetFileVersion",\n 2\n );\n Module["_FPDF_DocumentHasValidCrossReferenceTable"] = createExportWrapper("FPDF_DocumentHasValidCrossReferenceTable", 1);\n Module["_FPDF_GetDocPermissions"] = createExportWrapper(\n "FPDF_GetDocPermissions",\n 1\n );\n Module["_FPDF_GetDocUserPermissions"] = createExportWrapper(\n "FPDF_GetDocUserPermissions",\n 1\n );\n Module["_FPDF_GetSecurityHandlerRevision"] = createExportWrapper("FPDF_GetSecurityHandlerRevision", 1);\n Module["_EPDF_SetEncryption"] = createExportWrapper(\n "EPDF_SetEncryption",\n 4\n );\n Module["_EPDF_RemoveEncryption"] = createExportWrapper(\n "EPDF_RemoveEncryption",\n 1\n );\n Module["_EPDF_UnlockOwnerPermissions"] = createExportWrapper("EPDF_UnlockOwnerPermissions", 2);\n Module["_EPDF_IsEncrypted"] = createExportWrapper(\n "EPDF_IsEncrypted",\n 1\n );\n Module["_EPDF_IsOwnerUnlocked"] = createExportWrapper(\n "EPDF_IsOwnerUnlocked",\n 1\n );\n Module["_FPDF_GetPageCount"] = createExportWrapper(\n "FPDF_GetPageCount",\n 1\n );\n Module["_FPDF_LoadPage"] = createExportWrapper("FPDF_LoadPage", 2);\n Module["_FPDF_GetPageWidthF"] = createExportWrapper(\n "FPDF_GetPageWidthF",\n 1\n );\n Module["_FPDF_GetPageWidth"] = createExportWrapper(\n "FPDF_GetPageWidth",\n 1\n );\n Module["_FPDF_GetPageHeightF"] = createExportWrapper(\n "FPDF_GetPageHeightF",\n 1\n );\n Module["_FPDF_GetPageHeight"] = createExportWrapper(\n "FPDF_GetPageHeight",\n 1\n );\n Module["_FPDF_GetPageBoundingBox"] = createExportWrapper(\n "FPDF_GetPageBoundingBox",\n 2\n );\n Module["_FPDF_RenderPageBitmap"] = createExportWrapper(\n "FPDF_RenderPageBitmap",\n 8\n );\n Module["_FPDF_RenderPageBitmapWithMatrix"] = createExportWrapper("FPDF_RenderPageBitmapWithMatrix", 5);\n Module["_EPDF_RenderAnnotBitmap"] = createExportWrapper(\n "EPDF_RenderAnnotBitmap",\n 6\n );\n Module["_EPDF_RenderAnnotBitmapUnrotated"] = createExportWrapper("EPDF_RenderAnnotBitmapUnrotated", 6);\n Module["_FPDF_ClosePage"] = createExportWrapper("FPDF_ClosePage", 1);\n Module["_FPDF_CloseDocument"] = createExportWrapper(\n "FPDF_CloseDocument",\n 1\n );\n Module["_FPDF_GetLastError"] = createExportWrapper(\n "FPDF_GetLastError",\n 0\n );\n Module["_FPDF_DeviceToPage"] = createExportWrapper(\n "FPDF_DeviceToPage",\n 10\n );\n Module["_FPDF_PageToDevice"] = createExportWrapper(\n "FPDF_PageToDevice",\n 10\n );\n Module["_FPDFBitmap_Create"] = createExportWrapper(\n "FPDFBitmap_Create",\n 3\n );\n Module["_FPDFBitmap_CreateEx"] = createExportWrapper(\n "FPDFBitmap_CreateEx",\n 5\n );\n Module["_FPDFBitmap_GetFormat"] = createExportWrapper(\n "FPDFBitmap_GetFormat",\n 1\n );\n Module["_FPDFBitmap_FillRect"] = createExportWrapper(\n "FPDFBitmap_FillRect",\n 6\n );\n Module["_FPDFBitmap_GetBuffer"] = createExportWrapper(\n "FPDFBitmap_GetBuffer",\n 1\n );\n Module["_FPDFBitmap_GetWidth"] = createExportWrapper(\n "FPDFBitmap_GetWidth",\n 1\n );\n Module["_FPDFBitmap_GetHeight"] = createExportWrapper(\n "FPDFBitmap_GetHeight",\n 1\n );\n Module["_FPDFBitmap_GetStride"] = createExportWrapper(\n "FPDFBitmap_GetStride",\n 1\n );\n Module["_FPDFBitmap_Destroy"] = createExportWrapper(\n "FPDFBitmap_Destroy",\n 1\n );\n Module["_FPDF_GetPageSizeByIndexF"] = createExportWrapper(\n "FPDF_GetPageSizeByIndexF",\n 3\n );\n Module["_EPDF_GetPageRotationByIndex"] = createExportWrapper("EPDF_GetPageRotationByIndex", 2);\n Module["_EPDF_GetPageSizeByIndexNormalized"] = createExportWrapper("EPDF_GetPageSizeByIndexNormalized", 3);\n Module["_EPDF_LoadPageNormalized"] = createExportWrapper(\n "EPDF_LoadPageNormalized",\n 3\n );\n Module["_FPDF_GetPageSizeByIndex"] = createExportWrapper(\n "FPDF_GetPageSizeByIndex",\n 4\n );\n Module["_FPDF_VIEWERREF_GetPrintScaling"] = createExportWrapper("FPDF_VIEWERREF_GetPrintScaling", 1);\n Module["_FPDF_VIEWERREF_GetNumCopies"] = createExportWrapper("FPDF_VIEWERREF_GetNumCopies", 1);\n Module["_FPDF_VIEWERREF_GetPrintPageRange"] = createExportWrapper("FPDF_VIEWERREF_GetPrintPageRange", 1);\n Module["_FPDF_VIEWERREF_GetPrintPageRangeCount"] = createExportWrapper("FPDF_VIEWERREF_GetPrintPageRangeCount", 1);\n Module["_FPDF_VIEWERREF_GetPrintPageRangeElement"] = createExportWrapper("FPDF_VIEWERREF_GetPrintPageRangeElement", 2);\n Module["_FPDF_VIEWERREF_GetDuplex"] = createExportWrapper(\n "FPDF_VIEWERREF_GetDuplex",\n 1\n );\n Module["_FPDF_VIEWERREF_GetName"] = createExportWrapper(\n "FPDF_VIEWERREF_GetName",\n 4\n );\n Module["_FPDF_CountNamedDests"] = createExportWrapper(\n "FPDF_CountNamedDests",\n 1\n );\n Module["_FPDF_GetNamedDestByName"] = createExportWrapper(\n "FPDF_GetNamedDestByName",\n 2\n );\n Module["_FPDF_GetNamedDest"] = createExportWrapper(\n "FPDF_GetNamedDest",\n 4\n );\n Module["_FPDF_GetXFAPacketCount"] = createExportWrapper(\n "FPDF_GetXFAPacketCount",\n 1\n );\n Module["_FPDF_GetXFAPacketName"] = createExportWrapper(\n "FPDF_GetXFAPacketName",\n 4\n );\n Module["_FPDF_GetXFAPacketContent"] = createExportWrapper(\n "FPDF_GetXFAPacketContent",\n 5\n );\n Module["_FPDF_GetTrailerEnds"] = createExportWrapper(\n "FPDF_GetTrailerEnds",\n 3\n );\n var _fflush = createExportWrapper("fflush", 1);\n var _emscripten_builtin_memalign = createExportWrapper("emscripten_builtin_memalign", 2);\n var _strerror = createExportWrapper("strerror", 1);\n var _setThrew = createExportWrapper("setThrew", 2);\n var _emscripten_stack_init = () => (_emscripten_stack_init = wasmExports["emscripten_stack_init"])();\n var _emscripten_stack_get_end = () => (_emscripten_stack_get_end = wasmExports["emscripten_stack_get_end"])();\n var __emscripten_stack_restore = (a0) => (__emscripten_stack_restore = wasmExports["_emscripten_stack_restore"])(a0);\n var __emscripten_stack_alloc = (a0) => (__emscripten_stack_alloc = wasmExports["_emscripten_stack_alloc"])(a0);\n var _emscripten_stack_get_current = () => (_emscripten_stack_get_current = wasmExports["emscripten_stack_get_current"])();\n Module["dynCall_j"] = createExportWrapper("dynCall_j", 1);\n Module["dynCall_ji"] = createExportWrapper("dynCall_ji", 2);\n Module["dynCall_iiij"] = createExportWrapper("dynCall_iiij", 5);\n Module["dynCall_jji"] = createExportWrapper("dynCall_jji", 4);\n Module["dynCall_iji"] = createExportWrapper("dynCall_iji", 4);\n Module["dynCall_viijii"] = createExportWrapper("dynCall_viijii", 7);\n Module["dynCall_jij"] = createExportWrapper("dynCall_jij", 4);\n Module["dynCall_iij"] = createExportWrapper("dynCall_iij", 4);\n Module["dynCall_iiji"] = createExportWrapper("dynCall_iiji", 5);\n Module["dynCall_jiji"] = createExportWrapper("dynCall_jiji", 5);\n Module["dynCall_iiiiij"] = createExportWrapper("dynCall_iiiiij", 7);\n Module["dynCall_iiiiijj"] = createExportWrapper("dynCall_iiiiijj", 9);\n Module["dynCall_iiiiiijj"] = createExportWrapper(\n "dynCall_iiiiiijj",\n 10\n );\n Module["dynCall_viji"] = createExportWrapper("dynCall_viji", 5);\n function invoke_viii(index, a1, a2, a3) {\n var sp = stackSave();\n try {\n getWasmTableEntry(index)(a1, a2, a3);\n } catch (e) {\n stackRestore(sp);\n if (e !== e + 0) throw e;\n _setThrew(1, 0);\n }\n }\n function invoke_ii(index, a1) {\n var sp = stackSave();\n try {\n return getWasmTableEntry(index)(a1);\n } catch (e) {\n stackRestore(sp);\n if (e !== e + 0) throw e;\n _setThrew(1, 0);\n }\n }\n function invoke_iii(index, a1, a2) {\n var sp = stackSave();\n try {\n return getWasmTableEntry(index)(a1, a2);\n } catch (e) {\n stackRestore(sp);\n if (e !== e + 0) throw e;\n _setThrew(1, 0);\n }\n }\n function invoke_iiii(index, a1, a2, a3) {\n var sp = stackSave();\n try {\n return getWasmTableEntry(index)(a1, a2, a3);\n } catch (e) {\n stackRestore(sp);\n if (e !== e + 0) throw e;\n _setThrew(1, 0);\n }\n }\n function invoke_viiii(index, a1, a2, a3, a4) {\n var sp = stackSave();\n try {\n getWasmTableEntry(index)(a1, a2, a3, a4);\n } catch (e) {\n stackRestore(sp);\n if (e !== e + 0) throw e;\n _setThrew(1, 0);\n }\n }\n function invoke_iiiii(index, a1, a2, a3, a4) {\n var sp = stackSave();\n try {\n return getWasmTableEntry(index)(a1, a2, a3, a4);\n } catch (e) {\n stackRestore(sp);\n if (e !== e + 0) throw e;\n _setThrew(1, 0);\n }\n }\n function invoke_v(index) {\n var sp = stackSave();\n try {\n getWasmTableEntry(index)();\n } catch (e) {\n stackRestore(sp);\n if (e !== e + 0) throw e;\n _setThrew(1, 0);\n }\n }\n function invoke_vii(index, a1, a2) {\n var sp = stackSave();\n try {\n getWasmTableEntry(index)(a1, a2);\n } catch (e) {\n stackRestore(sp);\n if (e !== e + 0) throw e;\n _setThrew(1, 0);\n }\n }\n function invoke_viiiiiiiii(index, a1, a2, a3, a4, a5, a6, a7, a8, a9) {\n var sp = stackSave();\n try {\n getWasmTableEntry(index)(a1, a2, a3, a4, a5, a6, a7, a8, a9);\n } catch (e) {\n stackRestore(sp);\n if (e !== e + 0) throw e;\n _setThrew(1, 0);\n }\n }\n Module["wasmExports"] = wasmExports;\n Module["ccall"] = ccall;\n Module["cwrap"] = cwrap;\n Module["addFunction"] = addFunction;\n Module["removeFunction"] = removeFunction;\n Module["setValue"] = setValue;\n Module["getValue"] = getValue;\n Module["UTF8ToString"] = UTF8ToString;\n Module["stringToUTF8"] = stringToUTF8;\n Module["UTF16ToString"] = UTF16ToString;\n Module["stringToUTF16"] = stringToUTF16;\n var missingLibrarySymbols = [\n "writeI53ToI64",\n "writeI53ToI64Clamped",\n "writeI53ToI64Signaling",\n "writeI53ToU64Clamped",\n "writeI53ToU64Signaling",\n "readI53FromI64",\n "readI53FromU64",\n "convertI32PairToI53",\n "convertU32PairToI53",\n "getTempRet0",\n "setTempRet0",\n "exitJS",\n "inetPton4",\n "inetNtop4",\n "inetPton6",\n "inetNtop6",\n "readSockaddr",\n "writeSockaddr",\n "emscriptenLog",\n "readEmAsmArgs",\n "jstoi_q",\n "listenOnce",\n "autoResumeAudioContext",\n "dynCallLegacy",\n "getDynCaller",\n "dynCall",\n "handleException",\n "keepRuntimeAlive",\n "runtimeKeepalivePush",\n "runtimeKeepalivePop",\n "callUserCallback",\n "maybeExit",\n "asmjsMangle",\n "HandleAllocator",\n "getNativeTypeSize",\n "STACK_SIZE",\n "STACK_ALIGN",\n "POINTER_SIZE",\n "ASSERTIONS",\n "reallyNegative",\n "unSign",\n "strLen",\n "reSign",\n "formatString",\n "intArrayToString",\n "AsciiToString",\n "lengthBytesUTF16",\n "UTF32ToString",\n "stringToUTF32",\n "lengthBytesUTF32",\n "stringToNewUTF8",\n "registerKeyEventCallback",\n "maybeCStringToJsString",\n "findEventTarget",\n "getBoundingClientRect",\n "fillMouseEventData",\n "registerMouseEventCallback",\n "registerWheelEventCallback",\n "registerUiEventCallback",\n "registerFocusEventCallback",\n "fillDeviceOrientationEventData",\n "registerDeviceOrientationEventCallback",\n "fillDeviceMotionEventData",\n "registerDeviceMotionEventCallback",\n "screenOrientation",\n "fillOrientationChangeEventData",\n "registerOrientationChangeEventCallback",\n "fillFullscreenChangeEventData",\n "registerFullscreenChangeEventCallback",\n "JSEvents_requestFullscreen",\n "JSEvents_resizeCanvasForFullscreen",\n "registerRestoreOldStyle",\n "hideEverythingExceptGivenElement",\n "restoreHiddenElements",\n "setLetterbox",\n "softFullscreenResizeWebGLRenderTarget",\n "doRequestFullscreen",\n "fillPointerlockChangeEventData",\n "registerPointerlockChangeEventCallback",\n "registerPointerlockErrorEventCallback",\n "requestPointerLock",\n "fillVisibilityChangeEventData",\n "registerVisibilityChangeEventCallback",\n "registerTouchEventCallback",\n "fillGamepadEventData",\n "registerGamepadEventCallback",\n "registerBeforeUnloadEventCallback",\n "fillBatteryEventData",\n "battery",\n "registerBatteryEventCallback",\n "setCanvasElementSize",\n "getCanvasElementSize",\n "jsStackTrace",\n "getCallstack",\n "convertPCtoSourceLocation",\n "checkWasiClock",\n "wasiRightsToMuslOFlags",\n "wasiOFlagsToMuslOFlags",\n "createDyncallWrapper",\n "safeSetTimeout",\n "setImmediateWrapped",\n "clearImmediateWrapped",\n "polyfillSetImmediate",\n "registerPostMainLoop",\n "registerPreMainLoop",\n "getPromise",\n "makePromise",\n "idsToPromises",\n "makePromiseCallback",\n "ExceptionInfo",\n "findMatchingCatch",\n "Browser_asyncPrepareDataCounter",\n "safeRequestAnimationFrame",\n "arraySum",\n "addDays",\n "getSocketFromFD",\n "getSocketAddress",\n "FS_unlink",\n "FS_mkdirTree",\n "_setNetworkCallback",\n "heapObjectForWebGLType",\n "toTypedArrayIndex",\n "webgl_enable_ANGLE_instanced_arrays",\n "webgl_enable_OES_vertex_array_object",\n "webgl_enable_WEBGL_draw_buffers",\n "webgl_enable_WEBGL_multi_draw",\n "webgl_enable_EXT_polygon_offset_clamp",\n "webgl_enable_EXT_clip_control",\n "webgl_enable_WEBGL_polygon_mode",\n "emscriptenWebGLGet",\n "computeUnpackAlignedImageSize",\n "colorChannelsInGlTextureFormat",\n "emscriptenWebGLGetTexPixelData",\n "emscriptenWebGLGetUniform",\n "webglGetUniformLocation",\n "webglPrepareUniformLocationsBeforeFirstUse",\n "webglGetLeftBracePos",\n "emscriptenWebGLGetVertexAttrib",\n "__glGetActiveAttribOrUniform",\n "writeGLArray",\n "registerWebGlEventCallback",\n "runAndAbortIfError",\n "ALLOC_NORMAL",\n "ALLOC_STACK",\n "allocate",\n "writeStringToMemory",\n "writeAsciiToMemory",\n "setErrNo",\n "demangle",\n "stackTrace"\n ];\n missingLibrarySymbols.forEach(missingLibrarySymbol);\n var unexportedSymbols = [\n "run",\n "addOnPreRun",\n "addOnInit",\n "addOnPreMain",\n "addOnExit",\n "addOnPostRun",\n "addRunDependency",\n "removeRunDependency",\n "out",\n "err",\n "callMain",\n "abort",\n "wasmMemory",\n "writeStackCookie",\n "checkStackCookie",\n "convertI32PairToI53Checked",\n "stackSave",\n "stackRestore",\n "stackAlloc",\n "ptrToString",\n "zeroMemory",\n "getHeapMax",\n "growMemory",\n "ENV",\n "ERRNO_CODES",\n "strError",\n "DNS",\n "Protocols",\n "Sockets",\n "initRandomFill",\n "randomFill",\n "timers",\n "warnOnce",\n "readEmAsmArgsArray",\n "jstoi_s",\n "getExecutableName",\n "asyncLoad",\n "alignMemory",\n "mmapAlloc",\n "wasmTable",\n "noExitRuntime",\n "getCFunc",\n "uleb128Encode",\n "sigToWasmTypes",\n "generateFuncType",\n "convertJsFunctionToWasm",\n "freeTableIndexes",\n "functionsInTableMap",\n "getEmptyTableSlot",\n "updateTableMap",\n "getFunctionAddress",\n "PATH",\n "PATH_FS",\n "UTF8Decoder",\n "UTF8ArrayToString",\n "stringToUTF8Array",\n "lengthBytesUTF8",\n "intArrayFromString",\n "stringToAscii",\n "UTF16Decoder",\n "stringToUTF8OnStack",\n "writeArrayToMemory",\n "JSEvents",\n "specialHTMLTargets",\n "findCanvasEventTarget",\n "currentFullscreenStrategy",\n "restoreOldWindowedStyle",\n "UNWIND_CACHE",\n "ExitStatus",\n "getEnvStrings",\n "doReadv",\n "doWritev",\n "promiseMap",\n "uncaughtExceptionCount",\n "exceptionLast",\n "exceptionCaught",\n "Browser",\n "getPreloadedImageData__data",\n "wget",\n "MONTH_DAYS_REGULAR",\n "MONTH_DAYS_LEAP",\n "MONTH_DAYS_REGULAR_CUMULATIVE",\n "MONTH_DAYS_LEAP_CUMULATIVE",\n "isLeapYear",\n "ydayFromDate",\n "SYSCALLS",\n "preloadPlugins",\n "FS_createPreloadedFile",\n "FS_modeStringToFlags",\n "FS_getMode",\n "FS_stdin_getChar_buffer",\n "FS_stdin_getChar",\n "FS_createPath",\n "FS_createDevice",\n "FS_readFile",\n "FS",\n "FS_createDataFile",\n "FS_createLazyFile",\n "MEMFS",\n "TTY",\n "PIPEFS",\n "SOCKFS",\n "tempFixedLengthArray",\n "miniTempWebGLFloatBuffers",\n "miniTempWebGLIntBuffers",\n "GL",\n "AL",\n "GLUT",\n "EGL",\n "GLEW",\n "IDBStore",\n "SDL",\n "SDL_gfx",\n "allocateUTF8",\n "allocateUTF8OnStack",\n "print",\n "printErr"\n ];\n unexportedSymbols.forEach(unexportedRuntimeSymbol);\n var calledRun;\n var calledPrerun;\n dependenciesFulfilled = function runCaller() {\n if (!calledRun) run();\n if (!calledRun) dependenciesFulfilled = runCaller;\n };\n function stackCheckInit() {\n _emscripten_stack_init();\n writeStackCookie();\n }\n function run() {\n if (runDependencies > 0) {\n return;\n }\n stackCheckInit();\n if (!calledPrerun) {\n calledPrerun = 1;\n preRun();\n if (runDependencies > 0) {\n return;\n }\n }\n function doRun() {\n var _a;\n if (calledRun) return;\n calledRun = 1;\n Module["calledRun"] = 1;\n if (ABORT) return;\n initRuntime();\n readyPromiseResolve(Module);\n (_a = Module["onRuntimeInitialized"]) == null ? void 0 : _a.call(Module);\n assert(\n !Module["_main"],\n \'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]\'\n );\n postRun();\n }\n if (Module["setStatus"]) {\n Module["setStatus"]("Running...");\n setTimeout(() => {\n setTimeout(() => Module["setStatus"](""), 1);\n doRun();\n }, 1);\n } else {\n doRun();\n }\n checkStackCookie();\n }\n if (Module["preInit"]) {\n if (typeof Module["preInit"] == "function") Module["preInit"] = [Module["preInit"]];\n while (Module["preInit"].length > 0) {\n Module["preInit"].pop()();\n }\n }\n run();\n moduleRtn = readyPromise;\n for (const prop of Object.keys(Module)) {\n if (!(prop in moduleArg)) {\n Object.defineProperty(moduleArg, prop, {\n configurable: true,\n get() {\n abort(\n `Access to module property (\'${prop}\') is no longer possible via the module constructor argument; Instead, use the result of the module constructor.`\n );\n }\n });\n }\n }\n return moduleRtn;\n };\n})();\nconst functions = {\n EPDF_GetMetaKeyCount: [["number", "boolean"], "number"],\n EPDF_GetMetaKeyName: [\n ["number", "number", "boolean", "number", "number"],\n "number"\n ],\n EPDF_GetMetaTrapped: [["number"], "number"],\n EPDF_GetPageRotationByIndex: [["number", "number"], "number"],\n EPDF_GetPageSizeByIndexNormalized: [["number", "number", "number"], "boolean"],\n EPDF_HasMetaText: [["number", "string"], "boolean"],\n EPDF_IsEncrypted: [["number"], "boolean"],\n EPDF_IsOwnerUnlocked: [["number"], "boolean"],\n EPDF_LoadPageNormalized: [["number", "number", "number"], "number"],\n EPDF_PNG_EncodeRGBA: [\n ["number", "number", "number", "number", "number", "number"],\n "number"\n ],\n EPDF_RemoveEncryption: [["number"], "boolean"],\n EPDF_RenderAnnotBitmap: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n EPDF_RenderAnnotBitmapUnrotated: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n EPDF_SetEncryption: [["number", "string", "string", "number"], "boolean"],\n EPDF_SetMetaText: [["number", "string", "number"], "boolean"],\n EPDF_SetMetaTrapped: [["number", "number"], "boolean"],\n EPDF_UnlockOwnerPermissions: [["number", "string"], "boolean"],\n EPDFAction_CreateGoTo: [["number", "number"], "number"],\n EPDFAction_CreateGoToNamed: [["number", "string"], "number"],\n EPDFAction_CreateLaunch: [["number", "number"], "number"],\n EPDFAction_CreateRemoteGoToByName: [["number", "number", "number"], "number"],\n EPDFAction_CreateRemoteGoToDest: [["number", "number", "number"], "number"],\n EPDFAction_CreateURI: [["number", "string"], "number"],\n EPDFAnnot_ApplyRedaction: [["number", "number"], "boolean"],\n EPDFAnnot_ClearColor: [["number", "number"], "boolean"],\n EPDFAnnot_Flatten: [["number", "number"], "boolean"],\n EPDFAnnot_GenerateAppearance: [["number"], "boolean"],\n EPDFAnnot_GenerateAppearanceWithBlend: [["number", "number"], "boolean"],\n EPDFAnnot_GetAPMatrix: [["number", "number", "number"], "boolean"],\n EPDFAnnot_GetAvailableAppearanceModes: [["number"], "number"],\n EPDFAnnot_GetBlendMode: [["number"], "number"],\n EPDFAnnot_GetBorderDashPattern: [["number", "number", "number"], "boolean"],\n EPDFAnnot_GetBorderDashPatternCount: [["number"], "number"],\n EPDFAnnot_GetBorderEffect: [["number", "number"], "boolean"],\n EPDFAnnot_GetBorderStyle: [["number", "number"], "number"],\n EPDFAnnot_GetColor: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n EPDFAnnot_GetDefaultAppearance: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n EPDFAnnot_GetExtendedRotation: [["number", "number"], "boolean"],\n EPDFAnnot_GetIcon: [["number"], "number"],\n EPDFAnnot_GetIntent: [["number", "number", "number"], "number"],\n EPDFAnnot_GetLineEndings: [["number", "number", "number"], "boolean"],\n EPDFAnnot_GetOpacity: [["number", "number"], "boolean"],\n EPDFAnnot_GetOverlayText: [["number", "number", "number"], "number"],\n EPDFAnnot_GetOverlayTextRepeat: [["number"], "boolean"],\n EPDFAnnot_GetRect: [["number", "number"], "boolean"],\n EPDFAnnot_GetRectangleDifferences: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n EPDFAnnot_GetReplyType: [["number"], "number"],\n EPDFAnnot_GetRichContent: [["number", "number", "number"], "number"],\n EPDFAnnot_GetRotate: [["number", "number"], "boolean"],\n EPDFAnnot_GetTextAlignment: [["number"], "number"],\n EPDFAnnot_GetUnrotatedRect: [["number", "number"], "boolean"],\n EPDFAnnot_GetVerticalAlignment: [["number"], "number"],\n EPDFAnnot_SetAction: [["number", "number"], "boolean"],\n EPDFAnnot_SetAPMatrix: [["number", "number", "number"], "boolean"],\n EPDFAnnot_SetBorderDashPattern: [["number", "number", "number"], "boolean"],\n EPDFAnnot_SetBorderStyle: [["number", "number", "number"], "boolean"],\n EPDFAnnot_SetColor: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n EPDFAnnot_SetDefaultAppearance: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n EPDFAnnot_SetExtendedRotation: [["number", "number"], "boolean"],\n EPDFAnnot_SetIcon: [["number", "number"], "boolean"],\n EPDFAnnot_SetIntent: [["number", "string"], "boolean"],\n EPDFAnnot_SetLine: [["number", "number", "number"], "boolean"],\n EPDFAnnot_SetLineEndings: [["number", "number", "number"], "boolean"],\n EPDFAnnot_SetLinkedAnnot: [["number", "string", "number"], "boolean"],\n EPDFAnnot_SetOpacity: [["number", "number"], "boolean"],\n EPDFAnnot_SetOverlayText: [["number", "number"], "boolean"],\n EPDFAnnot_SetOverlayTextRepeat: [["number", "boolean"], "boolean"],\n EPDFAnnot_SetReplyType: [["number", "number"], "boolean"],\n EPDFAnnot_SetRotate: [["number", "number"], "boolean"],\n EPDFAnnot_SetTextAlignment: [["number", "number"], "boolean"],\n EPDFAnnot_SetUnrotatedRect: [["number", "number"], "boolean"],\n EPDFAnnot_SetVerticalAlignment: [["number", "number"], "boolean"],\n EPDFAnnot_SetVertices: [["number", "number", "number"], "boolean"],\n EPDFAnnot_UpdateAppearanceToRect: [["number", "number"], "boolean"],\n EPDFAttachment_GetDescription: [["number", "number", "number"], "number"],\n EPDFAttachment_GetIntegerValue: [["number", "string", "number"], "boolean"],\n EPDFAttachment_SetDescription: [["number", "number"], "boolean"],\n EPDFAttachment_SetSubtype: [["number", "string"], "boolean"],\n EPDFBookmark_AppendChild: [["number", "number", "number"], "number"],\n EPDFBookmark_Clear: [["number"], "boolean"],\n EPDFBookmark_ClearTarget: [["number"], "boolean"],\n EPDFBookmark_Create: [["number", "number"], "number"],\n EPDFBookmark_Delete: [["number", "number"], "boolean"],\n EPDFBookmark_InsertAfter: [["number", "number", "number", "number"], "number"],\n EPDFBookmark_SetAction: [["number", "number", "number"], "boolean"],\n EPDFBookmark_SetDest: [["number", "number", "number"], "boolean"],\n EPDFBookmark_SetTitle: [["number", "number"], "boolean"],\n EPDFCatalog_GetLanguage: [["number", "number", "number"], "number"],\n EPDFDest_CreateRemoteView: [\n ["number", "number", "number", "number", "number"],\n "number"\n ],\n EPDFDest_CreateRemoteXYZ: [\n ["number", "number", "boolean", "number", "boolean", "number", "boolean", "number"],\n "number"\n ],\n EPDFDest_CreateView: [["number", "number", "number", "number"], "number"],\n EPDFDest_CreateXYZ: [\n ["number", "boolean", "number", "boolean", "number", "boolean", "number"],\n "number"\n ],\n EPDFNamedDest_Remove: [["number", "string"], "boolean"],\n EPDFNamedDest_SetDest: [["number", "string", "number"], "boolean"],\n EPDFPage_ApplyRedactions: [["number"], "boolean"],\n EPDFPage_CreateAnnot: [["number", "number"], "number"],\n EPDFPage_GetAnnotByName: [["number", "number"], "number"],\n EPDFPage_GetAnnotCountRaw: [["number", "number"], "number"],\n EPDFPage_GetAnnotRaw: [["number", "number", "number"], "number"],\n EPDFPage_RemoveAnnotByName: [["number", "number"], "boolean"],\n EPDFPage_RemoveAnnotRaw: [["number", "number", "number"], "boolean"],\n EPDFText_RedactInQuads: [\n ["number", "number", "number", "boolean", "boolean"],\n "boolean"\n ],\n EPDFText_RedactInRect: [["number", "number", "boolean", "boolean"], "boolean"],\n FORM_CanRedo: [["number", "number"], "boolean"],\n FORM_CanUndo: [["number", "number"], "boolean"],\n FORM_DoDocumentAAction: [["number", "number"], null],\n FORM_DoDocumentJSAction: [["number"], null],\n FORM_DoDocumentOpenAction: [["number"], null],\n FORM_DoPageAAction: [["number", "number", "number"], null],\n FORM_ForceToKillFocus: [["number"], "boolean"],\n FORM_GetFocusedAnnot: [["number", "number", "number"], "boolean"],\n FORM_GetFocusedText: [["number", "number", "number", "number"], "number"],\n FORM_GetSelectedText: [["number", "number", "number", "number"], "number"],\n FORM_IsIndexSelected: [["number", "number", "number"], "boolean"],\n FORM_OnAfterLoadPage: [["number", "number"], null],\n FORM_OnBeforeClosePage: [["number", "number"], null],\n FORM_OnChar: [["number", "number", "number", "number"], "boolean"],\n FORM_OnFocus: [["number", "number", "number", "number", "number"], "boolean"],\n FORM_OnKeyDown: [["number", "number", "number", "number"], "boolean"],\n FORM_OnKeyUp: [["number", "number", "number", "number"], "boolean"],\n FORM_OnLButtonDoubleClick: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FORM_OnLButtonDown: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FORM_OnLButtonUp: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FORM_OnMouseMove: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FORM_OnMouseWheel: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FORM_OnRButtonDown: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FORM_OnRButtonUp: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FORM_Redo: [["number", "number"], "boolean"],\n FORM_ReplaceAndKeepSelection: [["number", "number", "number"], null],\n FORM_ReplaceSelection: [["number", "number", "number"], null],\n FORM_SelectAllText: [["number", "number"], "boolean"],\n FORM_SetFocusedAnnot: [["number", "number"], "boolean"],\n FORM_SetIndexSelected: [["number", "number", "number", "boolean"], "boolean"],\n FORM_Undo: [["number", "number"], "boolean"],\n FPDF_AddInstalledFont: [["number", "number", "number"], null],\n FPDF_CloseDocument: [["number"], null],\n FPDF_ClosePage: [["number"], null],\n FPDF_CloseXObject: [["number"], null],\n FPDF_CopyViewerPreferences: [["number", "number"], "boolean"],\n FPDF_CountNamedDests: [["number"], "number"],\n FPDF_CreateClipPath: [["number", "number", "number", "number"], "number"],\n FPDF_CreateNewDocument: [[], "number"],\n FPDF_DestroyClipPath: [["number"], null],\n FPDF_DestroyLibrary: [[], null],\n FPDF_DeviceToPage: [\n [\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number"\n ],\n "boolean"\n ],\n FPDF_DocumentHasValidCrossReferenceTable: [["number"], "boolean"],\n FPDF_FFLDraw: [\n [\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number"\n ],\n null\n ],\n FPDF_FreeDefaultSystemFontInfo: [["number"], null],\n FPDF_GetDefaultSystemFontInfo: [[], "number"],\n FPDF_GetDefaultTTFMap: [[], "number"],\n FPDF_GetDefaultTTFMapCount: [[], "number"],\n FPDF_GetDefaultTTFMapEntry: [["number"], "number"],\n FPDF_GetDocPermissions: [["number"], "number"],\n FPDF_GetDocUserPermissions: [["number"], "number"],\n FPDF_GetFileIdentifier: [["number", "number", "number", "number"], "number"],\n FPDF_GetFileVersion: [["number", "number"], "boolean"],\n FPDF_GetFormType: [["number"], "number"],\n FPDF_GetLastError: [[], "number"],\n FPDF_GetMetaText: [["number", "string", "number", "number"], "number"],\n FPDF_GetNamedDest: [["number", "number", "number", "number"], "number"],\n FPDF_GetNamedDestByName: [["number", "string"], "number"],\n FPDF_GetPageAAction: [["number", "number"], "number"],\n FPDF_GetPageBoundingBox: [["number", "number"], "boolean"],\n FPDF_GetPageCount: [["number"], "number"],\n FPDF_GetPageHeight: [["number"], "number"],\n FPDF_GetPageHeightF: [["number"], "number"],\n FPDF_GetPageLabel: [["number", "number", "number", "number"], "number"],\n FPDF_GetPageSizeByIndex: [["number", "number", "number", "number"], "number"],\n FPDF_GetPageSizeByIndexF: [["number", "number", "number"], "boolean"],\n FPDF_GetPageWidth: [["number"], "number"],\n FPDF_GetPageWidthF: [["number"], "number"],\n FPDF_GetSecurityHandlerRevision: [["number"], "number"],\n FPDF_GetSignatureCount: [["number"], "number"],\n FPDF_GetSignatureObject: [["number", "number"], "number"],\n FPDF_GetTrailerEnds: [["number", "number", "number"], "number"],\n FPDF_GetXFAPacketContent: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDF_GetXFAPacketCount: [["number"], "number"],\n FPDF_GetXFAPacketName: [["number", "number", "number", "number"], "number"],\n FPDF_ImportNPagesToOne: [\n ["number", "number", "number", "number", "number"],\n "number"\n ],\n FPDF_ImportPages: [["number", "number", "string", "number"], "boolean"],\n FPDF_ImportPagesByIndex: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDF_InitLibrary: [[], null],\n FPDF_InitLibraryWithConfig: [["number"], null],\n FPDF_LoadCustomDocument: [["number", "string"], "number"],\n FPDF_LoadDocument: [["number", "string"], "number"],\n FPDF_LoadMemDocument: [["number", "number", "string"], "number"],\n FPDF_LoadMemDocument64: [["number", "number", "string"], "number"],\n FPDF_LoadPage: [["number", "number"], "number"],\n FPDF_LoadXFA: [["number"], "boolean"],\n FPDF_MovePages: [["number", "number", "number", "number"], "boolean"],\n FPDF_NewFormObjectFromXObject: [["number"], "number"],\n FPDF_NewXObjectFromPage: [["number", "number", "number"], "number"],\n FPDF_PageToDevice: [\n [\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number"\n ],\n "boolean"\n ],\n FPDF_RemoveFormFieldHighlight: [["number"], null],\n FPDF_RenderPage_Close: [["number"], null],\n FPDF_RenderPage_Continue: [["number", "number"], "number"],\n FPDF_RenderPageBitmap: [\n ["number", "number", "number", "number", "number", "number", "number", "number"],\n null\n ],\n FPDF_RenderPageBitmap_Start: [\n [\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number"\n ],\n "number"\n ],\n FPDF_RenderPageBitmapWithColorScheme_Start: [\n [\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number",\n "number"\n ],\n "number"\n ],\n FPDF_RenderPageBitmapWithMatrix: [\n ["number", "number", "number", "number", "number"],\n null\n ],\n FPDF_SaveAsCopy: [["number", "number", "number"], "boolean"],\n FPDF_SaveWithVersion: [["number", "number", "number", "number"], "boolean"],\n FPDF_SetFormFieldHighlightAlpha: [["number", "number"], null],\n FPDF_SetFormFieldHighlightColor: [["number", "number", "number"], null],\n FPDF_SetSandBoxPolicy: [["number", "boolean"], null],\n FPDF_SetSystemFontInfo: [["number"], null],\n FPDF_StructElement_Attr_CountChildren: [["number"], "number"],\n FPDF_StructElement_Attr_GetBlobValue: [\n ["number", "number", "number", "number"],\n "boolean"\n ],\n FPDF_StructElement_Attr_GetBooleanValue: [["number", "number"], "boolean"],\n FPDF_StructElement_Attr_GetChildAtIndex: [["number", "number"], "number"],\n FPDF_StructElement_Attr_GetCount: [["number"], "number"],\n FPDF_StructElement_Attr_GetName: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDF_StructElement_Attr_GetNumberValue: [["number", "number"], "boolean"],\n FPDF_StructElement_Attr_GetStringValue: [\n ["number", "number", "number", "number"],\n "boolean"\n ],\n FPDF_StructElement_Attr_GetType: [["number"], "number"],\n FPDF_StructElement_Attr_GetValue: [["number", "string"], "number"],\n FPDF_StructElement_CountChildren: [["number"], "number"],\n FPDF_StructElement_GetActualText: [["number", "number", "number"], "number"],\n FPDF_StructElement_GetAltText: [["number", "number", "number"], "number"],\n FPDF_StructElement_GetAttributeAtIndex: [["number", "number"], "number"],\n FPDF_StructElement_GetAttributeCount: [["number"], "number"],\n FPDF_StructElement_GetChildAtIndex: [["number", "number"], "number"],\n FPDF_StructElement_GetChildMarkedContentID: [["number", "number"], "number"],\n FPDF_StructElement_GetID: [["number", "number", "number"], "number"],\n FPDF_StructElement_GetLang: [["number", "number", "number"], "number"],\n FPDF_StructElement_GetMarkedContentID: [["number"], "number"],\n FPDF_StructElement_GetMarkedContentIdAtIndex: [["number", "number"], "number"],\n FPDF_StructElement_GetMarkedContentIdCount: [["number"], "number"],\n FPDF_StructElement_GetObjType: [["number", "number", "number"], "number"],\n FPDF_StructElement_GetParent: [["number"], "number"],\n FPDF_StructElement_GetStringAttribute: [\n ["number", "string", "number", "number"],\n "number"\n ],\n FPDF_StructElement_GetTitle: [["number", "number", "number"], "number"],\n FPDF_StructElement_GetType: [["number", "number", "number"], "number"],\n FPDF_StructTree_Close: [["number"], null],\n FPDF_StructTree_CountChildren: [["number"], "number"],\n FPDF_StructTree_GetChildAtIndex: [["number", "number"], "number"],\n FPDF_StructTree_GetForPage: [["number"], "number"],\n FPDF_VIEWERREF_GetDuplex: [["number"], "number"],\n FPDF_VIEWERREF_GetName: [["number", "string", "number", "number"], "number"],\n FPDF_VIEWERREF_GetNumCopies: [["number"], "number"],\n FPDF_VIEWERREF_GetPrintPageRange: [["number"], "number"],\n FPDF_VIEWERREF_GetPrintPageRangeCount: [["number"], "number"],\n FPDF_VIEWERREF_GetPrintPageRangeElement: [["number", "number"], "number"],\n FPDF_VIEWERREF_GetPrintScaling: [["number"], "boolean"],\n FPDFAction_GetDest: [["number", "number"], "number"],\n FPDFAction_GetFilePath: [["number", "number", "number"], "number"],\n FPDFAction_GetType: [["number"], "number"],\n FPDFAction_GetURIPath: [["number", "number", "number", "number"], "number"],\n FPDFAnnot_AddFileAttachment: [["number", "number"], "number"],\n FPDFAnnot_AddInkStroke: [["number", "number", "number"], "number"],\n FPDFAnnot_AppendAttachmentPoints: [["number", "number"], "boolean"],\n FPDFAnnot_AppendObject: [["number", "number"], "boolean"],\n FPDFAnnot_CountAttachmentPoints: [["number"], "number"],\n FPDFAnnot_GetAP: [["number", "number", "number", "number"], "number"],\n FPDFAnnot_GetAttachmentPoints: [["number", "number", "number"], "boolean"],\n FPDFAnnot_GetBorder: [["number", "number", "number", "number"], "boolean"],\n FPDFAnnot_GetColor: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFAnnot_GetFileAttachment: [["number"], "number"],\n FPDFAnnot_GetFlags: [["number"], "number"],\n FPDFAnnot_GetFocusableSubtypes: [["number", "number", "number"], "boolean"],\n FPDFAnnot_GetFocusableSubtypesCount: [["number"], "number"],\n FPDFAnnot_GetFontColor: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFAnnot_GetFontSize: [["number", "number", "number"], "boolean"],\n FPDFAnnot_GetFormAdditionalActionJavaScript: [\n ["number", "number", "number", "number", "number"],\n "number"\n ],\n FPDFAnnot_GetFormControlCount: [["number", "number"], "number"],\n FPDFAnnot_GetFormControlIndex: [["number", "number"], "number"],\n FPDFAnnot_GetFormFieldAlternateName: [\n ["number", "number", "number", "number"],\n "number"\n ],\n FPDFAnnot_GetFormFieldAtPoint: [["number", "number", "number"], "number"],\n FPDFAnnot_GetFormFieldExportValue: [\n ["number", "number", "number", "number"],\n "number"\n ],\n FPDFAnnot_GetFormFieldFlags: [["number", "number"], "number"],\n FPDFAnnot_GetFormFieldName: [\n ["number", "number", "number", "number"],\n "number"\n ],\n FPDFAnnot_GetFormFieldType: [["number", "number"], "number"],\n FPDFAnnot_GetFormFieldValue: [\n ["number", "number", "number", "number"],\n "number"\n ],\n FPDFAnnot_GetInkListCount: [["number"], "number"],\n FPDFAnnot_GetInkListPath: [["number", "number", "number", "number"], "number"],\n FPDFAnnot_GetLine: [["number", "number", "number"], "boolean"],\n FPDFAnnot_GetLink: [["number"], "number"],\n FPDFAnnot_GetLinkedAnnot: [["number", "string"], "number"],\n FPDFAnnot_GetNumberValue: [["number", "string", "number"], "boolean"],\n FPDFAnnot_GetObject: [["number", "number"], "number"],\n FPDFAnnot_GetObjectCount: [["number"], "number"],\n FPDFAnnot_GetOptionCount: [["number", "number"], "number"],\n FPDFAnnot_GetOptionLabel: [\n ["number", "number", "number", "number", "number"],\n "number"\n ],\n FPDFAnnot_GetRect: [["number", "number"], "boolean"],\n FPDFAnnot_GetStringValue: [["number", "string", "number", "number"], "number"],\n FPDFAnnot_GetSubtype: [["number"], "number"],\n FPDFAnnot_GetValueType: [["number", "string"], "number"],\n FPDFAnnot_GetVertices: [["number", "number", "number"], "number"],\n FPDFAnnot_HasAttachmentPoints: [["number"], "boolean"],\n FPDFAnnot_HasKey: [["number", "string"], "boolean"],\n FPDFAnnot_IsChecked: [["number", "number"], "boolean"],\n FPDFAnnot_IsObjectSupportedSubtype: [["number"], "boolean"],\n FPDFAnnot_IsOptionSelected: [["number", "number", "number"], "boolean"],\n FPDFAnnot_IsSupportedSubtype: [["number"], "boolean"],\n FPDFAnnot_RemoveInkList: [["number"], "boolean"],\n FPDFAnnot_RemoveObject: [["number", "number"], "boolean"],\n FPDFAnnot_SetAP: [["number", "number", "number"], "boolean"],\n FPDFAnnot_SetAttachmentPoints: [["number", "number", "number"], "boolean"],\n FPDFAnnot_SetBorder: [["number", "number", "number", "number"], "boolean"],\n FPDFAnnot_SetColor: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFAnnot_SetFlags: [["number", "number"], "boolean"],\n FPDFAnnot_SetFocusableSubtypes: [["number", "number", "number"], "boolean"],\n FPDFAnnot_SetFontColor: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFAnnot_SetFormFieldFlags: [["number", "number", "number"], "boolean"],\n FPDFAnnot_SetRect: [["number", "number"], "boolean"],\n FPDFAnnot_SetStringValue: [["number", "string", "number"], "boolean"],\n FPDFAnnot_SetURI: [["number", "number"], "boolean"],\n FPDFAnnot_UpdateObject: [["number", "number"], "boolean"],\n FPDFAttachment_GetFile: [["number", "number", "number", "number"], "boolean"],\n FPDFAttachment_GetName: [["number", "number", "number"], "number"],\n FPDFAttachment_GetStringValue: [\n ["number", "string", "number", "number"],\n "number"\n ],\n FPDFAttachment_GetSubtype: [["number", "number", "number"], "number"],\n FPDFAttachment_GetValueType: [["number", "string"], "number"],\n FPDFAttachment_HasKey: [["number", "string"], "boolean"],\n FPDFAttachment_SetFile: [["number", "number", "number", "number"], "boolean"],\n FPDFAttachment_SetStringValue: [["number", "string", "number"], "boolean"],\n FPDFAvail_Create: [["number", "number"], "number"],\n FPDFAvail_Destroy: [["number"], null],\n FPDFAvail_GetDocument: [["number", "string"], "number"],\n FPDFAvail_GetFirstPageNum: [["number"], "number"],\n FPDFAvail_IsDocAvail: [["number", "number"], "number"],\n FPDFAvail_IsFormAvail: [["number", "number"], "number"],\n FPDFAvail_IsLinearized: [["number"], "number"],\n FPDFAvail_IsPageAvail: [["number", "number", "number"], "number"],\n FPDFBitmap_Create: [["number", "number", "number"], "number"],\n FPDFBitmap_CreateEx: [\n ["number", "number", "number", "number", "number"],\n "number"\n ],\n FPDFBitmap_Destroy: [["number"], null],\n FPDFBitmap_FillRect: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFBitmap_GetBuffer: [["number"], "number"],\n FPDFBitmap_GetFormat: [["number"], "number"],\n FPDFBitmap_GetHeight: [["number"], "number"],\n FPDFBitmap_GetStride: [["number"], "number"],\n FPDFBitmap_GetWidth: [["number"], "number"],\n FPDFBookmark_Find: [["number", "number"], "number"],\n FPDFBookmark_GetAction: [["number"], "number"],\n FPDFBookmark_GetCount: [["number"], "number"],\n FPDFBookmark_GetDest: [["number", "number"], "number"],\n FPDFBookmark_GetFirstChild: [["number", "number"], "number"],\n FPDFBookmark_GetNextSibling: [["number", "number"], "number"],\n FPDFBookmark_GetTitle: [["number", "number", "number"], "number"],\n FPDFCatalog_GetLanguage: [["number", "number", "number"], "number"],\n FPDFCatalog_IsTagged: [["number"], "boolean"],\n FPDFCatalog_SetLanguage: [["number", "number"], "boolean"],\n FPDFClipPath_CountPaths: [["number"], "number"],\n FPDFClipPath_CountPathSegments: [["number", "number"], "number"],\n FPDFClipPath_GetPathSegment: [["number", "number", "number"], "number"],\n FPDFDest_GetDestPageIndex: [["number", "number"], "number"],\n FPDFDest_GetLocationInPage: [\n ["number", "number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFDest_GetView: [["number", "number", "number"], "number"],\n FPDFDoc_AddAttachment: [["number", "number"], "number"],\n FPDFDoc_CloseJavaScriptAction: [["number"], null],\n FPDFDoc_DeleteAttachment: [["number", "number"], "boolean"],\n FPDFDOC_ExitFormFillEnvironment: [["number"], null],\n FPDFDoc_GetAttachment: [["number", "number"], "number"],\n FPDFDoc_GetAttachmentCount: [["number"], "number"],\n FPDFDoc_GetJavaScriptAction: [["number", "number"], "number"],\n FPDFDoc_GetJavaScriptActionCount: [["number"], "number"],\n FPDFDoc_GetPageMode: [["number"], "number"],\n FPDFDOC_InitFormFillEnvironment: [["number", "number"], "number"],\n FPDFFont_Close: [["number"], null],\n FPDFFont_GetAscent: [["number", "number", "number"], "boolean"],\n FPDFFont_GetBaseFontName: [["number", "number", "number"], "number"],\n FPDFFont_GetDescent: [["number", "number", "number"], "boolean"],\n FPDFFont_GetFamilyName: [["number", "number", "number"], "number"],\n FPDFFont_GetFlags: [["number"], "number"],\n FPDFFont_GetFontData: [["number", "number", "number", "number"], "boolean"],\n FPDFFont_GetGlyphPath: [["number", "number", "number"], "number"],\n FPDFFont_GetGlyphWidth: [["number", "number", "number", "number"], "boolean"],\n FPDFFont_GetIsEmbedded: [["number"], "number"],\n FPDFFont_GetItalicAngle: [["number", "number"], "boolean"],\n FPDFFont_GetWeight: [["number"], "number"],\n FPDFFormObj_CountObjects: [["number"], "number"],\n FPDFFormObj_GetObject: [["number", "number"], "number"],\n FPDFFormObj_RemoveObject: [["number", "number"], "boolean"],\n FPDFGlyphPath_CountGlyphSegments: [["number"], "number"],\n FPDFGlyphPath_GetGlyphPathSegment: [["number", "number"], "number"],\n FPDFImageObj_GetBitmap: [["number"], "number"],\n FPDFImageObj_GetIccProfileDataDecoded: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFImageObj_GetImageDataDecoded: [["number", "number", "number"], "number"],\n FPDFImageObj_GetImageDataRaw: [["number", "number", "number"], "number"],\n FPDFImageObj_GetImageFilter: [\n ["number", "number", "number", "number"],\n "number"\n ],\n FPDFImageObj_GetImageFilterCount: [["number"], "number"],\n FPDFImageObj_GetImageMetadata: [["number", "number", "number"], "boolean"],\n FPDFImageObj_GetImagePixelSize: [["number", "number", "number"], "boolean"],\n FPDFImageObj_GetRenderedBitmap: [["number", "number", "number"], "number"],\n FPDFImageObj_LoadJpegFile: [\n ["number", "number", "number", "number"],\n "boolean"\n ],\n FPDFImageObj_LoadJpegFileInline: [\n ["number", "number", "number", "number"],\n "boolean"\n ],\n FPDFImageObj_SetBitmap: [["number", "number", "number", "number"], "boolean"],\n FPDFImageObj_SetMatrix: [\n ["number", "number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFJavaScriptAction_GetName: [["number", "number", "number"], "number"],\n FPDFJavaScriptAction_GetScript: [["number", "number", "number"], "number"],\n FPDFLink_CloseWebLinks: [["number"], null],\n FPDFLink_CountQuadPoints: [["number"], "number"],\n FPDFLink_CountRects: [["number", "number"], "number"],\n FPDFLink_CountWebLinks: [["number"], "number"],\n FPDFLink_Enumerate: [["number", "number", "number"], "boolean"],\n FPDFLink_GetAction: [["number"], "number"],\n FPDFLink_GetAnnot: [["number", "number"], "number"],\n FPDFLink_GetAnnotRect: [["number", "number"], "boolean"],\n FPDFLink_GetDest: [["number", "number"], "number"],\n FPDFLink_GetLinkAtPoint: [["number", "number", "number"], "number"],\n FPDFLink_GetLinkZOrderAtPoint: [["number", "number", "number"], "number"],\n FPDFLink_GetQuadPoints: [["number", "number", "number"], "boolean"],\n FPDFLink_GetRect: [\n ["number", "number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFLink_GetTextRange: [["number", "number", "number", "number"], "boolean"],\n FPDFLink_GetURL: [["number", "number", "number", "number"], "number"],\n FPDFLink_LoadWebLinks: [["number"], "number"],\n FPDFPage_CloseAnnot: [["number"], null],\n FPDFPage_CountObjects: [["number"], "number"],\n FPDFPage_CreateAnnot: [["number", "number"], "number"],\n FPDFPage_Delete: [["number", "number"], null],\n FPDFPage_Flatten: [["number", "number"], "number"],\n FPDFPage_FormFieldZOrderAtPoint: [\n ["number", "number", "number", "number"],\n "number"\n ],\n FPDFPage_GenerateContent: [["number"], "boolean"],\n FPDFPage_GetAnnot: [["number", "number"], "number"],\n FPDFPage_GetAnnotCount: [["number"], "number"],\n FPDFPage_GetAnnotIndex: [["number", "number"], "number"],\n FPDFPage_GetArtBox: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPage_GetBleedBox: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPage_GetCropBox: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPage_GetDecodedThumbnailData: [["number", "number", "number"], "number"],\n FPDFPage_GetMediaBox: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPage_GetObject: [["number", "number"], "number"],\n FPDFPage_GetRawThumbnailData: [["number", "number", "number"], "number"],\n FPDFPage_GetRotation: [["number"], "number"],\n FPDFPage_GetThumbnailAsBitmap: [["number"], "number"],\n FPDFPage_GetTrimBox: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPage_HasFormFieldAtPoint: [\n ["number", "number", "number", "number"],\n "number"\n ],\n FPDFPage_HasTransparency: [["number"], "boolean"],\n FPDFPage_InsertClipPath: [["number", "number"], null],\n FPDFPage_InsertObject: [["number", "number"], null],\n FPDFPage_InsertObjectAtIndex: [["number", "number", "number"], "boolean"],\n FPDFPage_New: [["number", "number", "number", "number"], "number"],\n FPDFPage_RemoveAnnot: [["number", "number"], "boolean"],\n FPDFPage_RemoveObject: [["number", "number"], "boolean"],\n FPDFPage_SetArtBox: [["number", "number", "number", "number", "number"], null],\n FPDFPage_SetBleedBox: [\n ["number", "number", "number", "number", "number"],\n null\n ],\n FPDFPage_SetCropBox: [["number", "number", "number", "number", "number"], null],\n FPDFPage_SetMediaBox: [\n ["number", "number", "number", "number", "number"],\n null\n ],\n FPDFPage_SetRotation: [["number", "number"], null],\n FPDFPage_SetTrimBox: [["number", "number", "number", "number", "number"], null],\n FPDFPage_TransformAnnots: [\n ["number", "number", "number", "number", "number", "number", "number"],\n null\n ],\n FPDFPage_TransFormWithClip: [["number", "number", "number"], "boolean"],\n FPDFPageObj_AddMark: [["number", "string"], "number"],\n FPDFPageObj_CountMarks: [["number"], "number"],\n FPDFPageObj_CreateNewPath: [["number", "number"], "number"],\n FPDFPageObj_CreateNewRect: [["number", "number", "number", "number"], "number"],\n FPDFPageObj_CreateTextObj: [["number", "number", "number"], "number"],\n FPDFPageObj_Destroy: [["number"], null],\n FPDFPageObj_GetBounds: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPageObj_GetClipPath: [["number"], "number"],\n FPDFPageObj_GetDashArray: [["number", "number", "number"], "boolean"],\n FPDFPageObj_GetDashCount: [["number"], "number"],\n FPDFPageObj_GetDashPhase: [["number", "number"], "boolean"],\n FPDFPageObj_GetFillColor: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPageObj_GetIsActive: [["number", "number"], "boolean"],\n FPDFPageObj_GetLineCap: [["number"], "number"],\n FPDFPageObj_GetLineJoin: [["number"], "number"],\n FPDFPageObj_GetMark: [["number", "number"], "number"],\n FPDFPageObj_GetMarkedContentID: [["number"], "number"],\n FPDFPageObj_GetMatrix: [["number", "number"], "boolean"],\n FPDFPageObj_GetRotatedBounds: [["number", "number"], "boolean"],\n FPDFPageObj_GetStrokeColor: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPageObj_GetStrokeWidth: [["number", "number"], "boolean"],\n FPDFPageObj_GetType: [["number"], "number"],\n FPDFPageObj_HasTransparency: [["number"], "boolean"],\n FPDFPageObj_NewImageObj: [["number"], "number"],\n FPDFPageObj_NewTextObj: [["number", "string", "number"], "number"],\n FPDFPageObj_RemoveMark: [["number", "number"], "boolean"],\n FPDFPageObj_SetBlendMode: [["number", "string"], null],\n FPDFPageObj_SetDashArray: [["number", "number", "number", "number"], "boolean"],\n FPDFPageObj_SetDashPhase: [["number", "number"], "boolean"],\n FPDFPageObj_SetFillColor: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPageObj_SetIsActive: [["number", "boolean"], "boolean"],\n FPDFPageObj_SetLineCap: [["number", "number"], "boolean"],\n FPDFPageObj_SetLineJoin: [["number", "number"], "boolean"],\n FPDFPageObj_SetMatrix: [["number", "number"], "boolean"],\n FPDFPageObj_SetStrokeColor: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPageObj_SetStrokeWidth: [["number", "number"], "boolean"],\n FPDFPageObj_Transform: [\n ["number", "number", "number", "number", "number", "number", "number"],\n null\n ],\n FPDFPageObj_TransformClipPath: [\n ["number", "number", "number", "number", "number", "number", "number"],\n null\n ],\n FPDFPageObj_TransformF: [["number", "number"], "boolean"],\n FPDFPageObjMark_CountParams: [["number"], "number"],\n FPDFPageObjMark_GetName: [["number", "number", "number", "number"], "boolean"],\n FPDFPageObjMark_GetParamBlobValue: [\n ["number", "string", "number", "number", "number"],\n "boolean"\n ],\n FPDFPageObjMark_GetParamFloatValue: [["number", "string", "number"], "boolean"],\n FPDFPageObjMark_GetParamIntValue: [["number", "string", "number"], "boolean"],\n FPDFPageObjMark_GetParamKey: [\n ["number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPageObjMark_GetParamStringValue: [\n ["number", "string", "number", "number", "number"],\n "boolean"\n ],\n FPDFPageObjMark_GetParamValueType: [["number", "string"], "number"],\n FPDFPageObjMark_RemoveParam: [["number", "number", "string"], "boolean"],\n FPDFPageObjMark_SetBlobParam: [\n ["number", "number", "number", "string", "number", "number"],\n "boolean"\n ],\n FPDFPageObjMark_SetFloatParam: [\n ["number", "number", "number", "string", "number"],\n "boolean"\n ],\n FPDFPageObjMark_SetIntParam: [\n ["number", "number", "number", "string", "number"],\n "boolean"\n ],\n FPDFPageObjMark_SetStringParam: [\n ["number", "number", "number", "string", "string"],\n "boolean"\n ],\n FPDFPath_BezierTo: [\n ["number", "number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFPath_Close: [["number"], "boolean"],\n FPDFPath_CountSegments: [["number"], "number"],\n FPDFPath_GetDrawMode: [["number", "number", "number"], "boolean"],\n FPDFPath_GetPathSegment: [["number", "number"], "number"],\n FPDFPath_LineTo: [["number", "number", "number"], "boolean"],\n FPDFPath_MoveTo: [["number", "number", "number"], "boolean"],\n FPDFPath_SetDrawMode: [["number", "number", "boolean"], "boolean"],\n FPDFPathSegment_GetClose: [["number"], "boolean"],\n FPDFPathSegment_GetPoint: [["number", "number", "number"], "boolean"],\n FPDFPathSegment_GetType: [["number"], "number"],\n FPDFSignatureObj_GetByteRange: [["number", "number", "number"], "number"],\n FPDFSignatureObj_GetContents: [["number", "number", "number"], "number"],\n FPDFSignatureObj_GetDocMDPPermission: [["number"], "number"],\n FPDFSignatureObj_GetReason: [["number", "number", "number"], "number"],\n FPDFSignatureObj_GetSubFilter: [["number", "number", "number"], "number"],\n FPDFSignatureObj_GetTime: [["number", "number", "number"], "number"],\n FPDFText_ClosePage: [["number"], null],\n FPDFText_CountChars: [["number"], "number"],\n FPDFText_CountRects: [["number", "number", "number"], "number"],\n FPDFText_FindClose: [["number"], null],\n FPDFText_FindNext: [["number"], "boolean"],\n FPDFText_FindPrev: [["number"], "boolean"],\n FPDFText_FindStart: [["number", "number", "number", "number"], "number"],\n FPDFText_GetBoundedText: [\n ["number", "number", "number", "number", "number", "number", "number"],\n "number"\n ],\n FPDFText_GetCharAngle: [["number", "number"], "number"],\n FPDFText_GetCharBox: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFText_GetCharIndexAtPos: [\n ["number", "number", "number", "number", "number"],\n "number"\n ],\n FPDFText_GetCharIndexFromTextIndex: [["number", "number"], "number"],\n FPDFText_GetCharOrigin: [["number", "number", "number", "number"], "boolean"],\n FPDFText_GetFillColor: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFText_GetFontInfo: [\n ["number", "number", "number", "number", "number"],\n "number"\n ],\n FPDFText_GetFontSize: [["number", "number"], "number"],\n FPDFText_GetFontWeight: [["number", "number"], "number"],\n FPDFText_GetLooseCharBox: [["number", "number", "number"], "boolean"],\n FPDFText_GetMatrix: [["number", "number", "number"], "boolean"],\n FPDFText_GetRect: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFText_GetSchCount: [["number"], "number"],\n FPDFText_GetSchResultIndex: [["number"], "number"],\n FPDFText_GetStrokeColor: [\n ["number", "number", "number", "number", "number", "number"],\n "boolean"\n ],\n FPDFText_GetText: [["number", "number", "number", "number"], "number"],\n FPDFText_GetTextIndexFromCharIndex: [["number", "number"], "number"],\n FPDFText_GetTextObject: [["number", "number"], "number"],\n FPDFText_GetUnicode: [["number", "number"], "number"],\n FPDFText_HasUnicodeMapError: [["number", "number"], "number"],\n FPDFText_IsGenerated: [["number", "number"], "number"],\n FPDFText_IsHyphen: [["number", "number"], "number"],\n FPDFText_LoadCidType2Font: [\n ["number", "number", "number", "string", "number", "number"],\n "number"\n ],\n FPDFText_LoadFont: [\n ["number", "number", "number", "number", "boolean"],\n "number"\n ],\n FPDFText_LoadPage: [["number"], "number"],\n FPDFText_LoadStandardFont: [["number", "string"], "number"],\n FPDFText_SetCharcodes: [["number", "number", "number"], "boolean"],\n FPDFText_SetText: [["number", "number"], "boolean"],\n FPDFTextObj_GetFont: [["number"], "number"],\n FPDFTextObj_GetFontSize: [["number", "number"], "boolean"],\n FPDFTextObj_GetRenderedBitmap: [\n ["number", "number", "number", "number"],\n "number"\n ],\n FPDFTextObj_GetText: [["number", "number", "number", "number"], "number"],\n FPDFTextObj_GetTextRenderMode: [["number"], "number"],\n FPDFTextObj_SetTextRenderMode: [["number", "number"], "boolean"],\n PDFiumExt_CloseFileWriter: [["number"], null],\n PDFiumExt_CloseFormFillInfo: [["number"], null],\n PDFiumExt_ExitFormFillEnvironment: [["number"], null],\n PDFiumExt_GetFileWriterData: [["number", "number", "number"], "number"],\n PDFiumExt_GetFileWriterSize: [["number"], "number"],\n PDFiumExt_Init: [[], null],\n PDFiumExt_InitFormFillEnvironment: [["number", "number"], "number"],\n PDFiumExt_OpenFileWriter: [[], "number"],\n PDFiumExt_OpenFormFillInfo: [[], "number"],\n PDFiumExt_SaveAsCopy: [["number", "number"], "number"]\n};\nasync function createWrappedModule(pdfium) {\n const module = {\n pdfium\n };\n for (const key in functions) {\n const ident = key;\n const args = functions[ident][0];\n const ret = functions[ident][1];\n module[ident] = pdfium.cwrap(key, ret, args);\n }\n return module;\n}\nasync function init(moduleOverrides) {\n const pdfium = await createPdfium(moduleOverrides);\n return createWrappedModule(pdfium);\n}\nfunction readString(wasmModule, readChars, parseChars, defaultLength = 100) {\n let buffer = wasmModule.wasmExports.malloc(defaultLength);\n for (let i = 0; i < defaultLength; i++) {\n wasmModule.HEAP8[buffer + i] = 0;\n }\n const actualLength = readChars(buffer, defaultLength);\n let str;\n if (actualLength > defaultLength) {\n wasmModule.wasmExports.free(buffer);\n buffer = wasmModule.wasmExports.malloc(actualLength);\n for (let i = 0; i < actualLength; i++) {\n wasmModule.HEAP8[buffer + i] = 0;\n }\n readChars(buffer, actualLength);\n str = parseChars(buffer);\n } else {\n str = parseChars(buffer);\n }\n wasmModule.wasmExports.free(buffer);\n return str;\n}\nfunction readArrayBuffer(wasmModule, readChars) {\n const bufferSize = readChars(0, 0);\n const bufferPtr = wasmModule.wasmExports.malloc(bufferSize);\n readChars(bufferPtr, bufferSize);\n const arrayBuffer = new ArrayBuffer(bufferSize);\n const view = new DataView(arrayBuffer);\n for (let i = 0; i < bufferSize; i++) {\n view.setInt8(i, wasmModule.getValue(bufferPtr + i, "i8"));\n }\n wasmModule.wasmExports.free(bufferPtr);\n return arrayBuffer;\n}\nconst RESERVED_INFO_KEYS = /* @__PURE__ */ new Set([\n "Title",\n "Author",\n "Subject",\n "Keywords",\n "Producer",\n "Creator",\n "CreationDate",\n "ModDate",\n "Trapped"\n]);\nfunction isValidCustomKey(key) {\n if (!key || key.length > 127) return false;\n if (RESERVED_INFO_KEYS.has(key)) return false;\n if (key[0] === "/") return false;\n for (let i = 0; i < key.length; i++) {\n const c = key.charCodeAt(i);\n if (c < 32 || c > 126) return false;\n }\n return true;\n}\nfunction computeFormDrawParams(matrix, rect, pageSize, rotation) {\n const rectLeft = rect.origin.x;\n const rectBottom = rect.origin.y;\n const rectRight = rectLeft + rect.size.width;\n const rectTop = rectBottom + rect.size.height;\n const pageWidth = pageSize.width;\n const pageHeight = pageSize.height;\n const scaleX = Math.hypot(matrix.a, matrix.b);\n const scaleY = Math.hypot(matrix.c, matrix.d);\n const swap2 = (rotation & 1) === 1;\n const formsWidth = swap2 ? Math.max(1, Math.round(pageHeight * scaleX)) : Math.max(1, Math.round(pageWidth * scaleX));\n const formsHeight = swap2 ? Math.max(1, Math.round(pageWidth * scaleY)) : Math.max(1, Math.round(pageHeight * scaleY));\n let startX;\n let startY;\n switch (rotation) {\n case Rotation.Degree0:\n startX = -Math.round(rectLeft * scaleX);\n startY = -Math.round(rectBottom * scaleY);\n break;\n case Rotation.Degree90:\n startX = Math.round((rectTop - pageHeight) * scaleX);\n startY = -Math.round(rectLeft * scaleY);\n break;\n case Rotation.Degree180:\n startX = Math.round((rectRight - pageWidth) * scaleX);\n startY = Math.round((rectTop - pageHeight) * scaleY);\n break;\n case Rotation.Degree270:\n startX = -Math.round(rectBottom * scaleX);\n startY = Math.round((rectRight - pageWidth) * scaleY);\n break;\n default:\n startX = -Math.round(rectLeft * scaleX);\n startY = -Math.round(rectBottom * scaleY);\n break;\n }\n return { startX, startY, formsWidth, formsHeight, scaleX, scaleY };\n}\nconst WasmPointer = (ptr) => ptr;\nconst DEFAULT_CONFIG = {\n pageTtl: 5e3,\n // 5 seconds\n maxPagesPerDocument: 10,\n normalizeRotation: false\n};\nclass PdfCache {\n constructor(pdfium, memoryManager, config = {}) {\n this.pdfium = pdfium;\n this.memoryManager = memoryManager;\n this.docs = /* @__PURE__ */ new Map();\n this.config = { ...DEFAULT_CONFIG, ...config };\n }\n /** Open (or re-use) a document */\n setDocument(id, filePtr, docPtr, normalizeRotation = false) {\n let ctx = this.docs.get(id);\n if (!ctx) {\n const docConfig = { ...this.config, normalizeRotation };\n ctx = new DocumentContext(filePtr, docPtr, this.pdfium, this.memoryManager, docConfig);\n this.docs.set(id, ctx);\n }\n }\n /** Retrieve the DocumentContext for a given PdfDocumentObject */\n getContext(docId) {\n return this.docs.get(docId);\n }\n /** Close & fully release a document and all its pages */\n closeDocument(docId) {\n const ctx = this.docs.get(docId);\n if (!ctx) return false;\n ctx.dispose();\n this.docs.delete(docId);\n return true;\n }\n /** Close all documents */\n closeAllDocuments() {\n for (const ctx of this.docs.values()) {\n ctx.dispose();\n }\n this.docs.clear();\n }\n /** Update cache configuration for all existing documents */\n updateConfig(newConfig) {\n Object.assign(this.config, newConfig);\n for (const ctx of this.docs.values()) {\n ctx.updateConfig(this.config);\n }\n }\n /** Get current cache statistics */\n getCacheStats() {\n const pagesByDocument = {};\n let totalPages = 0;\n for (const [docId, ctx] of this.docs.entries()) {\n const pageCount = ctx.getCacheSize();\n pagesByDocument[docId] = pageCount;\n totalPages += pageCount;\n }\n return {\n documents: this.docs.size,\n totalPages,\n pagesByDocument\n };\n }\n}\nclass DocumentContext {\n constructor(filePtr, docPtr, pdfium, memoryManager, config) {\n this.filePtr = filePtr;\n this.docPtr = docPtr;\n this.memoryManager = memoryManager;\n this.normalizeRotation = config.normalizeRotation;\n this.pageCache = new PageCache(pdfium, docPtr, config);\n }\n /** Main accessor for pages */\n acquirePage(pageIdx) {\n return this.pageCache.acquire(pageIdx);\n }\n /** Scoped accessor for one-off / bulk operations */\n borrowPage(pageIdx, fn) {\n return this.pageCache.borrowPage(pageIdx, fn);\n }\n /** Update cache configuration */\n updateConfig(config) {\n this.pageCache.updateConfig(config);\n }\n /** Get number of pages currently in cache */\n getCacheSize() {\n return this.pageCache.size();\n }\n /** Tear down all pages + this document */\n dispose() {\n this.pageCache.forceReleaseAll();\n this.pageCache.pdf.FPDF_CloseDocument(this.docPtr);\n this.memoryManager.free(WasmPointer(this.filePtr));\n }\n}\nclass PageCache {\n constructor(pdf, docPtr, config) {\n this.pdf = pdf;\n this.docPtr = docPtr;\n this.cache = /* @__PURE__ */ new Map();\n this.accessOrder = [];\n this.config = config;\n }\n acquire(pageIdx) {\n let ctx = this.cache.get(pageIdx);\n if (!ctx) {\n this.evictIfNeeded();\n let pagePtr;\n if (this.config.normalizeRotation) {\n pagePtr = this.pdf.EPDF_LoadPageNormalized(this.docPtr, pageIdx, 0);\n } else {\n pagePtr = this.pdf.FPDF_LoadPage(this.docPtr, pageIdx);\n }\n ctx = new PageContext(this.pdf, this.docPtr, pageIdx, pagePtr, this.config.pageTtl, () => {\n this.cache.delete(pageIdx);\n this.removeFromAccessOrder(pageIdx);\n });\n this.cache.set(pageIdx, ctx);\n }\n this.updateAccessOrder(pageIdx);\n ctx.clearExpiryTimer();\n ctx.bumpRefCount();\n return ctx;\n }\n /** Helper: run a function "scoped" to a page.\n * – if the page was already cached → .release() (keeps TTL logic)\n * – if the page was loaded just now → .disposeImmediate() (free right away)\n */\n borrowPage(pageIdx, fn) {\n const existed = this.cache.has(pageIdx);\n const ctx = this.acquire(pageIdx);\n try {\n return fn(ctx);\n } finally {\n existed ? ctx.release() : ctx.disposeImmediate();\n }\n }\n forceReleaseAll() {\n for (const ctx of this.cache.values()) {\n ctx.disposeImmediate();\n }\n this.cache.clear();\n this.accessOrder.length = 0;\n }\n /** Update cache configuration */\n updateConfig(config) {\n this.config = config;\n for (const ctx of this.cache.values()) {\n ctx.updateTtl(config.pageTtl);\n }\n this.evictIfNeeded();\n }\n /** Get current cache size */\n size() {\n return this.cache.size;\n }\n /** Evict least recently used pages if cache exceeds max size */\n evictIfNeeded() {\n while (this.cache.size >= this.config.maxPagesPerDocument) {\n const lruPageIdx = this.accessOrder[0];\n if (lruPageIdx !== void 0) {\n const ctx = this.cache.get(lruPageIdx);\n if (ctx) {\n if (ctx.getRefCount() === 0) {\n ctx.disposeImmediate();\n } else {\n break;\n }\n } else {\n this.removeFromAccessOrder(lruPageIdx);\n }\n } else {\n break;\n }\n }\n }\n /** Update the access order for LRU tracking */\n updateAccessOrder(pageIdx) {\n this.removeFromAccessOrder(pageIdx);\n this.accessOrder.push(pageIdx);\n }\n /** Remove a page from the access order array */\n removeFromAccessOrder(pageIdx) {\n const index = this.accessOrder.indexOf(pageIdx);\n if (index > -1) {\n this.accessOrder.splice(index, 1);\n }\n }\n}\nclass PageContext {\n constructor(pdf, docPtr, pageIdx, pagePtr, ttl, onFinalDispose) {\n this.pdf = pdf;\n this.docPtr = docPtr;\n this.pageIdx = pageIdx;\n this.pagePtr = pagePtr;\n this.onFinalDispose = onFinalDispose;\n this.refCount = 0;\n this.disposed = false;\n this.ttl = ttl;\n }\n /** Called by PageCache.acquire() */\n bumpRefCount() {\n if (this.disposed) throw new Error("Context already disposed");\n this.refCount++;\n }\n /** Get current reference count */\n getRefCount() {\n return this.refCount;\n }\n /** Called by PageCache.acquire() */\n clearExpiryTimer() {\n if (this.expiryTimer) {\n clearTimeout(this.expiryTimer);\n this.expiryTimer = void 0;\n }\n }\n /** Update TTL configuration */\n updateTtl(newTtl) {\n this.ttl = newTtl;\n if (this.expiryTimer && this.refCount === 0) {\n this.clearExpiryTimer();\n this.expiryTimer = setTimeout(() => this.disposeImmediate(), this.ttl);\n }\n }\n /** Called by PageCache.release() internally */\n release() {\n if (this.disposed) return;\n this.refCount--;\n if (this.refCount === 0) {\n this.expiryTimer = setTimeout(() => this.disposeImmediate(), this.ttl);\n }\n }\n /** Tear down _all_ sub-pointers & the page. */\n disposeImmediate() {\n if (this.disposed) return;\n this.disposed = true;\n this.clearExpiryTimer();\n if (this.textPagePtr !== void 0) {\n this.pdf.FPDFText_ClosePage(this.textPagePtr);\n }\n if (this.formHandle !== void 0) {\n this.pdf.FORM_OnBeforeClosePage(this.pagePtr, this.formHandle);\n this.pdf.PDFiumExt_ExitFormFillEnvironment(this.formHandle);\n }\n if (this.formInfoPtr !== void 0) {\n this.pdf.PDFiumExt_CloseFormFillInfo(this.formInfoPtr);\n }\n this.pdf.FPDF_ClosePage(this.pagePtr);\n this.onFinalDispose();\n }\n // ── public helpers ──\n /** Always safe: opens (once) and returns the text-page ptr. */\n getTextPage() {\n this.ensureAlive();\n if (this.textPagePtr === void 0) {\n this.textPagePtr = this.pdf.FPDFText_LoadPage(this.pagePtr);\n }\n return this.textPagePtr;\n }\n /** Always safe: opens (once) and returns the form-fill handle. */\n getFormHandle() {\n this.ensureAlive();\n if (this.formHandle === void 0) {\n this.formInfoPtr = this.pdf.PDFiumExt_OpenFormFillInfo();\n this.formHandle = this.pdf.PDFiumExt_InitFormFillEnvironment(this.docPtr, this.formInfoPtr);\n this.pdf.FORM_OnAfterLoadPage(this.pagePtr, this.formHandle);\n }\n return this.formHandle;\n }\n /**\n * Safely execute `fn` with an annotation pointer.\n * Pointer is ALWAYS closed afterwards.\n */\n withAnnotation(annotIdx, fn) {\n this.ensureAlive();\n const annotPtr = this.pdf.FPDFPage_GetAnnot(this.pagePtr, annotIdx);\n try {\n return fn(annotPtr);\n } finally {\n this.pdf.FPDFPage_CloseAnnot(annotPtr);\n }\n }\n ensureAlive() {\n if (this.disposed) throw new Error("PageContext already disposed");\n }\n}\nconst MEMORY_LIMITS = {\n /** Maximum total memory that can be allocated (2GB) */\n MAX_TOTAL_MEMORY: 2 * 1024 * 1024 * 1024\n};\nconst LIMITS = {\n MEMORY: MEMORY_LIMITS\n};\nconst LOG_SOURCE$3 = "PDFiumEngine";\nconst LOG_CATEGORY$3 = "MemoryManager";\nclass MemoryManager {\n constructor(pdfiumModule, logger) {\n this.pdfiumModule = pdfiumModule;\n this.logger = logger;\n this.allocations = /* @__PURE__ */ new Map();\n this.totalAllocated = 0;\n }\n /**\n * Allocate memory with tracking and validation\n */\n malloc(size) {\n if (this.totalAllocated + size > LIMITS.MEMORY.MAX_TOTAL_MEMORY) {\n throw new Error(\n `Total memory usage would exceed limit: ${this.totalAllocated + size} > ${LIMITS.MEMORY.MAX_TOTAL_MEMORY}`\n );\n }\n const ptr = this.pdfiumModule.pdfium.wasmExports.malloc(size);\n if (!ptr) {\n throw new Error(`Failed to allocate ${size} bytes`);\n }\n const allocation = {\n ptr: WasmPointer(ptr),\n size,\n timestamp: Date.now(),\n stack: this.logger.isEnabled("debug") ? new Error().stack : void 0\n };\n this.allocations.set(ptr, allocation);\n this.totalAllocated += size;\n return WasmPointer(ptr);\n }\n /**\n * Free memory with validation\n */\n free(ptr) {\n const allocation = this.allocations.get(ptr);\n if (!allocation) {\n this.logger.warn(LOG_SOURCE$3, LOG_CATEGORY$3, `Freeing untracked pointer: ${ptr}`);\n } else {\n this.totalAllocated -= allocation.size;\n this.allocations.delete(ptr);\n }\n this.pdfiumModule.pdfium.wasmExports.free(ptr);\n }\n /**\n * Get memory statistics\n */\n getStats() {\n return {\n totalAllocated: this.totalAllocated,\n allocationCount: this.allocations.size,\n allocations: this.logger.isEnabled("debug") ? Array.from(this.allocations.values()) : []\n };\n }\n /**\n * Check for memory leaks\n */\n checkLeaks() {\n if (this.allocations.size > 0) {\n this.logger.warn(\n LOG_SOURCE$3,\n LOG_CATEGORY$3,\n `Potential memory leak: ${this.allocations.size} unfreed allocations`\n );\n for (const [ptr, alloc] of this.allocations) {\n this.logger.warn(LOG_SOURCE$3, LOG_CATEGORY$3, ` - ${ptr}: ${alloc.size} bytes`, alloc.stack);\n }\n }\n }\n}\nconst SYSFONTINFO_SIZE = 36;\nconst OFFSET_VERSION = 0;\nconst OFFSET_RELEASE = 4;\nconst OFFSET_ENUMFONTS = 8;\nconst OFFSET_MAPFONT = 12;\nconst OFFSET_GETFONT = 16;\nconst OFFSET_GETFONTDATA = 20;\nconst OFFSET_GETFACENAME = 24;\nconst OFFSET_GETFONTCHARSET = 28;\nconst OFFSET_DELETEFONT = 32;\nconst LOG_SOURCE$2 = "pdfium";\nconst LOG_CATEGORY$2 = "font-fallback";\nclass FontFallbackManager {\n constructor(config, logger = new NoopLogger()) {\n this.fontHandles = /* @__PURE__ */ new Map();\n this.fontCache = /* @__PURE__ */ new Map();\n this.nextHandleId = 1;\n this.module = null;\n this.enabled = false;\n this.structPtr = 0;\n this.releaseFnPtr = 0;\n this.enumFontsFnPtr = 0;\n this.mapFontFnPtr = 0;\n this.getFontFnPtr = 0;\n this.getFontDataFnPtr = 0;\n this.getFaceNameFnPtr = 0;\n this.getFontCharsetFnPtr = 0;\n this.deleteFontFnPtr = 0;\n this.fontConfig = config;\n this.logger = logger;\n }\n /**\n * Initialize the font fallback system and attach to PDFium module\n */\n initialize(module) {\n if (this.enabled) {\n this.logger.warn(LOG_SOURCE$2, LOG_CATEGORY$2, "Font fallback already initialized");\n return;\n }\n this.module = module;\n const pdfium = module.pdfium;\n if (typeof pdfium.addFunction !== "function") {\n this.logger.error(\n LOG_SOURCE$2,\n LOG_CATEGORY$2,\n "addFunction not available. Make sure WASM is compiled with -sALLOW_TABLE_GROWTH"\n );\n return;\n }\n try {\n this.structPtr = pdfium.wasmExports.malloc(SYSFONTINFO_SIZE);\n if (!this.structPtr) {\n throw new Error("Failed to allocate FPDF_SYSFONTINFO struct");\n }\n for (let i = 0; i < SYSFONTINFO_SIZE; i++) {\n pdfium.setValue(this.structPtr + i, 0, "i8");\n }\n this.releaseFnPtr = pdfium.addFunction((_pThis) => {\n }, "vi");\n this.enumFontsFnPtr = pdfium.addFunction((_pThis, _pMapper) => {\n }, "vii");\n this.mapFontFnPtr = pdfium.addFunction(\n (_pThis, weight, bItalic, charset, pitchFamily, facePtr, bExactPtr) => {\n const face = facePtr ? pdfium.UTF8ToString(facePtr) : "";\n const handle = this.mapFont(weight, bItalic, charset, pitchFamily, face);\n if (bExactPtr) {\n pdfium.setValue(bExactPtr, 0, "i32");\n }\n return handle;\n },\n "iiiiiiii"\n );\n this.getFontFnPtr = pdfium.addFunction((_pThis, facePtr) => {\n const face = facePtr ? pdfium.UTF8ToString(facePtr) : "";\n return this.mapFont(400, 0, 0, 0, face);\n }, "iii");\n this.getFontDataFnPtr = pdfium.addFunction(\n (_pThis, hFont, table, buffer, bufSize) => {\n return this.getFontData(hFont, table, buffer, bufSize);\n },\n "iiiiii"\n );\n this.getFaceNameFnPtr = pdfium.addFunction(\n (_pThis, _hFont, _buffer, _bufSize) => {\n return 0;\n },\n "iiiii"\n );\n this.getFontCharsetFnPtr = pdfium.addFunction((_pThis, hFont) => {\n const handle = this.fontHandles.get(hFont);\n return (handle == null ? void 0 : handle.charset) ?? 0;\n }, "iii");\n this.deleteFontFnPtr = pdfium.addFunction((_pThis, hFont) => {\n this.deleteFont(hFont);\n }, "vii");\n pdfium.setValue(this.structPtr + OFFSET_VERSION, 1, "i32");\n pdfium.setValue(this.structPtr + OFFSET_RELEASE, this.releaseFnPtr, "i32");\n pdfium.setValue(this.structPtr + OFFSET_ENUMFONTS, this.enumFontsFnPtr, "i32");\n pdfium.setValue(this.structPtr + OFFSET_MAPFONT, this.mapFontFnPtr, "i32");\n pdfium.setValue(this.structPtr + OFFSET_GETFONT, this.getFontFnPtr, "i32");\n pdfium.setValue(this.structPtr + OFFSET_GETFONTDATA, this.getFontDataFnPtr, "i32");\n pdfium.setValue(this.structPtr + OFFSET_GETFACENAME, this.getFaceNameFnPtr, "i32");\n pdfium.setValue(this.structPtr + OFFSET_GETFONTCHARSET, this.getFontCharsetFnPtr, "i32");\n pdfium.setValue(this.structPtr + OFFSET_DELETEFONT, this.deleteFontFnPtr, "i32");\n module.FPDF_SetSystemFontInfo(this.structPtr);\n this.enabled = true;\n this.logger.info(\n LOG_SOURCE$2,\n LOG_CATEGORY$2,\n "Font fallback system initialized (pure TypeScript)",\n Object.keys(this.fontConfig.fonts)\n );\n } catch (error) {\n this.logger.error(LOG_SOURCE$2, LOG_CATEGORY$2, "Failed to initialize font fallback", error);\n this.cleanup();\n throw error;\n }\n }\n /**\n * Disable the font fallback system and clean up resources\n */\n disable() {\n if (!this.enabled || !this.module) {\n return;\n }\n this.module.FPDF_SetSystemFontInfo(0);\n this.cleanup();\n this.enabled = false;\n this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, "Font fallback system disabled");\n }\n /**\n * Clean up allocated resources\n */\n cleanup() {\n if (!this.module) return;\n const pdfium = this.module.pdfium;\n if (this.structPtr) {\n pdfium.wasmExports.free(this.structPtr);\n this.structPtr = 0;\n }\n const removeIfExists = (ptr) => {\n if (ptr && typeof pdfium.removeFunction === "function") {\n try {\n pdfium.removeFunction(ptr);\n } catch {\n }\n }\n };\n removeIfExists(this.releaseFnPtr);\n removeIfExists(this.enumFontsFnPtr);\n removeIfExists(this.mapFontFnPtr);\n removeIfExists(this.getFontFnPtr);\n removeIfExists(this.getFontDataFnPtr);\n removeIfExists(this.getFaceNameFnPtr);\n removeIfExists(this.getFontCharsetFnPtr);\n removeIfExists(this.deleteFontFnPtr);\n this.releaseFnPtr = 0;\n this.enumFontsFnPtr = 0;\n this.mapFontFnPtr = 0;\n this.getFontFnPtr = 0;\n this.getFontDataFnPtr = 0;\n this.getFaceNameFnPtr = 0;\n this.getFontCharsetFnPtr = 0;\n this.deleteFontFnPtr = 0;\n }\n /**\n * Check if font fallback is enabled\n */\n isEnabled() {\n return this.enabled;\n }\n /**\n * Get statistics about font loading\n */\n getStats() {\n return {\n handleCount: this.fontHandles.size,\n cacheSize: this.fontCache.size,\n cachedUrls: Array.from(this.fontCache.keys())\n };\n }\n /**\n * Pre-load fonts for specific charsets (optional optimization)\n * This can be called to warm the cache before rendering\n */\n async preloadFonts(charsets) {\n const urls = charsets.map((charset) => this.getFontUrlForCharset(charset)).filter((url) => url !== null);\n const uniqueUrls = [...new Set(urls)];\n await Promise.all(\n uniqueUrls.map(async (url) => {\n if (!this.fontCache.has(url)) {\n try {\n const data = await this.fetchFontAsync(url);\n if (data) {\n this.fontCache.set(url, data);\n this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, `Pre-loaded font: ${url}`);\n }\n } catch (error) {\n this.logger.warn(LOG_SOURCE$2, LOG_CATEGORY$2, `Failed to pre-load font: ${url}`, error);\n }\n }\n })\n );\n }\n // ============================================================================\n // PDFium Callback Implementations\n // ============================================================================\n /**\n * MapFont - called by PDFium when it needs a font\n */\n mapFont(weight, bItalic, charset, pitchFamily, face) {\n const italic = bItalic !== 0;\n this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, "MapFont called", {\n weight,\n italic,\n charset,\n pitchFamily,\n face\n });\n const result = this.findBestFontMatch(charset, weight, italic);\n if (!result) {\n this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, `No font configured for charset ${charset}`);\n return 0;\n }\n const handle = {\n id: this.nextHandleId++,\n charset,\n weight,\n italic,\n url: result.url,\n data: null\n };\n this.fontHandles.set(handle.id, handle);\n this.logger.debug(\n LOG_SOURCE$2,\n LOG_CATEGORY$2,\n `Created font handle ${handle.id} for ${result.url} (requested: weight=${weight}, italic=${italic}, matched: weight=${result.matchedWeight}, italic=${result.matchedItalic})`\n );\n return handle.id;\n }\n /**\n * GetFontData - called by PDFium to get font bytes\n */\n getFontData(fontHandle, table, bufferPtr, bufSize) {\n const handle = this.fontHandles.get(fontHandle);\n if (!handle) {\n this.logger.warn(LOG_SOURCE$2, LOG_CATEGORY$2, `Unknown font handle: ${fontHandle}`);\n return 0;\n }\n if (!handle.data) {\n if (this.fontCache.has(handle.url)) {\n handle.data = this.fontCache.get(handle.url);\n } else {\n handle.data = this.fetchFontSync(handle.url);\n if (handle.data) {\n this.fontCache.set(handle.url, handle.data);\n }\n }\n }\n if (!handle.data) {\n this.logger.warn(LOG_SOURCE$2, LOG_CATEGORY$2, `Failed to load font: ${handle.url}`);\n return 0;\n }\n const fontData = handle.data;\n if (table !== 0) {\n this.logger.debug(\n LOG_SOURCE$2,\n LOG_CATEGORY$2,\n `Table ${table} requested - returning 0 to request whole file`\n );\n return 0;\n }\n if (bufferPtr === 0 || bufSize < fontData.length) {\n return fontData.length;\n }\n if (this.module) {\n const heap = this.module.pdfium.HEAPU8;\n heap.set(fontData, bufferPtr);\n this.logger.debug(\n LOG_SOURCE$2,\n LOG_CATEGORY$2,\n `Copied ${fontData.length} bytes to buffer for handle ${fontHandle}`\n );\n }\n return fontData.length;\n }\n /**\n * DeleteFont - called by PDFium when done with a font\n */\n deleteFont(fontHandle) {\n const handle = this.fontHandles.get(fontHandle);\n if (handle) {\n this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, `Deleting font handle ${fontHandle}`);\n this.fontHandles.delete(fontHandle);\n }\n }\n // ============================================================================\n // Helper Methods\n // ============================================================================\n /**\n * Find the best matching font variant for the given parameters\n */\n findBestFontMatch(charset, requestedWeight, requestedItalic) {\n const { fonts: fonts2, defaultFont, baseUrl } = this.fontConfig;\n const entry = fonts2[charset] ?? defaultFont;\n if (!entry) {\n return null;\n }\n const variants = this.normalizeToVariants(entry);\n if (variants.length === 0) {\n return null;\n }\n const best = this.selectBestVariant(variants, requestedWeight, requestedItalic);\n let url = best.url;\n if (baseUrl && !url.startsWith("http://") && !url.startsWith("https://") && !url.startsWith("/")) {\n url = `${baseUrl}/${url}`;\n }\n return {\n url,\n matchedWeight: best.weight ?? 400,\n matchedItalic: best.italic ?? false\n };\n }\n /**\n * Normalize a FontEntry to an array of FontVariants\n */\n normalizeToVariants(entry) {\n if (typeof entry === "string") {\n return [{ url: entry, weight: 400, italic: false }];\n }\n if (Array.isArray(entry)) {\n return entry.map((v) => ({\n url: v.url,\n weight: v.weight ?? 400,\n italic: v.italic ?? false\n }));\n }\n return [{ url: entry.url, weight: entry.weight ?? 400, italic: entry.italic ?? false }];\n }\n /**\n * Select the best matching variant based on weight and italic\n * Uses CSS font matching algorithm principles:\n * 1. Exact italic match preferred\n * 2. Closest weight (with bias toward bolder for weights >= 400)\n */\n selectBestVariant(variants, requestedWeight, requestedItalic) {\n if (variants.length === 1) {\n return variants[0];\n }\n const italicMatches = variants.filter((v) => (v.italic ?? false) === requestedItalic);\n const candidates = italicMatches.length > 0 ? italicMatches : variants;\n let bestMatch = candidates[0];\n let bestDistance = Math.abs((bestMatch.weight ?? 400) - requestedWeight);\n for (const variant of candidates) {\n const variantWeight = variant.weight ?? 400;\n const distance = Math.abs(variantWeight - requestedWeight);\n if (distance < bestDistance) {\n bestMatch = variant;\n bestDistance = distance;\n } else if (distance === bestDistance) {\n const currentWeight = bestMatch.weight ?? 400;\n if (requestedWeight >= 500) {\n if (variantWeight > currentWeight) {\n bestMatch = variant;\n }\n } else {\n if (variantWeight < currentWeight) {\n bestMatch = variant;\n }\n }\n }\n }\n return bestMatch;\n }\n /**\n * Get font URL for a charset (backward compatible helper)\n */\n getFontUrlForCharset(charset) {\n const result = this.findBestFontMatch(charset, 400, false);\n return (result == null ? void 0 : result.url) ?? null;\n }\n /**\n * Fetch font data synchronously\n * Uses custom fontLoader if provided, otherwise falls back to XMLHttpRequest (browser)\n */\n fetchFontSync(pathOrUrl) {\n this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, `Fetching font synchronously: ${pathOrUrl}`);\n if (this.fontConfig.fontLoader) {\n try {\n const data = this.fontConfig.fontLoader(pathOrUrl);\n if (data) {\n this.logger.info(\n LOG_SOURCE$2,\n LOG_CATEGORY$2,\n `Loaded font via custom loader: ${pathOrUrl} (${data.length} bytes)`\n );\n } else {\n this.logger.warn(\n LOG_SOURCE$2,\n LOG_CATEGORY$2,\n `Custom font loader returned null for: ${pathOrUrl}`\n );\n }\n return data;\n } catch (error) {\n this.logger.error(\n LOG_SOURCE$2,\n LOG_CATEGORY$2,\n `Error in custom font loader: ${pathOrUrl}`,\n error\n );\n return null;\n }\n }\n try {\n const xhr = new XMLHttpRequest();\n xhr.open("GET", pathOrUrl, false);\n xhr.responseType = "arraybuffer";\n xhr.send();\n if (xhr.status === 200) {\n const data = new Uint8Array(xhr.response);\n this.logger.info(\n LOG_SOURCE$2,\n LOG_CATEGORY$2,\n `Loaded font: ${pathOrUrl} (${data.length} bytes)`\n );\n return data;\n } else {\n this.logger.error(\n LOG_SOURCE$2,\n LOG_CATEGORY$2,\n `Failed to load font: ${pathOrUrl} (HTTP ${xhr.status})`\n );\n return null;\n }\n } catch (error) {\n this.logger.error(LOG_SOURCE$2, LOG_CATEGORY$2, `Error fetching font: ${pathOrUrl}`, error);\n return null;\n }\n }\n /**\n * Fetch font data asynchronously (for preloading)\n * Uses custom fontLoader if provided, otherwise falls back to fetch API\n */\n async fetchFontAsync(pathOrUrl) {\n if (this.fontConfig.fontLoader) {\n try {\n return this.fontConfig.fontLoader(pathOrUrl);\n } catch {\n return null;\n }\n }\n try {\n const response = await fetch(pathOrUrl);\n if (response.ok) {\n const buffer = await response.arrayBuffer();\n return new Uint8Array(buffer);\n }\n return null;\n } catch {\n return null;\n }\n }\n}\nconst LOG_SOURCE$1 = "PDFiumEngine";\nconst LOG_CATEGORY$1 = "Engine";\nclass PdfiumNative {\n /**\n * Create an instance of PdfiumNative and initialize PDFium\n * @param wasmModule - pdfium wasm module\n * @param options - configuration options\n */\n constructor(pdfiumModule, options = {}) {\n this.pdfiumModule = pdfiumModule;\n this.memoryLeakCheckInterval = null;\n this.fontFallbackManager = null;\n const { logger = new NoopLogger(), fontFallback } = options;\n this.logger = logger;\n this.memoryManager = new MemoryManager(this.pdfiumModule, this.logger);\n this.cache = new PdfCache(this.pdfiumModule, this.memoryManager);\n if (this.logger.isEnabled("debug")) {\n this.memoryLeakCheckInterval = setInterval(() => {\n this.memoryManager.checkLeaks();\n }, 1e4);\n }\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "initialize");\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `Initialize`, "Begin", "General");\n this.pdfiumModule.PDFiumExt_Init();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `Initialize`, "End", "General");\n if (fontFallback) {\n this.fontFallbackManager = new FontFallbackManager(fontFallback, this.logger);\n this.fontFallbackManager.initialize(this.pdfiumModule);\n this.logger.info(LOG_SOURCE$1, LOG_CATEGORY$1, "Font fallback system enabled");\n }\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.destroy}\n *\n * @public\n */\n destroy() {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "destroy");\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `Destroy`, "Begin", "General");\n if (this.fontFallbackManager) {\n this.fontFallbackManager.disable();\n this.fontFallbackManager = null;\n }\n this.pdfiumModule.FPDF_DestroyLibrary();\n if (this.memoryLeakCheckInterval) {\n clearInterval(this.memoryLeakCheckInterval);\n this.memoryLeakCheckInterval = null;\n }\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `Destroy`, "End", "General");\n return PdfTaskHelper.resolve(true);\n }\n /**\n * Get the font fallback manager instance\n * Useful for pre-loading fonts or checking stats\n */\n getFontFallbackManager() {\n return this.fontFallbackManager;\n }\n /** Write a UTF-16LE (WIDESTRING) to wasm, call `fn(ptr)`, then free. */\n withWString(value, fn) {\n const length = (value.length + 1) * 2;\n const ptr = this.memoryManager.malloc(length);\n try {\n this.pdfiumModule.pdfium.stringToUTF16(value, ptr, length);\n return fn(ptr);\n } finally {\n this.memoryManager.free(ptr);\n }\n }\n /** Write a float[] to wasm, call `fn(ptr, count)`, then free. */\n withFloatArray(values, fn) {\n const arr = values ?? [];\n const bytes = arr.length * 4;\n const ptr = bytes ? this.memoryManager.malloc(bytes) : WasmPointer(0);\n try {\n if (bytes) {\n for (let i = 0; i < arr.length; i++) {\n this.pdfiumModule.pdfium.setValue(ptr + i * 4, arr[i], "float");\n }\n }\n return fn(ptr, arr.length);\n } finally {\n if (bytes) this.memoryManager.free(ptr);\n }\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.openDocument}\n *\n * @public\n */\n openDocumentBuffer(file, options) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "openDocumentBuffer", file, options);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `OpenDocumentBuffer`, "Begin", file.id);\n const normalizeRotation = (options == null ? void 0 : options.normalizeRotation) ?? false;\n const array = new Uint8Array(file.content);\n const length = array.length;\n const filePtr = this.memoryManager.malloc(length);\n this.pdfiumModule.pdfium.HEAPU8.set(array, filePtr);\n const docPtr = this.pdfiumModule.FPDF_LoadMemDocument(filePtr, length, (options == null ? void 0 : options.password) ?? "");\n if (!docPtr) {\n const lastError = this.pdfiumModule.FPDF_GetLastError();\n this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, `FPDF_LoadMemDocument failed with ${lastError}`);\n this.memoryManager.free(filePtr);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `OpenDocumentBuffer`, "End", file.id);\n return PdfTaskHelper.reject({\n code: lastError,\n message: `FPDF_LoadMemDocument failed`\n });\n }\n const pageCount = this.pdfiumModule.FPDF_GetPageCount(docPtr);\n const pages = [];\n const sizePtr = this.memoryManager.malloc(8);\n for (let index = 0; index < pageCount; index++) {\n const result = normalizeRotation ? this.pdfiumModule.EPDF_GetPageSizeByIndexNormalized(docPtr, index, sizePtr) : this.pdfiumModule.FPDF_GetPageSizeByIndexF(docPtr, index, sizePtr);\n if (!result) {\n const lastError = this.pdfiumModule.FPDF_GetLastError();\n this.logger.error(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `${normalizeRotation ? "EPDF_GetPageSizeByIndexNormalized" : "FPDF_GetPageSizeByIndexF"} failed with ${lastError}`\n );\n this.memoryManager.free(sizePtr);\n this.pdfiumModule.FPDF_CloseDocument(docPtr);\n this.memoryManager.free(filePtr);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `OpenDocumentBuffer`, "End", file.id);\n return PdfTaskHelper.reject({\n code: lastError,\n message: `${normalizeRotation ? "EPDF_GetPageSizeByIndexNormalized" : "FPDF_GetPageSizeByIndexF"} failed`\n });\n }\n const rotation = this.pdfiumModule.EPDF_GetPageRotationByIndex(docPtr, index);\n const page = {\n index,\n size: {\n width: this.pdfiumModule.pdfium.getValue(sizePtr, "float"),\n height: this.pdfiumModule.pdfium.getValue(sizePtr + 4, "float")\n },\n rotation\n };\n pages.push(page);\n }\n this.memoryManager.free(sizePtr);\n const isEncrypted = this.pdfiumModule.EPDF_IsEncrypted(docPtr);\n const isOwnerUnlocked = this.pdfiumModule.EPDF_IsOwnerUnlocked(docPtr);\n const permissions = this.pdfiumModule.FPDF_GetDocPermissions(docPtr);\n const pdfDoc = {\n id: file.id,\n pageCount,\n pages,\n isEncrypted,\n isOwnerUnlocked,\n permissions,\n normalizedRotation: normalizeRotation\n };\n this.cache.setDocument(file.id, filePtr, docPtr, normalizeRotation);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `OpenDocumentBuffer`, "End", file.id);\n return PdfTaskHelper.resolve(pdfDoc);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.getMetadata}\n *\n * @public\n */\n getMetadata(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getMetadata", doc);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `GetMetadata`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `GetMetadata`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const creationRaw = this.readMetaText(ctx.docPtr, "CreationDate");\n const modRaw = this.readMetaText(ctx.docPtr, "ModDate");\n const metadata = {\n title: this.readMetaText(ctx.docPtr, "Title"),\n author: this.readMetaText(ctx.docPtr, "Author"),\n subject: this.readMetaText(ctx.docPtr, "Subject"),\n keywords: this.readMetaText(ctx.docPtr, "Keywords"),\n producer: this.readMetaText(ctx.docPtr, "Producer"),\n creator: this.readMetaText(ctx.docPtr, "Creator"),\n creationDate: creationRaw ? pdfDateToDate(creationRaw) ?? null : null,\n modificationDate: modRaw ? pdfDateToDate(modRaw) ?? null : null,\n trapped: this.getMetaTrapped(ctx.docPtr),\n custom: this.readAllMeta(ctx.docPtr, true)\n };\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `GetMetadata`, "End", doc.id);\n return PdfTaskHelper.resolve(metadata);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.setMetadata}\n *\n * @public\n */\n setMetadata(doc, meta) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "setMetadata", doc, meta);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "SetMetadata", "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "SetMetadata", "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const strMap = [\n ["title", "Title"],\n ["author", "Author"],\n ["subject", "Subject"],\n ["keywords", "Keywords"],\n ["producer", "Producer"],\n ["creator", "Creator"]\n ];\n let ok = true;\n for (const [field, key] of strMap) {\n const v = meta[field];\n if (v === void 0) continue;\n const s = v === null ? null : v;\n if (!this.setMetaText(ctx.docPtr, key, s)) ok = false;\n }\n const writeDate = (field, key) => {\n const v = meta[field];\n if (v === void 0) return;\n if (v === null) {\n if (!this.setMetaText(ctx.docPtr, key, null)) ok = false;\n return;\n }\n const d = v;\n const raw = dateToPdfDate(d);\n if (!this.setMetaText(ctx.docPtr, key, raw)) ok = false;\n };\n writeDate("creationDate", "CreationDate");\n writeDate("modificationDate", "ModDate");\n if (meta.trapped !== void 0) {\n if (!this.setMetaTrapped(ctx.docPtr, meta.trapped ?? null)) ok = false;\n }\n if (meta.custom !== void 0) {\n for (const [key, value] of Object.entries(meta.custom)) {\n if (!isValidCustomKey(key)) {\n this.logger.warn(LOG_SOURCE$1, LOG_CATEGORY$1, "Invalid custom metadata key skipped", key);\n continue;\n }\n if (!this.setMetaText(ctx.docPtr, key, value ?? null)) ok = false;\n }\n }\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "SetMetadata", "End", doc.id);\n return ok ? PdfTaskHelper.resolve(true) : PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: "one or more metadata fields could not be written"\n });\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.getDocPermissions}\n *\n * @public\n */\n getDocPermissions(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getDocPermissions", doc);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `getDocPermissions`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `getDocPermissions`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const permissions = this.pdfiumModule.FPDF_GetDocPermissions(ctx.docPtr);\n return PdfTaskHelper.resolve(permissions);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.getDocUserPermissions}\n *\n * @public\n */\n getDocUserPermissions(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getDocUserPermissions", doc);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `getDocUserPermissions`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `getDocUserPermissions`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const permissions = this.pdfiumModule.FPDF_GetDocUserPermissions(ctx.docPtr);\n return PdfTaskHelper.resolve(permissions);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.getSignatures}\n *\n * @public\n */\n getSignatures(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getSignatures", doc);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `GetSignatures`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `GetSignatures`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const signatures = [];\n const count = this.pdfiumModule.FPDF_GetSignatureCount(ctx.docPtr);\n for (let i = 0; i < count; i++) {\n const signatureObjPtr = this.pdfiumModule.FPDF_GetSignatureObject(ctx.docPtr, i);\n const contents = readArrayBuffer(this.pdfiumModule.pdfium, (buffer, bufferSize) => {\n return this.pdfiumModule.FPDFSignatureObj_GetContents(signatureObjPtr, buffer, bufferSize);\n });\n const byteRange = readArrayBuffer(this.pdfiumModule.pdfium, (buffer, bufferSize) => {\n return this.pdfiumModule.FPDFSignatureObj_GetByteRange(signatureObjPtr, buffer, bufferSize) * 4;\n });\n const subFilter = readArrayBuffer(this.pdfiumModule.pdfium, (buffer, bufferSize) => {\n return this.pdfiumModule.FPDFSignatureObj_GetSubFilter(signatureObjPtr, buffer, bufferSize);\n });\n const reason = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFSignatureObj_GetReason(\n signatureObjPtr,\n buffer,\n bufferLength\n );\n },\n this.pdfiumModule.pdfium.UTF16ToString\n );\n const time = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFSignatureObj_GetTime(signatureObjPtr, buffer, bufferLength);\n },\n this.pdfiumModule.pdfium.UTF8ToString\n );\n const docMDP = this.pdfiumModule.FPDFSignatureObj_GetDocMDPPermission(signatureObjPtr);\n signatures.push({\n contents,\n byteRange,\n subFilter,\n reason,\n time,\n docMDP\n });\n }\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `GetSignatures`, "End", doc.id);\n return PdfTaskHelper.resolve(signatures);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.getBookmarks}\n *\n * @public\n */\n getBookmarks(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getBookmarks", doc);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `GetBookmarks`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `getBookmarks`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const bookmarks = this.readPdfBookmarks(ctx.docPtr, 0);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `GetBookmarks`, "End", doc.id);\n return PdfTaskHelper.resolve({\n bookmarks\n });\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.setBookmarks}\n *\n * @public\n */\n setBookmarks(doc, list) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "setBookmarks", doc, list);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `SetBookmarks`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `SetBookmarks`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n if (!this.pdfiumModule.EPDFBookmark_Clear(ctx.docPtr)) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `SetBookmarks`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: "failed to clear existing bookmarks"\n });\n }\n const build = (parentPtr, items) => {\n var _a;\n for (const item of items) {\n const bmPtr = this.withWString(\n item.title ?? "",\n (wptr) => this.pdfiumModule.EPDFBookmark_AppendChild(ctx.docPtr, parentPtr, wptr)\n );\n if (!bmPtr) return false;\n if (item.target) {\n const ok2 = this.applyBookmarkTarget(ctx.docPtr, bmPtr, item.target);\n if (!ok2) return false;\n }\n if ((_a = item.children) == null ? void 0 : _a.length) {\n const ok2 = build(bmPtr, item.children);\n if (!ok2) return false;\n }\n }\n return true;\n };\n const ok = build(\n /*top-level*/\n 0,\n list\n );\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `SetBookmarks`, "End", doc.id);\n if (!ok) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: "failed to build bookmark tree"\n });\n }\n return PdfTaskHelper.resolve(true);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.deleteBookmarks}\n *\n * @public\n */\n deleteBookmarks(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "deleteBookmarks", doc);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `DeleteBookmarks`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `DeleteBookmarks`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const ok = this.pdfiumModule.EPDFBookmark_Clear(ctx.docPtr);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `DeleteBookmarks`, "End", doc.id);\n return ok ? PdfTaskHelper.resolve(true) : PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: "failed to clear bookmarks"\n });\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.renderPage}\n *\n * @public\n */\n renderPageRaw(doc, page, options) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "renderPage", doc, page, options);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `RenderPage`, "Begin", `${doc.id}-${page.index}`);\n const rect = { origin: { x: 0, y: 0 }, size: page.size };\n const task = this.renderRectEncoded(doc, page, rect, options);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `RenderPage`, "End", `${doc.id}-${page.index}`);\n return task;\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.renderPageRect}\n *\n * @public\n */\n renderPageRect(doc, page, rect, options) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "renderPageRect", doc, page, rect, options);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RenderPageRect`,\n "Begin",\n `${doc.id}-${page.index}`\n );\n const task = this.renderRectEncoded(doc, page, rect, options);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `RenderPageRect`, "End", `${doc.id}-${page.index}`);\n return task;\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.getPageAnnotations}\n *\n * @public\n */\n getPageAnnotations(doc, page) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageAnnotations", doc, page);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `GetPageAnnotations`,\n "Begin",\n `${doc.id}-${page.index}`\n );\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `GetPageAnnotations`,\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const annotations = this.readPageAnnotations(doc, ctx, page);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `GetPageAnnotations`,\n "End",\n `${doc.id}-${page.index}`\n );\n this.logger.debug(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `GetPageAnnotations`,\n `${doc.id}-${page.index}`,\n annotations\n );\n return PdfTaskHelper.resolve(annotations);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.createPageAnnotation}\n *\n * @public\n */\n createPageAnnotation(doc, page, annotation, context) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "createPageAnnotation", doc, page, annotation);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `CreatePageAnnotation`,\n "Begin",\n `${doc.id}-${page.index}`\n );\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `CreatePageAnnotation`,\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const annotationPtr = this.pdfiumModule.EPDFPage_CreateAnnot(pageCtx.pagePtr, annotation.type);\n if (!annotationPtr) {\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `CreatePageAnnotation`,\n "End",\n `${doc.id}-${page.index}`\n );\n pageCtx.release();\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantCreateAnnot,\n message: "can not create annotation with specified type"\n });\n }\n if (!isUuidV4(annotation.id)) {\n annotation.id = uuidV4();\n }\n if (!this.setAnnotString(annotationPtr, "NM", annotation.id)) {\n this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);\n pageCtx.release();\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantSetAnnotString,\n message: "can not set the name of the annotation"\n });\n }\n if (!this.setPageAnnoRect(doc, page, annotationPtr, annotation.rect)) {\n this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);\n pageCtx.release();\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `CreatePageAnnotation`,\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantSetAnnotRect,\n message: "can not set the rect of the annotation"\n });\n }\n const saveAnnotation = this.prepareAnnotationForSave(annotation);\n let isSucceed = false;\n switch (saveAnnotation.type) {\n case PdfAnnotationSubtype.INK:\n isSucceed = this.addInkStroke(\n doc,\n page,\n pageCtx.pagePtr,\n annotationPtr,\n saveAnnotation\n );\n break;\n case PdfAnnotationSubtype.STAMP:\n isSucceed = this.addStampContent(\n doc,\n ctx.docPtr,\n page,\n pageCtx.pagePtr,\n annotationPtr,\n saveAnnotation,\n context == null ? void 0 : context.imageData\n );\n break;\n case PdfAnnotationSubtype.TEXT:\n isSucceed = this.addTextContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotationPtr,\n saveAnnotation\n );\n break;\n case PdfAnnotationSubtype.FREETEXT:\n isSucceed = this.addFreeTextContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotationPtr,\n saveAnnotation\n );\n break;\n case PdfAnnotationSubtype.LINE:\n isSucceed = this.addLineContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotationPtr,\n saveAnnotation\n );\n break;\n case PdfAnnotationSubtype.POLYLINE:\n case PdfAnnotationSubtype.POLYGON:\n isSucceed = this.addPolyContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotationPtr,\n saveAnnotation\n );\n break;\n case PdfAnnotationSubtype.CIRCLE:\n case PdfAnnotationSubtype.SQUARE:\n isSucceed = this.addShapeContent(doc, page, pageCtx.pagePtr, annotationPtr, saveAnnotation);\n break;\n case PdfAnnotationSubtype.UNDERLINE:\n case PdfAnnotationSubtype.STRIKEOUT:\n case PdfAnnotationSubtype.SQUIGGLY:\n case PdfAnnotationSubtype.HIGHLIGHT:\n isSucceed = this.addTextMarkupContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotationPtr,\n saveAnnotation\n );\n break;\n case PdfAnnotationSubtype.LINK:\n isSucceed = this.addLinkContent(\n doc,\n page,\n ctx.docPtr,\n pageCtx.pagePtr,\n annotationPtr,\n saveAnnotation\n );\n break;\n case PdfAnnotationSubtype.REDACT:\n isSucceed = this.addRedactContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotationPtr,\n saveAnnotation\n );\n break;\n }\n if (!isSucceed) {\n this.pdfiumModule.FPDFPage_RemoveAnnot(pageCtx.pagePtr, annotationPtr);\n pageCtx.release();\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `CreatePageAnnotation`,\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantSetAnnotContent,\n message: "can not add content of the annotation"\n });\n }\n if (annotation.blendMode !== void 0) {\n this.pdfiumModule.EPDFAnnot_GenerateAppearanceWithBlend(annotationPtr, annotation.blendMode);\n } else {\n this.pdfiumModule.EPDFAnnot_GenerateAppearance(annotationPtr);\n }\n this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);\n this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);\n pageCtx.release();\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `CreatePageAnnotation`,\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.resolve(annotation.id);\n }\n /**\n * Update an existing page annotation in-place\n *\n * • Locates the annot by page-local index (`annotation.id`)\n * • Re-writes its /Rect and type-specific payload\n * • Calls FPDFPage_GenerateContent so the new appearance is rendered\n *\n * @returns PdfTask – true on success\n */\n updatePageAnnotation(doc, page, annotation) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "updatePageAnnotation", doc, page, annotation);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "UpdatePageAnnotation",\n "Begin",\n `${doc.id}-${page.index}`\n );\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "UpdatePageAnnotation",\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const annotPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);\n if (!annotPtr) {\n pageCtx.release();\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "UpdatePageAnnotation",\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({ code: PdfErrorCode.NotFound, message: "annotation not found" });\n }\n if (!this.setPageAnnoRect(doc, page, annotPtr, annotation.rect)) {\n this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);\n pageCtx.release();\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "UpdatePageAnnotation",\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantSetAnnotRect,\n message: "failed to move annotation"\n });\n }\n const saveAnnotation = this.prepareAnnotationForSave(annotation);\n let ok = false;\n switch (saveAnnotation.type) {\n /* ── Ink ─────────────────────────────────────────────────────────────── */\n case PdfAnnotationSubtype.INK: {\n if (!this.pdfiumModule.FPDFAnnot_RemoveInkList(annotPtr)) break;\n ok = this.addInkStroke(\n doc,\n page,\n pageCtx.pagePtr,\n annotPtr,\n saveAnnotation\n );\n break;\n }\n /* ── Stamp ───────────────────────────────────────────────────────────── */\n case PdfAnnotationSubtype.STAMP: {\n ok = this.addStampContent(\n doc,\n ctx.docPtr,\n page,\n pageCtx.pagePtr,\n annotPtr,\n saveAnnotation\n );\n break;\n }\n case PdfAnnotationSubtype.TEXT: {\n ok = this.addTextContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotPtr,\n saveAnnotation\n );\n break;\n }\n /* ── Free text ────────────────────────────────────────────────────────── */\n case PdfAnnotationSubtype.FREETEXT: {\n ok = this.addFreeTextContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotPtr,\n saveAnnotation\n );\n break;\n }\n /* ── Shape ───────────────────────────────────────────────────────────── */\n case PdfAnnotationSubtype.CIRCLE:\n case PdfAnnotationSubtype.SQUARE: {\n ok = this.addShapeContent(doc, page, pageCtx.pagePtr, annotPtr, saveAnnotation);\n break;\n }\n /* ── Line ─────────────────────────────────────────────────────────────── */\n case PdfAnnotationSubtype.LINE: {\n ok = this.addLineContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotPtr,\n saveAnnotation\n );\n break;\n }\n /* ── Polygon / Polyline ───────────────────────────────────────────────── */\n case PdfAnnotationSubtype.POLYGON:\n case PdfAnnotationSubtype.POLYLINE: {\n ok = this.addPolyContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotPtr,\n saveAnnotation\n );\n break;\n }\n /* ── Text-markup family ──────────────────────────────────────────────── */\n case PdfAnnotationSubtype.HIGHLIGHT:\n case PdfAnnotationSubtype.UNDERLINE:\n case PdfAnnotationSubtype.STRIKEOUT:\n case PdfAnnotationSubtype.SQUIGGLY: {\n ok = this.addTextMarkupContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotPtr,\n saveAnnotation\n );\n break;\n }\n /* ── Link ─────────────────────────────────────────────────────────────── */\n case PdfAnnotationSubtype.LINK: {\n ok = this.addLinkContent(\n doc,\n page,\n ctx.docPtr,\n pageCtx.pagePtr,\n annotPtr,\n saveAnnotation\n );\n break;\n }\n /* ── Redact ───────────────────────────────────────────────────────────── */\n case PdfAnnotationSubtype.REDACT: {\n ok = this.addRedactContent(\n doc,\n page,\n pageCtx.pagePtr,\n annotPtr,\n saveAnnotation\n );\n break;\n }\n /* ── Unsupported edits – fall through to error ───────────────────────── */\n default:\n ok = false;\n }\n if (ok) {\n if (annotation.blendMode !== void 0) {\n this.pdfiumModule.EPDFAnnot_GenerateAppearanceWithBlend(annotPtr, annotation.blendMode);\n } else {\n this.pdfiumModule.EPDFAnnot_GenerateAppearance(annotPtr);\n }\n this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);\n }\n this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);\n pageCtx.release();\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "UpdatePageAnnotation",\n "End",\n `${doc.id}-${page.index}`\n );\n return ok ? PdfTaskHelper.resolve(true) : PdfTaskHelper.reject({\n code: PdfErrorCode.CantSetAnnotContent,\n message: "failed to update annotation"\n });\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.removePageAnnotation}\n *\n * @public\n */\n removePageAnnotation(doc, page, annotation) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "removePageAnnotation", doc, page, annotation);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RemovePageAnnotation`,\n "Begin",\n `${doc.id}-${page.index}`\n );\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RemovePageAnnotation`,\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n let result = false;\n result = this.removeAnnotationByName(pageCtx.pagePtr, annotation.id);\n if (!result) {\n this.logger.error(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `FPDFPage_RemoveAnnot Failed`,\n `${doc.id}-${page.index}`\n );\n } else {\n result = this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);\n if (!result) {\n this.logger.error(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `FPDFPage_GenerateContent Failed`,\n `${doc.id}-${page.index}`\n );\n }\n }\n pageCtx.release();\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RemovePageAnnotation`,\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.resolve(result);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.getPageTextRects}\n *\n * @public\n */\n getPageTextRects(doc, page) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageTextRects", doc, page);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `GetPageTextRects`,\n "Begin",\n `${doc.id}-${page.index}`\n );\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `GetPageTextRects`,\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const textPagePtr = this.pdfiumModule.FPDFText_LoadPage(pageCtx.pagePtr);\n const textRects = this.readPageTextRects(page, pageCtx.docPtr, pageCtx.pagePtr, textPagePtr);\n this.pdfiumModule.FPDFText_ClosePage(textPagePtr);\n pageCtx.release();\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `GetPageTextRects`,\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.resolve(textRects);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.renderThumbnail}\n *\n * @public\n */\n renderThumbnailRaw(doc, page, options) {\n const { scaleFactor = 1, ...rest } = options ?? {};\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "renderThumbnail", doc, page, options);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RenderThumbnail`,\n "Begin",\n `${doc.id}-${page.index}`\n );\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RenderThumbnail`,\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const result = this.renderPageRaw(doc, page, {\n scaleFactor: Math.max(scaleFactor, 0.5),\n ...rest\n });\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `RenderThumbnail`, "End", `${doc.id}-${page.index}`);\n return result;\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.getAttachments}\n *\n * @public\n */\n getAttachments(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getAttachments", doc);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `GetAttachments`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `GetAttachments`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const attachments = [];\n const count = this.pdfiumModule.FPDFDoc_GetAttachmentCount(ctx.docPtr);\n for (let i = 0; i < count; i++) {\n const attachment = this.readPdfAttachment(ctx.docPtr, i);\n attachments.push(attachment);\n }\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `GetAttachments`, "End", doc.id);\n return PdfTaskHelper.resolve(attachments);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.addAttachment}\n *\n * @public\n */\n addAttachment(doc, params) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "addAttachment", doc, params == null ? void 0 : params.name);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `AddAttachment`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `AddAttachment`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const { name, description, mimeType, data } = params ?? {};\n if (!name) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `AddAttachment`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.NotFound,\n message: "attachment name is required"\n });\n }\n if (!data || (data instanceof Uint8Array ? data.byteLength === 0 : data.byteLength === 0)) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `AddAttachment`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.NotFound,\n message: "attachment data is empty"\n });\n }\n const attachmentPtr = this.withWString(\n name,\n (wNamePtr) => this.pdfiumModule.FPDFDoc_AddAttachment(ctx.docPtr, wNamePtr)\n );\n if (!attachmentPtr) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `AddAttachment`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: `An attachment named "${name}" already exists`\n });\n }\n this.withWString(\n description,\n (wDescriptionPtr) => this.pdfiumModule.EPDFAttachment_SetDescription(attachmentPtr, wDescriptionPtr)\n );\n this.pdfiumModule.EPDFAttachment_SetSubtype(attachmentPtr, mimeType);\n const u8 = data instanceof Uint8Array ? data : new Uint8Array(data);\n const len = u8.byteLength;\n const contentPtr = this.memoryManager.malloc(len);\n try {\n this.pdfiumModule.pdfium.HEAPU8.set(u8, contentPtr);\n const ok = this.pdfiumModule.FPDFAttachment_SetFile(\n attachmentPtr,\n ctx.docPtr,\n contentPtr,\n len\n );\n if (!ok) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `AddAttachment`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: "failed to write attachment bytes"\n });\n }\n } finally {\n this.memoryManager.free(contentPtr);\n }\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `AddAttachment`, "End", doc.id);\n return PdfTaskHelper.resolve(true);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.removeAttachment}\n *\n * @public\n */\n removeAttachment(doc, attachment) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "deleteAttachment", doc, attachment);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `DeleteAttachment`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `DeleteAttachment`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const count = this.pdfiumModule.FPDFDoc_GetAttachmentCount(ctx.docPtr);\n if (attachment.index < 0 || attachment.index >= count) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `DeleteAttachment`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: `attachment index ${attachment.index} out of range`\n });\n }\n const ok = this.pdfiumModule.FPDFDoc_DeleteAttachment(ctx.docPtr, attachment.index);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `DeleteAttachment`, "End", doc.id);\n if (!ok) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: "failed to delete attachment"\n });\n }\n return PdfTaskHelper.resolve(true);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.readAttachmentContent}\n *\n * @public\n */\n readAttachmentContent(doc, attachment) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "readAttachmentContent", doc, attachment);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ReadAttachmentContent`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ReadAttachmentContent`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const attachmentPtr = this.pdfiumModule.FPDFDoc_GetAttachment(ctx.docPtr, attachment.index);\n const sizePtr = this.memoryManager.malloc(4);\n if (!this.pdfiumModule.FPDFAttachment_GetFile(attachmentPtr, 0, 0, sizePtr)) {\n this.memoryManager.free(sizePtr);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ReadAttachmentContent`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantReadAttachmentSize,\n message: "can not read attachment size"\n });\n }\n const size = this.pdfiumModule.pdfium.getValue(sizePtr, "i32") >>> 0;\n const contentPtr = this.memoryManager.malloc(size);\n if (!this.pdfiumModule.FPDFAttachment_GetFile(attachmentPtr, contentPtr, size, sizePtr)) {\n this.memoryManager.free(sizePtr);\n this.memoryManager.free(contentPtr);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ReadAttachmentContent`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantReadAttachmentContent,\n message: "can not read attachment content"\n });\n }\n const buffer = new ArrayBuffer(size);\n const view = new DataView(buffer);\n for (let i = 0; i < size; i++) {\n view.setInt8(i, this.pdfiumModule.pdfium.getValue(contentPtr + i, "i8"));\n }\n this.memoryManager.free(sizePtr);\n this.memoryManager.free(contentPtr);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ReadAttachmentContent`, "End", doc.id);\n return PdfTaskHelper.resolve(buffer);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.setFormFieldValue}\n *\n * @public\n */\n setFormFieldValue(doc, page, annotation, value) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "SetFormFieldValue", doc, annotation, value);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `SetFormFieldValue`,\n "Begin",\n `${doc.id}-${annotation.id}`\n );\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "SetFormFieldValue", "document is not opened");\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `SetFormFieldValue`,\n "End",\n `${doc.id}-${annotation.id}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const formFillInfoPtr = this.pdfiumModule.PDFiumExt_OpenFormFillInfo();\n const formHandle = this.pdfiumModule.PDFiumExt_InitFormFillEnvironment(\n ctx.docPtr,\n formFillInfoPtr\n );\n const pageCtx = ctx.acquirePage(page.index);\n this.pdfiumModule.FORM_OnAfterLoadPage(pageCtx.pagePtr, formHandle);\n const annotationPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);\n if (!annotationPtr) {\n pageCtx.release();\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "SetFormFieldValue",\n "End",\n `${doc.id}-${page.index}`\n );\n return PdfTaskHelper.reject({ code: PdfErrorCode.NotFound, message: "annotation not found" });\n }\n if (!this.pdfiumModule.FORM_SetFocusedAnnot(formHandle, annotationPtr)) {\n this.logger.debug(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "SetFormFieldValue",\n "failed to set focused annotation"\n );\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `SetFormFieldValue`,\n "End",\n `${doc.id}-${annotation.id}`\n );\n this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);\n this.pdfiumModule.FORM_OnBeforeClosePage(pageCtx.pagePtr, formHandle);\n pageCtx.release();\n this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(formHandle);\n this.pdfiumModule.PDFiumExt_CloseFormFillInfo(formFillInfoPtr);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantFocusAnnot,\n message: "failed to set focused annotation"\n });\n }\n switch (value.kind) {\n case "text":\n {\n if (!this.pdfiumModule.FORM_SelectAllText(formHandle, pageCtx.pagePtr)) {\n this.logger.debug(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "SetFormFieldValue",\n "failed to select all text"\n );\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `SetFormFieldValue`,\n "End",\n `${doc.id}-${annotation.id}`\n );\n this.pdfiumModule.FORM_ForceToKillFocus(formHandle);\n this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);\n this.pdfiumModule.FORM_OnBeforeClosePage(pageCtx.pagePtr, formHandle);\n pageCtx.release();\n this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(formHandle);\n this.pdfiumModule.PDFiumExt_CloseFormFillInfo(formFillInfoPtr);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantSelectText,\n message: "failed to select all text"\n });\n }\n const length = 2 * (value.text.length + 1);\n const textPtr = this.memoryManager.malloc(length);\n this.pdfiumModule.pdfium.stringToUTF16(value.text, textPtr, length);\n this.pdfiumModule.FORM_ReplaceSelection(formHandle, pageCtx.pagePtr, textPtr);\n this.memoryManager.free(textPtr);\n }\n break;\n case "selection":\n {\n if (!this.pdfiumModule.FORM_SetIndexSelected(\n formHandle,\n pageCtx.pagePtr,\n value.index,\n value.isSelected\n )) {\n this.logger.debug(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "SetFormFieldValue",\n "failed to set index selected"\n );\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `SetFormFieldValue`,\n "End",\n `${doc.id}-${annotation.id}`\n );\n this.pdfiumModule.FORM_ForceToKillFocus(formHandle);\n this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);\n this.pdfiumModule.FORM_OnBeforeClosePage(pageCtx.pagePtr, formHandle);\n pageCtx.release();\n this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(formHandle);\n this.pdfiumModule.PDFiumExt_CloseFormFillInfo(formFillInfoPtr);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantSelectOption,\n message: "failed to set index selected"\n });\n }\n }\n break;\n case "checked":\n {\n const kReturn = 13;\n if (!this.pdfiumModule.FORM_OnChar(formHandle, pageCtx.pagePtr, kReturn, 0)) {\n this.logger.debug(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "SetFormFieldValue",\n "failed to set field checked"\n );\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `SetFormFieldValue`,\n "End",\n `${doc.id}-${annotation.id}`\n );\n this.pdfiumModule.FORM_ForceToKillFocus(formHandle);\n this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);\n this.pdfiumModule.FORM_OnBeforeClosePage(pageCtx.pagePtr, formHandle);\n pageCtx.release();\n this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(formHandle);\n this.pdfiumModule.PDFiumExt_CloseFormFillInfo(formFillInfoPtr);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantCheckField,\n message: "failed to set field checked"\n });\n }\n }\n break;\n }\n this.pdfiumModule.FORM_ForceToKillFocus(formHandle);\n this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);\n this.pdfiumModule.FORM_OnBeforeClosePage(pageCtx.pagePtr, formHandle);\n pageCtx.release();\n this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(formHandle);\n this.pdfiumModule.PDFiumExt_CloseFormFillInfo(formFillInfoPtr);\n return PdfTaskHelper.resolve(true);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.flattenPage}\n *\n * @public\n */\n flattenPage(doc, page, options) {\n const { flag = PdfPageFlattenFlag.Display } = options ?? {};\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "flattenPage", doc, page, flag);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `flattenPage`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `flattenPage`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const result = this.pdfiumModule.FPDFPage_Flatten(pageCtx.pagePtr, flag);\n pageCtx.release();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `flattenPage`, "End", doc.id);\n return PdfTaskHelper.resolve(result);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.extractPages}\n *\n * @public\n */\n extractPages(doc, pageIndexes) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "extractPages", doc, pageIndexes);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ExtractPages`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ExtractPages`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const newDocPtr = this.pdfiumModule.FPDF_CreateNewDocument();\n if (!newDocPtr) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ExtractPages`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantCreateNewDoc,\n message: "can not create new document"\n });\n }\n const pageIndexesPtr = this.memoryManager.malloc(pageIndexes.length * 4);\n for (let i = 0; i < pageIndexes.length; i++) {\n this.pdfiumModule.pdfium.setValue(pageIndexesPtr + i * 4, pageIndexes[i], "i32");\n }\n if (!this.pdfiumModule.FPDF_ImportPagesByIndex(\n newDocPtr,\n ctx.docPtr,\n pageIndexesPtr,\n pageIndexes.length,\n 0\n )) {\n this.pdfiumModule.FPDF_CloseDocument(newDocPtr);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ExtractPages`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantImportPages,\n message: "can not import pages to new document"\n });\n }\n const buffer = this.saveDocument(newDocPtr);\n this.pdfiumModule.FPDF_CloseDocument(newDocPtr);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ExtractPages`, "End", doc.id);\n return PdfTaskHelper.resolve(buffer);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.extractText}\n *\n * @public\n */\n extractText(doc, pageIndexes) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "extractText", doc, pageIndexes);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ExtractText`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ExtractText`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const strings = [];\n for (let i = 0; i < pageIndexes.length; i++) {\n const pageCtx = ctx.acquirePage(pageIndexes[i]);\n const textPagePtr = this.pdfiumModule.FPDFText_LoadPage(pageCtx.pagePtr);\n const charCount = this.pdfiumModule.FPDFText_CountChars(textPagePtr);\n const bufferPtr = this.memoryManager.malloc((charCount + 1) * 2);\n this.pdfiumModule.FPDFText_GetText(textPagePtr, 0, charCount, bufferPtr);\n const text2 = this.pdfiumModule.pdfium.UTF16ToString(bufferPtr);\n this.memoryManager.free(bufferPtr);\n strings.push(text2);\n this.pdfiumModule.FPDFText_ClosePage(textPagePtr);\n pageCtx.release();\n }\n const text = strings.join("\\n\\n");\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `ExtractText`, "End", doc.id);\n return PdfTaskHelper.resolve(text);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.getTextSlices}\n *\n * @public\n */\n getTextSlices(doc, slices) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getTextSlices", doc, slices);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetTextSlices", "Begin", doc.id);\n if (slices.length === 0) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetTextSlices", "End", doc.id);\n return PdfTaskHelper.resolve([]);\n }\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetTextSlices", "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n try {\n const out = new Array(slices.length);\n const byPage = /* @__PURE__ */ new Map();\n slices.forEach((s, i) => {\n (byPage.get(s.pageIndex) ?? byPage.set(s.pageIndex, []).get(s.pageIndex)).push({\n slice: s,\n pos: i\n });\n });\n for (const [pageIdx, list] of byPage) {\n const pageCtx = ctx.acquirePage(pageIdx);\n const textPagePtr = pageCtx.getTextPage();\n for (const { slice, pos } of list) {\n const bufPtr = this.memoryManager.malloc(2 * (slice.charCount + 1));\n this.pdfiumModule.FPDFText_GetText(textPagePtr, slice.charIndex, slice.charCount, bufPtr);\n out[pos] = stripPdfUnwantedMarkers(this.pdfiumModule.pdfium.UTF16ToString(bufPtr));\n this.memoryManager.free(bufPtr);\n }\n pageCtx.release();\n }\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetTextSlices", "End", doc.id);\n return PdfTaskHelper.resolve(out);\n } catch (e) {\n this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, "getTextSlices error", e);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetTextSlices", "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: String(e)\n });\n }\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.merge}\n *\n * @public\n */\n merge(files) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "merge", files);\n const fileIds = files.map((file2) => file2.id).join(".");\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `Merge`, "Begin", fileIds);\n const newDocPtr = this.pdfiumModule.FPDF_CreateNewDocument();\n if (!newDocPtr) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `Merge`, "End", fileIds);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantCreateNewDoc,\n message: "can not create new document"\n });\n }\n const ptrs = [];\n for (const file2 of files.reverse()) {\n const array = new Uint8Array(file2.content);\n const length = array.length;\n const filePtr = this.memoryManager.malloc(length);\n this.pdfiumModule.pdfium.HEAPU8.set(array, filePtr);\n const docPtr = this.pdfiumModule.FPDF_LoadMemDocument(filePtr, length, "");\n if (!docPtr) {\n const lastError = this.pdfiumModule.FPDF_GetLastError();\n this.logger.error(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `FPDF_LoadMemDocument failed with ${lastError}`\n );\n this.memoryManager.free(filePtr);\n for (const ptr of ptrs) {\n this.pdfiumModule.FPDF_CloseDocument(ptr.docPtr);\n this.memoryManager.free(ptr.filePtr);\n }\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `Merge`, "End", fileIds);\n return PdfTaskHelper.reject({\n code: lastError,\n message: `FPDF_LoadMemDocument failed`\n });\n }\n ptrs.push({ filePtr, docPtr });\n if (!this.pdfiumModule.FPDF_ImportPages(newDocPtr, docPtr, "", 0)) {\n this.pdfiumModule.FPDF_CloseDocument(newDocPtr);\n for (const ptr of ptrs) {\n this.pdfiumModule.FPDF_CloseDocument(ptr.docPtr);\n this.memoryManager.free(ptr.filePtr);\n }\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `Merge`, "End", fileIds);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantImportPages,\n message: "can not import pages to new document"\n });\n }\n }\n const buffer = this.saveDocument(newDocPtr);\n this.pdfiumModule.FPDF_CloseDocument(newDocPtr);\n for (const ptr of ptrs) {\n this.pdfiumModule.FPDF_CloseDocument(ptr.docPtr);\n this.memoryManager.free(ptr.filePtr);\n }\n const file = {\n id: `${Math.random()}`,\n content: buffer\n };\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `Merge`, "End", fileIds);\n return PdfTaskHelper.resolve(file);\n }\n /**\n * Merges specific pages from multiple PDF documents in a custom order\n *\n * @param mergeConfigs Array of configurations specifying which pages to merge from which documents\n * @returns A PdfTask that resolves with the merged PDF file\n * @public\n */\n mergePages(mergeConfigs) {\n const configIds = mergeConfigs.map((config) => `${config.docId}:${config.pageIndices.join(",")}`).join("|");\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "mergePages", mergeConfigs);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `MergePages`, "Begin", configIds);\n const newDocPtr = this.pdfiumModule.FPDF_CreateNewDocument();\n if (!newDocPtr) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `MergePages`, "End", configIds);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantCreateNewDoc,\n message: "Cannot create new document"\n });\n }\n try {\n for (const config of [...mergeConfigs].reverse()) {\n const ctx = this.cache.getContext(config.docId);\n if (!ctx) {\n this.logger.warn(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `Document ${config.docId} is not open, skipping`\n );\n continue;\n }\n const pageCount = this.pdfiumModule.FPDF_GetPageCount(ctx.docPtr);\n const validPageIndices = config.pageIndices.filter(\n (index) => index >= 0 && index < pageCount\n );\n if (validPageIndices.length === 0) {\n continue;\n }\n const pageString = validPageIndices.map((index) => index + 1).join(",");\n try {\n if (!this.pdfiumModule.FPDF_ImportPages(\n newDocPtr,\n ctx.docPtr,\n pageString,\n 0\n // Insert at the beginning\n )) {\n throw new Error(`Failed to import pages ${pageString} from document ${config.docId}`);\n }\n } finally {\n }\n }\n const buffer = this.saveDocument(newDocPtr);\n const file = {\n id: `${Math.random()}`,\n content: buffer\n };\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `MergePages`, "End", configIds);\n return PdfTaskHelper.resolve(file);\n } catch (error) {\n this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, "mergePages failed", error);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `MergePages`, "End", configIds);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantImportPages,\n message: error instanceof Error ? error.message : "Failed to merge pages"\n });\n } finally {\n if (newDocPtr) {\n this.pdfiumModule.FPDF_CloseDocument(newDocPtr);\n }\n }\n }\n /**\n * Sets AES-256 encryption on a document.\n * Must be called before saveAsCopy() for encryption to take effect.\n *\n * @param doc - Document to encrypt\n * @param userPassword - Password to open document (empty = no open password)\n * @param ownerPassword - Password to change permissions (required)\n * @param allowedFlags - OR\'d PdfPermissionFlag values indicating allowed actions\n * @returns true on success, false if already encrypted or invalid params\n *\n * @public\n */\n setDocumentEncryption(doc, userPassword, ownerPassword, allowedFlags) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "setDocumentEncryption", doc, allowedFlags);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const result = this.pdfiumModule.EPDF_SetEncryption(\n ctx.docPtr,\n userPassword,\n ownerPassword,\n allowedFlags\n );\n return PdfTaskHelper.resolve(result);\n }\n /**\n * Marks document for encryption removal on save.\n * When saveAsCopy is called, the document will be saved without encryption.\n *\n * @param doc - Document to remove encryption from\n * @returns true on success\n *\n * @public\n */\n removeEncryption(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "removeEncryption", doc);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const result = this.pdfiumModule.EPDF_RemoveEncryption(ctx.docPtr);\n return PdfTaskHelper.resolve(result);\n }\n /**\n * Attempts to unlock owner permissions for an already-opened encrypted document.\n *\n * @param doc - Document to unlock\n * @param ownerPassword - The owner password\n * @returns true on success, false on failure\n *\n * @public\n */\n unlockOwnerPermissions(doc, ownerPassword) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "unlockOwnerPermissions", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const success = this.pdfiumModule.EPDF_UnlockOwnerPermissions(ctx.docPtr, ownerPassword);\n return PdfTaskHelper.resolve(success);\n }\n /**\n * Check if a document is encrypted.\n *\n * @param doc - Document to check\n * @returns true if the document is encrypted\n *\n * @public\n */\n isEncrypted(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "isEncrypted", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const result = this.pdfiumModule.EPDF_IsEncrypted(ctx.docPtr);\n return PdfTaskHelper.resolve(result);\n }\n /**\n * Check if owner permissions are currently unlocked.\n *\n * @param doc - Document to check\n * @returns true if owner permissions are unlocked\n *\n * @public\n */\n isOwnerUnlocked(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "isOwnerUnlocked", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const result = this.pdfiumModule.EPDF_IsOwnerUnlocked(ctx.docPtr);\n return PdfTaskHelper.resolve(result);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.saveAsCopy}\n *\n * @public\n */\n saveAsCopy(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "saveAsCopy", doc);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `SaveAsCopy`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `SaveAsCopy`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const buffer = this.saveDocument(ctx.docPtr);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `SaveAsCopy`, "End", doc.id);\n return PdfTaskHelper.resolve(buffer);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.closeDocument}\n *\n * @public\n */\n closeDocument(doc) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "closeDocument", doc);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `CloseDocument`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) return PdfTaskHelper.resolve(true);\n ctx.dispose();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `CloseDocument`, "End", doc.id);\n return PdfTaskHelper.resolve(true);\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.closeAllDocuments}\n *\n * @public\n */\n closeAllDocuments() {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "closeAllDocuments");\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `CloseAllDocuments`, "Begin");\n this.cache.closeAllDocuments();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `CloseAllDocuments`, "End");\n return PdfTaskHelper.resolve(true);\n }\n /**\n * Add text content to annotation\n * @param page - page info\n * @param pagePtr - pointer to page object\n * @param annotationPtr - pointer to text annotation\n * @param annotation - text annotation\n * @returns whether text content is added to annotation\n *\n * @private\n */\n addTextContent(doc, page, pagePtr, annotationPtr, annotation) {\n if (!this.setAnnotationIcon(annotationPtr, annotation.icon || PdfAnnotationIcon.Comment)) {\n return false;\n }\n if (annotation.state && !this.setAnnotString(annotationPtr, "State", annotation.state)) {\n return false;\n }\n if (annotation.stateModel && !this.setAnnotString(annotationPtr, "StateModel", annotation.stateModel)) {\n return false;\n }\n if (!annotation.flags) {\n if (!this.setAnnotationFlags(annotationPtr, ["print", "noZoom", "noRotate"])) {\n return false;\n }\n }\n return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);\n }\n /**\n * Add free text content to annotation\n * @param page - page info\n * @param pagePtr - pointer to page object\n * @param annotationPtr - pointer to free text annotation\n * @param annotation - free text annotation\n * @returns whether free text content is added to annotation\n *\n * @private\n */\n addFreeTextContent(doc, page, pagePtr, annotationPtr, annotation) {\n if (!this.setBorderStyle(annotationPtr, PdfAnnotationBorderStyle.SOLID, 0)) {\n return false;\n }\n if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {\n return false;\n }\n if (!this.setAnnotationTextAlignment(annotationPtr, annotation.textAlign)) {\n return false;\n }\n if (!this.setAnnotationVerticalAlignment(annotationPtr, annotation.verticalAlign)) {\n return false;\n }\n if (!this.setAnnotationDefaultAppearance(\n annotationPtr,\n annotation.fontFamily,\n annotation.fontSize,\n annotation.fontColor\n )) {\n return false;\n }\n if (annotation.intent && !this.setAnnotIntent(annotationPtr, annotation.intent)) {\n return false;\n }\n const bgColor = annotation.color ?? annotation.backgroundColor;\n if (!bgColor || bgColor === "transparent") {\n if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.Color)) {\n return false;\n }\n } else if (!this.setAnnotationColor(annotationPtr, bgColor ?? "#FFFFFF", PdfAnnotationColorType.Color)) {\n return false;\n }\n return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);\n }\n /**\n * Set the rect of specified annotation\n * @param page - page info that the annotation is belonged to\n * @param pagePtr - pointer of page object\n * @param annotationPtr - pointer to annotation object\n * @param inkList - ink lists that added to the annotation\n * @returns whether the ink lists is setted\n *\n * @private\n */\n addInkStroke(doc, page, pagePtr, annotationPtr, annotation) {\n if (!this.setBorderStyle(annotationPtr, PdfAnnotationBorderStyle.SOLID, annotation.strokeWidth)) {\n return false;\n }\n if (!this.setInkList(doc, page, annotationPtr, annotation.inkList)) {\n return false;\n }\n if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {\n return false;\n }\n const strokeColor = annotation.strokeColor ?? annotation.color ?? "#FFFF00";\n if (!this.setAnnotationColor(annotationPtr, strokeColor, PdfAnnotationColorType.Color)) {\n return false;\n }\n return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);\n }\n /**\n * Add line content to annotation\n * @param page - page info\n * @param pagePtr - pointer to page object\n * @param annotationPtr - pointer to line annotation\n * @param annotation - line annotation\n * @returns whether line content is added to annotation\n *\n * @private\n */\n addLineContent(doc, page, pagePtr, annotationPtr, annotation) {\n var _a, _b;\n if (!this.setLinePoints(\n doc,\n page,\n annotationPtr,\n annotation.linePoints.start,\n annotation.linePoints.end\n )) {\n return false;\n }\n if (!this.setLineEndings(\n annotationPtr,\n ((_a = annotation.lineEndings) == null ? void 0 : _a.start) ?? PdfAnnotationLineEnding.None,\n ((_b = annotation.lineEndings) == null ? void 0 : _b.end) ?? PdfAnnotationLineEnding.None\n )) {\n return false;\n }\n if (!this.setBorderStyle(annotationPtr, annotation.strokeStyle, annotation.strokeWidth)) {\n return false;\n }\n if (!this.setBorderDashPattern(annotationPtr, annotation.strokeDashArray ?? [])) {\n return false;\n }\n if (annotation.intent && !this.setAnnotIntent(annotationPtr, annotation.intent)) {\n return false;\n }\n if (!annotation.color || annotation.color === "transparent") {\n if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.InteriorColor)) {\n return false;\n }\n } else if (!this.setAnnotationColor(\n annotationPtr,\n annotation.color ?? "#FFFF00",\n PdfAnnotationColorType.InteriorColor\n )) {\n return false;\n }\n if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {\n return false;\n }\n if (!this.setAnnotationColor(\n annotationPtr,\n annotation.strokeColor ?? "#FFFF00",\n PdfAnnotationColorType.Color\n )) {\n return false;\n }\n return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);\n }\n /**\n * Add polygon or polyline content to annotation\n * @param page - page info\n * @param pagePtr - pointer to page object\n * @param annotationPtr - pointer to polygon or polyline annotation\n * @param annotation - polygon or polyline annotation\n * @returns whether polygon or polyline content is added to annotation\n *\n * @private\n */\n addPolyContent(doc, page, pagePtr, annotationPtr, annotation) {\n var _a, _b;\n if (annotation.type === PdfAnnotationSubtype.POLYLINE && !this.setLineEndings(\n annotationPtr,\n ((_a = annotation.lineEndings) == null ? void 0 : _a.start) ?? PdfAnnotationLineEnding.None,\n ((_b = annotation.lineEndings) == null ? void 0 : _b.end) ?? PdfAnnotationLineEnding.None\n )) {\n return false;\n }\n if (!this.setPdfAnnoVertices(doc, page, annotationPtr, annotation.vertices)) {\n return false;\n }\n if (!this.setBorderStyle(annotationPtr, annotation.strokeStyle, annotation.strokeWidth)) {\n return false;\n }\n if (!this.setBorderDashPattern(annotationPtr, annotation.strokeDashArray ?? [])) {\n return false;\n }\n if (annotation.intent && !this.setAnnotIntent(annotationPtr, annotation.intent)) {\n return false;\n }\n if (!annotation.color || annotation.color === "transparent") {\n if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.InteriorColor)) {\n return false;\n }\n } else if (!this.setAnnotationColor(\n annotationPtr,\n annotation.color ?? "#FFFF00",\n PdfAnnotationColorType.InteriorColor\n )) {\n return false;\n }\n if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {\n return false;\n }\n if (!this.setAnnotationColor(\n annotationPtr,\n annotation.strokeColor ?? "#FFFF00",\n PdfAnnotationColorType.Color\n )) {\n return false;\n }\n return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);\n }\n /**\n * Add link content (action or destination) to a link annotation\n * @param docPtr - pointer to pdf document\n * @param pagePtr - pointer to the page\n * @param annotationPtr - pointer to pdf annotation\n * @param annotation - the link annotation object\n * @returns true if successful\n *\n * @private\n */\n addLinkContent(doc, page, docPtr, pagePtr, annotationPtr, annotation) {\n const style = annotation.strokeStyle ?? PdfAnnotationBorderStyle.UNDERLINE;\n const width = annotation.strokeWidth ?? 2;\n if (!this.setBorderStyle(annotationPtr, style, width)) {\n return false;\n }\n if (annotation.strokeDashArray && !this.setBorderDashPattern(annotationPtr, annotation.strokeDashArray)) {\n return false;\n }\n if (annotation.strokeColor) {\n if (!this.setAnnotationColor(\n annotationPtr,\n annotation.strokeColor,\n PdfAnnotationColorType.Color\n )) {\n return false;\n }\n }\n if (annotation.target) {\n if (!this.applyLinkTarget(docPtr, annotationPtr, annotation.target)) {\n return false;\n }\n }\n return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);\n }\n /**\n * Add shape content to annotation\n * @param page - page info\n * @param pagePtr - pointer to page object\n * @param annotationPtr - pointer to shape annotation\n * @param annotation - shape annotation\n * @returns whether shape content is added to annotation\n *\n * @private\n */\n addShapeContent(doc, page, pagePtr, annotationPtr, annotation) {\n if (!this.setBorderStyle(annotationPtr, annotation.strokeStyle, annotation.strokeWidth)) {\n return false;\n }\n if (!this.setBorderDashPattern(annotationPtr, annotation.strokeDashArray ?? [])) {\n return false;\n }\n if (!annotation.color || annotation.color === "transparent") {\n if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.InteriorColor)) {\n return false;\n }\n } else if (!this.setAnnotationColor(\n annotationPtr,\n annotation.color ?? "#FFFF00",\n PdfAnnotationColorType.InteriorColor\n )) {\n return false;\n }\n if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {\n return false;\n }\n if (!this.setAnnotationColor(\n annotationPtr,\n annotation.strokeColor ?? "#FFFF00",\n PdfAnnotationColorType.Color\n )) {\n return false;\n }\n return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);\n }\n /**\n * Add highlight content to annotation\n * @param page - page info\n * @param annotationPtr - pointer to highlight annotation\n * @param annotation - highlight annotation\n * @returns whether highlight content is added to annotation\n *\n * @private\n */\n addTextMarkupContent(doc, page, pagePtr, annotationPtr, annotation) {\n if (!this.syncQuadPointsAnno(doc, page, annotationPtr, annotation.segmentRects)) {\n return false;\n }\n if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {\n return false;\n }\n const strokeColor = annotation.strokeColor ?? annotation.color ?? "#FFFF00";\n if (!this.setAnnotationColor(annotationPtr, strokeColor, PdfAnnotationColorType.Color)) {\n return false;\n }\n return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);\n }\n /**\n * Add content to redact annotation\n * @param page - page info\n * @param pagePtr - pointer to page object\n * @param annotationPtr - pointer to redact annotation\n * @param annotation - redact annotation\n * @returns whether redact content is added to annotation\n *\n * @private\n */\n addRedactContent(doc, page, pagePtr, annotationPtr, annotation) {\n if (!this.syncQuadPointsAnno(doc, page, annotationPtr, annotation.segmentRects)) {\n return false;\n }\n if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {\n return false;\n }\n if (!annotation.color || annotation.color === "transparent") {\n if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.InteriorColor)) {\n return false;\n }\n } else if (!this.setAnnotationColor(\n annotationPtr,\n annotation.color,\n PdfAnnotationColorType.InteriorColor\n )) {\n return false;\n }\n if (!annotation.overlayColor || annotation.overlayColor === "transparent") {\n if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.OverlayColor)) {\n return false;\n }\n } else if (!this.setAnnotationColor(\n annotationPtr,\n annotation.overlayColor,\n PdfAnnotationColorType.OverlayColor\n )) {\n return false;\n }\n if (!annotation.strokeColor || annotation.strokeColor === "transparent") {\n if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.Color)) {\n return false;\n }\n } else if (!this.setAnnotationColor(annotationPtr, annotation.strokeColor, PdfAnnotationColorType.Color)) {\n return false;\n }\n if (!this.setOverlayText(annotationPtr, annotation.overlayText)) {\n return false;\n }\n if (annotation.overlayTextRepeat !== void 0 && !this.setOverlayTextRepeat(annotationPtr, annotation.overlayTextRepeat)) {\n return false;\n }\n if (annotation.fontFamily !== void 0 || annotation.fontSize !== void 0) {\n if (!this.setAnnotationDefaultAppearance(\n annotationPtr,\n annotation.fontFamily ?? PdfStandardFont.Helvetica,\n annotation.fontSize ?? 12,\n annotation.fontColor ?? "#000000"\n )) {\n return false;\n }\n }\n if (annotation.textAlign !== void 0 && !this.setAnnotationTextAlignment(annotationPtr, annotation.textAlign)) {\n return false;\n }\n return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);\n }\n /**\n * Add contents to stamp annotation\n * @param doc - pdf document object\n * @param docPtr - pointer to pdf document object\n * @param page - page info\n * @param pagePtr - pointer to page object\n * @param annotationPtr - pointer to stamp annotation\n * @param rect - rect of stamp annotation\n * @param contents - contents of stamp annotation\n * @returns whether contents is added to annotation\n *\n * @private\n */\n addStampContent(doc, docPtr, page, pagePtr, annotationPtr, annotation, imageData) {\n if (annotation.icon && !this.setAnnotationIcon(annotationPtr, annotation.icon)) {\n return false;\n }\n if (annotation.subject && !this.setAnnotString(annotationPtr, "Subj", annotation.subject)) {\n return false;\n }\n if (imageData) {\n for (let i = this.pdfiumModule.FPDFAnnot_GetObjectCount(annotationPtr) - 1; i >= 0; i--) {\n this.pdfiumModule.FPDFAnnot_RemoveObject(annotationPtr, i);\n }\n if (!this.addImageObject(doc, docPtr, page, pagePtr, annotationPtr, annotation.rect, imageData)) {\n return false;\n }\n }\n if (!this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation)) {\n return false;\n }\n return !!this.pdfiumModule.EPDFAnnot_UpdateAppearanceToRect(annotationPtr, PdfStampFit.Cover);\n }\n /**\n * Add image object to annotation\n * @param doc - pdf document object\n * @param docPtr - pointer to pdf document object\n * @param page - page info\n * @param pagePtr - pointer to page object\n * @param annotationPtr - pointer to stamp annotation\n * @param position - position of image\n * @param imageData - data of image\n * @returns whether image is added to annotation\n *\n * @private\n */\n addImageObject(doc, docPtr, page, pagePtr, annotationPtr, rect, imageData) {\n const bytesPerPixel = 4;\n const pixelCount = imageData.width * imageData.height;\n const bitmapBufferPtr = this.memoryManager.malloc(bytesPerPixel * pixelCount);\n if (!bitmapBufferPtr) {\n return false;\n }\n for (let i = 0; i < pixelCount; i++) {\n const red = imageData.data[i * bytesPerPixel];\n const green = imageData.data[i * bytesPerPixel + 1];\n const blue = imageData.data[i * bytesPerPixel + 2];\n const alpha = imageData.data[i * bytesPerPixel + 3];\n this.pdfiumModule.pdfium.setValue(bitmapBufferPtr + i * bytesPerPixel, blue, "i8");\n this.pdfiumModule.pdfium.setValue(bitmapBufferPtr + i * bytesPerPixel + 1, green, "i8");\n this.pdfiumModule.pdfium.setValue(bitmapBufferPtr + i * bytesPerPixel + 2, red, "i8");\n this.pdfiumModule.pdfium.setValue(bitmapBufferPtr + i * bytesPerPixel + 3, alpha, "i8");\n }\n const format = 4;\n const bitmapPtr = this.pdfiumModule.FPDFBitmap_CreateEx(\n imageData.width,\n imageData.height,\n format,\n bitmapBufferPtr,\n 0\n );\n if (!bitmapPtr) {\n this.memoryManager.free(bitmapBufferPtr);\n return false;\n }\n const imageObjectPtr = this.pdfiumModule.FPDFPageObj_NewImageObj(docPtr);\n if (!imageObjectPtr) {\n this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);\n this.memoryManager.free(bitmapBufferPtr);\n return false;\n }\n if (!this.pdfiumModule.FPDFImageObj_SetBitmap(pagePtr, 0, imageObjectPtr, bitmapPtr)) {\n this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);\n this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);\n this.memoryManager.free(bitmapBufferPtr);\n return false;\n }\n const matrixPtr = this.memoryManager.malloc(6 * 4);\n this.pdfiumModule.pdfium.setValue(matrixPtr, imageData.width, "float");\n this.pdfiumModule.pdfium.setValue(matrixPtr + 4, 0, "float");\n this.pdfiumModule.pdfium.setValue(matrixPtr + 8, 0, "float");\n this.pdfiumModule.pdfium.setValue(matrixPtr + 12, imageData.height, "float");\n this.pdfiumModule.pdfium.setValue(matrixPtr + 16, 0, "float");\n this.pdfiumModule.pdfium.setValue(matrixPtr + 20, 0, "float");\n if (!this.pdfiumModule.FPDFPageObj_SetMatrix(imageObjectPtr, matrixPtr)) {\n this.memoryManager.free(matrixPtr);\n this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);\n this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);\n this.memoryManager.free(bitmapBufferPtr);\n return false;\n }\n this.memoryManager.free(matrixPtr);\n const pagePos = this.convertDevicePointToPagePoint(doc, page, {\n x: rect.origin.x,\n y: rect.origin.y + imageData.height\n // shift down by the image height\n });\n this.pdfiumModule.FPDFPageObj_Transform(imageObjectPtr, 1, 0, 0, 1, pagePos.x, pagePos.y);\n if (!this.pdfiumModule.FPDFAnnot_AppendObject(annotationPtr, imageObjectPtr)) {\n this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);\n this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);\n this.memoryManager.free(bitmapBufferPtr);\n return false;\n }\n this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);\n this.memoryManager.free(bitmapBufferPtr);\n return true;\n }\n /**\n * Save document to array buffer\n * @param docPtr - pointer to pdf document\n * @returns array buffer contains the pdf content\n *\n * @private\n */\n saveDocument(docPtr) {\n const writerPtr = this.pdfiumModule.PDFiumExt_OpenFileWriter();\n this.pdfiumModule.PDFiumExt_SaveAsCopy(docPtr, writerPtr);\n const size = this.pdfiumModule.PDFiumExt_GetFileWriterSize(writerPtr);\n const dataPtr = this.memoryManager.malloc(size);\n this.pdfiumModule.PDFiumExt_GetFileWriterData(writerPtr, dataPtr, size);\n const buffer = new ArrayBuffer(size);\n const view = new DataView(buffer);\n for (let i = 0; i < size; i++) {\n view.setInt8(i, this.pdfiumModule.pdfium.getValue(dataPtr + i, "i8"));\n }\n this.memoryManager.free(dataPtr);\n this.pdfiumModule.PDFiumExt_CloseFileWriter(writerPtr);\n return buffer;\n }\n /**\n * Read Catalog /Lang via EPDFCatalog_GetLanguage (UTF-16LE → JS string).\n * Returns:\n * null -> /Lang not present (getter returned 0) OR doc not open,\n * \'\' -> /Lang exists but is explicitly empty,\n * \'en\', \'en-US\', ... -> normal tag.\n *\n * Note: EPDFCatalog_GetLanguage lengths are BYTES (incl. trailing NUL).\n *\n * @private\n */\n readCatalogLanguage(docPtr) {\n const byteLen = this.pdfiumModule.EPDFCatalog_GetLanguage(docPtr, 0, 0) >>> 0;\n if (byteLen === 0) return null;\n if (byteLen === 2) return "";\n return readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => this.pdfiumModule.EPDFCatalog_GetLanguage(docPtr, buffer, bufferLength),\n this.pdfiumModule.pdfium.UTF16ToString,\n byteLen\n );\n }\n /**\n * Read metadata from pdf document\n * @param docPtr - pointer to pdf document\n * @param key - key of metadata field\n * @returns metadata value\n *\n * @private\n */\n readMetaText(docPtr, key) {\n const exists = !!this.pdfiumModule.EPDF_HasMetaText(docPtr, key);\n if (!exists) return null;\n const len = this.pdfiumModule.FPDF_GetMetaText(docPtr, key, 0, 0);\n if (len === 2) return "";\n return readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => this.pdfiumModule.FPDF_GetMetaText(docPtr, key, buffer, bufferLength),\n this.pdfiumModule.pdfium.UTF16ToString,\n len\n );\n }\n /**\n * Write metadata into the PDF\'s Info dictionary.\n * If `value` is null or empty string, the key is removed.\n * @param docPtr - pointer to pdf document\n * @param key - key of metadata field\n * @param value - value of metadata field\n * @returns whether metadata is written to the pdf document\n *\n * @private\n */\n setMetaText(docPtr, key, value) {\n if (value == null || value.length === 0) {\n const ok = this.pdfiumModule.EPDF_SetMetaText(docPtr, key, 0);\n return !!ok;\n }\n const bytes = 2 * (value.length + 1);\n const ptr = this.memoryManager.malloc(bytes);\n try {\n this.pdfiumModule.pdfium.stringToUTF16(value, ptr, bytes);\n const ok = this.pdfiumModule.EPDF_SetMetaText(docPtr, key, ptr);\n return !!ok;\n } finally {\n this.memoryManager.free(ptr);\n }\n }\n /**\n * Read the document\'s trapped status via PDFium.\n * Falls back to `Unknown` on unexpected values.\n *\n * @private\n */\n getMetaTrapped(docPtr) {\n const raw = Number(this.pdfiumModule.EPDF_GetMetaTrapped(docPtr));\n switch (raw) {\n case PdfTrappedStatus.NotSet:\n case PdfTrappedStatus.True:\n case PdfTrappedStatus.False:\n case PdfTrappedStatus.Unknown:\n return raw;\n default:\n return PdfTrappedStatus.Unknown;\n }\n }\n /**\n * Write (or clear) the document\'s trapped status via PDFium.\n * Pass `null`/`undefined` to remove the `/Trapped` key.\n *\n * @private\n */\n setMetaTrapped(docPtr, status) {\n const toSet = status == null || status === void 0 ? PdfTrappedStatus.NotSet : status;\n const valid = toSet === PdfTrappedStatus.NotSet || toSet === PdfTrappedStatus.True || toSet === PdfTrappedStatus.False || toSet === PdfTrappedStatus.Unknown;\n if (!valid) return false;\n return !!this.pdfiumModule.EPDF_SetMetaTrapped(docPtr, toSet);\n }\n /**\n * Get the number of keys in the document\'s Info dictionary.\n * @param docPtr - pointer to pdf document\n * @param customOnly - if true, only count non-reserved (custom) keys; if false, count all keys.\n * @returns the number of keys (possibly 0). On error, returns 0.\n *\n * @private\n */\n getMetaKeyCount(docPtr, customOnly) {\n return Number(this.pdfiumModule.EPDF_GetMetaKeyCount(docPtr, customOnly)) | 0;\n }\n /**\n * Get the name of the Info dictionary key at |index|.\n * @param docPtr - pointer to pdf document\n * @param index - 0-based key index in the order returned by PDFium.\n * @param customOnly - if true, indexes only over non-reserved (custom) keys; if false, indexes over all keys.\n * @returns the name of the key, or null if the key is not found.\n *\n * @private\n */\n getMetaKeyName(docPtr, index, customOnly) {\n const len = this.pdfiumModule.EPDF_GetMetaKeyName(docPtr, index, customOnly, 0, 0);\n if (!len) return null;\n return readString(\n this.pdfiumModule.pdfium,\n (buffer, buflen) => this.pdfiumModule.EPDF_GetMetaKeyName(docPtr, index, customOnly, buffer, buflen),\n this.pdfiumModule.pdfium.UTF8ToString,\n len\n );\n }\n /**\n * Read all metadata from the document\'s Info dictionary.\n * @param docPtr - pointer to pdf document\n * @param customOnly - if true, only read non-reserved (custom) keys; if false, read all keys.\n * @returns all metadata\n *\n * @private\n */\n readAllMeta(docPtr, customOnly = true) {\n const n = this.getMetaKeyCount(docPtr, customOnly);\n const out = {};\n for (let i = 0; i < n; i++) {\n const key = this.getMetaKeyName(docPtr, i, customOnly);\n if (!key) continue;\n out[key] = this.readMetaText(docPtr, key);\n }\n return out;\n }\n /**\n * Read bookmarks in the pdf document\n * @param docPtr - pointer to pdf document\n * @param rootBookmarkPtr - pointer to root bookmark\n * @returns bookmarks in the pdf document\n *\n * @private\n */\n readPdfBookmarks(docPtr, rootBookmarkPtr = 0) {\n let bookmarkPtr = this.pdfiumModule.FPDFBookmark_GetFirstChild(docPtr, rootBookmarkPtr);\n const bookmarks = [];\n while (bookmarkPtr) {\n const bookmark = this.readPdfBookmark(docPtr, bookmarkPtr);\n bookmarks.push(bookmark);\n const nextBookmarkPtr = this.pdfiumModule.FPDFBookmark_GetNextSibling(docPtr, bookmarkPtr);\n bookmarkPtr = nextBookmarkPtr;\n }\n return bookmarks;\n }\n /**\n * Read bookmark in the pdf document\n * @param docPtr - pointer to pdf document\n * @param bookmarkPtr - pointer to bookmark object\n * @returns pdf bookmark object\n *\n * @private\n */\n readPdfBookmark(docPtr, bookmarkPtr) {\n const title = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFBookmark_GetTitle(bookmarkPtr, buffer, bufferLength);\n },\n this.pdfiumModule.pdfium.UTF16ToString\n );\n const bookmarks = this.readPdfBookmarks(docPtr, bookmarkPtr);\n const target = this.readPdfBookmarkTarget(\n docPtr,\n () => {\n return this.pdfiumModule.FPDFBookmark_GetAction(bookmarkPtr);\n },\n () => {\n return this.pdfiumModule.FPDFBookmark_GetDest(docPtr, bookmarkPtr);\n }\n );\n return {\n title,\n target,\n children: bookmarks\n };\n }\n /**\n * Read text rects in pdf page\n * @param page - pdf page info\n * @param docPtr - pointer to pdf document\n * @param pagePtr - pointer to pdf page\n * @param textPagePtr - pointer to pdf text page\n * @returns text rects in the pdf page\n *\n * @public\n */\n readPageTextRects(page, docPtr, pagePtr, textPagePtr) {\n const rectsCount = this.pdfiumModule.FPDFText_CountRects(textPagePtr, 0, -1);\n const textRects = [];\n for (let i = 0; i < rectsCount; i++) {\n const topPtr = this.memoryManager.malloc(8);\n const leftPtr = this.memoryManager.malloc(8);\n const rightPtr = this.memoryManager.malloc(8);\n const bottomPtr = this.memoryManager.malloc(8);\n const isSucceed = this.pdfiumModule.FPDFText_GetRect(\n textPagePtr,\n i,\n leftPtr,\n topPtr,\n rightPtr,\n bottomPtr\n );\n if (!isSucceed) {\n this.memoryManager.free(leftPtr);\n this.memoryManager.free(topPtr);\n this.memoryManager.free(rightPtr);\n this.memoryManager.free(bottomPtr);\n continue;\n }\n const left = this.pdfiumModule.pdfium.getValue(leftPtr, "double");\n const top = this.pdfiumModule.pdfium.getValue(topPtr, "double");\n const right = this.pdfiumModule.pdfium.getValue(rightPtr, "double");\n const bottom = this.pdfiumModule.pdfium.getValue(bottomPtr, "double");\n this.memoryManager.free(leftPtr);\n this.memoryManager.free(topPtr);\n this.memoryManager.free(rightPtr);\n this.memoryManager.free(bottomPtr);\n const deviceXPtr = this.memoryManager.malloc(4);\n const deviceYPtr = this.memoryManager.malloc(4);\n this.pdfiumModule.FPDF_PageToDevice(\n pagePtr,\n 0,\n 0,\n page.size.width,\n page.size.height,\n 0,\n left,\n top,\n deviceXPtr,\n deviceYPtr\n );\n const x = this.pdfiumModule.pdfium.getValue(deviceXPtr, "i32");\n const y = this.pdfiumModule.pdfium.getValue(deviceYPtr, "i32");\n this.memoryManager.free(deviceXPtr);\n this.memoryManager.free(deviceYPtr);\n const rect = {\n origin: {\n x,\n y\n },\n size: {\n width: Math.ceil(Math.abs(right - left)),\n height: Math.ceil(Math.abs(top - bottom))\n }\n };\n const utf16Length = this.pdfiumModule.FPDFText_GetBoundedText(\n textPagePtr,\n left,\n top,\n right,\n bottom,\n 0,\n 0\n );\n const bytesCount = (utf16Length + 1) * 2;\n const textBuffer = this.memoryManager.malloc(bytesCount);\n this.pdfiumModule.FPDFText_GetBoundedText(\n textPagePtr,\n left,\n top,\n right,\n bottom,\n textBuffer,\n utf16Length\n );\n const content = this.pdfiumModule.pdfium.UTF16ToString(textBuffer);\n this.memoryManager.free(textBuffer);\n const charIndex = this.pdfiumModule.FPDFText_GetCharIndexAtPos(textPagePtr, left, top, 2, 2);\n let fontFamily = "";\n let fontSize = rect.size.height;\n if (charIndex >= 0) {\n fontSize = this.pdfiumModule.FPDFText_GetFontSize(textPagePtr, charIndex);\n const fontNameLength = this.pdfiumModule.FPDFText_GetFontInfo(\n textPagePtr,\n charIndex,\n 0,\n 0,\n 0\n );\n const bytesCount2 = fontNameLength + 1;\n const textBufferPtr = this.memoryManager.malloc(bytesCount2);\n const flagsPtr = this.memoryManager.malloc(4);\n this.pdfiumModule.FPDFText_GetFontInfo(\n textPagePtr,\n charIndex,\n textBufferPtr,\n bytesCount2,\n flagsPtr\n );\n fontFamily = this.pdfiumModule.pdfium.UTF8ToString(textBufferPtr);\n this.memoryManager.free(textBufferPtr);\n this.memoryManager.free(flagsPtr);\n }\n const textRect = {\n content,\n rect,\n font: {\n family: fontFamily,\n size: fontSize\n }\n };\n textRects.push(textRect);\n }\n return textRects;\n }\n /**\n * Return geometric + logical text layout for one page\n * (glyph-only implementation, no FPDFText_GetRect).\n *\n * @public\n */\n getPageGeometry(doc, page) {\n const label = "getPageGeometry";\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const textPagePtr = pageCtx.getTextPage();\n const glyphCount = this.pdfiumModule.FPDFText_CountChars(textPagePtr);\n const glyphs = [];\n for (let i = 0; i < glyphCount; i++) {\n const g = this.readGlyphInfo(page, pageCtx.pagePtr, textPagePtr, i);\n glyphs.push(g);\n }\n const runs = this.buildRunsFromGlyphs(glyphs, textPagePtr);\n pageCtx.release();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", doc.id);\n return PdfTaskHelper.resolve({ runs });\n }\n /**\n * Group consecutive glyphs that belong to the same CPDF_TextObject\n * using FPDFText_GetTextObject(), and calculate rotation from glyph positions.\n */\n buildRunsFromGlyphs(glyphs, textPagePtr) {\n const runs = [];\n let current = null;\n let curObjPtr = null;\n let bounds = null;\n for (let i = 0; i < glyphs.length; i++) {\n const g = glyphs[i];\n const objPtr = this.pdfiumModule.FPDFText_GetTextObject(textPagePtr, i);\n if (objPtr !== curObjPtr) {\n curObjPtr = objPtr;\n current = {\n rect: {\n x: g.origin.x,\n y: g.origin.y,\n width: g.size.width,\n height: g.size.height\n },\n charStart: i,\n glyphs: [],\n fontSize: this.pdfiumModule.FPDFText_GetFontSize(textPagePtr, i)\n };\n bounds = {\n minX: g.origin.x,\n minY: g.origin.y,\n maxX: g.origin.x + g.size.width,\n maxY: g.origin.y + g.size.height\n };\n runs.push(current);\n }\n current.glyphs.push({\n x: g.origin.x,\n y: g.origin.y,\n width: g.size.width,\n height: g.size.height,\n flags: g.isEmpty ? 2 : g.isSpace ? 1 : 0,\n ...g.tightOrigin && { tightX: g.tightOrigin.x, tightY: g.tightOrigin.y },\n ...g.tightSize && { tightWidth: g.tightSize.width, tightHeight: g.tightSize.height }\n });\n if (g.isEmpty) {\n continue;\n }\n const right = g.origin.x + g.size.width;\n const bottom = g.origin.y + g.size.height;\n bounds.minX = Math.min(bounds.minX, g.origin.x);\n bounds.minY = Math.min(bounds.minY, g.origin.y);\n bounds.maxX = Math.max(bounds.maxX, right);\n bounds.maxY = Math.max(bounds.maxY, bottom);\n current.rect.x = bounds.minX;\n current.rect.y = bounds.minY;\n current.rect.width = bounds.maxX - bounds.minX;\n current.rect.height = bounds.maxY - bounds.minY;\n }\n return runs;\n }\n /**\n * Rich text runs: groups consecutive characters sharing the same\n * text object, font, size, and fill color into structured segments\n * with full font metadata and bounding boxes in PDF page coordinates.\n *\n * @public\n */\n getPageTextRuns(doc, page) {\n const label = "getPageTextRuns";\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const textPagePtr = pageCtx.getTextPage();\n const charCount = this.pdfiumModule.FPDFText_CountChars(textPagePtr);\n const runs = [];\n let runStart = 0;\n let curObjPtr = null;\n let curFont = null;\n let curFontSize = 0;\n let curColor = null;\n let bounds = null;\n const flushRun = (end) => {\n if (curObjPtr === null || curFont === null || curColor === null || bounds === null) return;\n const count = end - runStart;\n if (count <= 0) return;\n const bufPtr = this.memoryManager.malloc(2 * (count + 1));\n this.pdfiumModule.FPDFText_GetText(textPagePtr, runStart, count, bufPtr);\n const text = stripPdfUnwantedMarkers(this.pdfiumModule.pdfium.UTF16ToString(bufPtr));\n this.memoryManager.free(bufPtr);\n runs.push({\n text,\n rect: {\n origin: { x: bounds.minX, y: bounds.minY },\n size: {\n width: Math.max(1, bounds.maxX - bounds.minX),\n height: Math.max(1, bounds.maxY - bounds.minY)\n }\n },\n font: curFont,\n fontSize: curFontSize,\n color: curColor,\n charIndex: runStart,\n charCount: count\n });\n };\n const rPtr = this.memoryManager.malloc(4);\n const gPtr = this.memoryManager.malloc(4);\n const bPtr = this.memoryManager.malloc(4);\n const aPtr = this.memoryManager.malloc(4);\n const rectPtr = this.memoryManager.malloc(16);\n const dx1Ptr = this.memoryManager.malloc(4);\n const dy1Ptr = this.memoryManager.malloc(4);\n const dx2Ptr = this.memoryManager.malloc(4);\n const dy2Ptr = this.memoryManager.malloc(4);\n const italicAnglePtr = this.memoryManager.malloc(4);\n for (let i = 0; i < charCount; i++) {\n const uc = this.pdfiumModule.FPDFText_GetUnicode(textPagePtr, i);\n if (uc === 65534 || uc === 65533) continue;\n const objPtr = this.pdfiumModule.FPDFText_GetTextObject(textPagePtr, i);\n if (objPtr === 0) continue;\n const fontSize = this.pdfiumModule.FPDFText_GetFontSize(textPagePtr, i);\n this.pdfiumModule.FPDFText_GetFillColor(textPagePtr, i, rPtr, gPtr, bPtr, aPtr);\n const red = this.pdfiumModule.pdfium.getValue(rPtr, "i32") & 255;\n const green = this.pdfiumModule.pdfium.getValue(gPtr, "i32") & 255;\n const blue = this.pdfiumModule.pdfium.getValue(bPtr, "i32") & 255;\n const alpha = this.pdfiumModule.pdfium.getValue(aPtr, "i32") & 255;\n const fontInfo = this.readFontInfoFromTextObject(objPtr, italicAnglePtr);\n const needNewRun = curObjPtr === null || objPtr !== curObjPtr || fontInfo.name !== curFont.name || Math.abs(fontSize - curFontSize) > 0.01 || red !== curColor.red || green !== curColor.green || blue !== curColor.blue;\n if (needNewRun) {\n flushRun(i);\n curObjPtr = objPtr;\n curFont = fontInfo;\n curFontSize = fontSize;\n curColor = { red, green, blue, alpha };\n runStart = i;\n bounds = null;\n }\n if (this.pdfiumModule.FPDFText_GetLooseCharBox(textPagePtr, i, rectPtr)) {\n const left = this.pdfiumModule.pdfium.getValue(rectPtr, "float");\n const top = this.pdfiumModule.pdfium.getValue(rectPtr + 4, "float");\n const right = this.pdfiumModule.pdfium.getValue(rectPtr + 8, "float");\n const bottom = this.pdfiumModule.pdfium.getValue(rectPtr + 12, "float");\n if (left !== right && top !== bottom) {\n this.pdfiumModule.FPDF_PageToDevice(\n pageCtx.pagePtr,\n 0,\n 0,\n page.size.width,\n page.size.height,\n 0,\n left,\n top,\n dx1Ptr,\n dy1Ptr\n );\n this.pdfiumModule.FPDF_PageToDevice(\n pageCtx.pagePtr,\n 0,\n 0,\n page.size.width,\n page.size.height,\n 0,\n right,\n bottom,\n dx2Ptr,\n dy2Ptr\n );\n const x1 = this.pdfiumModule.pdfium.getValue(dx1Ptr, "i32");\n const y1 = this.pdfiumModule.pdfium.getValue(dy1Ptr, "i32");\n const x2 = this.pdfiumModule.pdfium.getValue(dx2Ptr, "i32");\n const y2 = this.pdfiumModule.pdfium.getValue(dy2Ptr, "i32");\n const cx = Math.min(x1, x2);\n const cy = Math.min(y1, y2);\n const cw = Math.abs(x2 - x1);\n const ch = Math.abs(y2 - y1);\n if (bounds === null) {\n bounds = { minX: cx, minY: cy, maxX: cx + cw, maxY: cy + ch };\n } else {\n bounds.minX = Math.min(bounds.minX, cx);\n bounds.minY = Math.min(bounds.minY, cy);\n bounds.maxX = Math.max(bounds.maxX, cx + cw);\n bounds.maxY = Math.max(bounds.maxY, cy + ch);\n }\n }\n }\n }\n flushRun(charCount);\n [rPtr, gPtr, bPtr, aPtr, rectPtr, dx1Ptr, dy1Ptr, dx2Ptr, dy2Ptr, italicAnglePtr].forEach(\n (p) => this.memoryManager.free(p)\n );\n pageCtx.release();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", doc.id);\n return PdfTaskHelper.resolve({ runs });\n }\n /**\n * Read font metadata from a text object handle via FPDFFont_* APIs.\n */\n readFontInfoFromTextObject(textObjPtr, italicAnglePtr) {\n const fontPtr = this.pdfiumModule.FPDFTextObj_GetFont(textObjPtr);\n let name = "";\n let familyName = "";\n let weight = 400;\n let italic = false;\n let monospaced = false;\n let embedded = false;\n if (fontPtr) {\n const nameLen = this.pdfiumModule.FPDFFont_GetBaseFontName(fontPtr, 0, 0);\n if (nameLen > 0) {\n const nameBuf = this.memoryManager.malloc(nameLen + 1);\n this.pdfiumModule.FPDFFont_GetBaseFontName(fontPtr, nameBuf, nameLen + 1);\n name = this.pdfiumModule.pdfium.UTF8ToString(nameBuf);\n this.memoryManager.free(nameBuf);\n }\n const famLen = this.pdfiumModule.FPDFFont_GetFamilyName(fontPtr, 0, 0);\n if (famLen > 0) {\n const famBuf = this.memoryManager.malloc(famLen + 1);\n this.pdfiumModule.FPDFFont_GetFamilyName(fontPtr, famBuf, famLen + 1);\n familyName = this.pdfiumModule.pdfium.UTF8ToString(famBuf);\n this.memoryManager.free(famBuf);\n }\n weight = this.pdfiumModule.FPDFFont_GetWeight(fontPtr);\n embedded = this.pdfiumModule.FPDFFont_GetIsEmbedded(fontPtr) !== 0;\n if (this.pdfiumModule.FPDFFont_GetItalicAngle(fontPtr, italicAnglePtr)) {\n const angle = this.pdfiumModule.pdfium.getValue(italicAnglePtr, "i32");\n italic = angle !== 0;\n }\n const flags = this.pdfiumModule.FPDFFont_GetFlags(fontPtr);\n monospaced = (flags & 1) !== 0;\n }\n return { name, familyName, weight, italic, monospaced, embedded };\n }\n /**\n * Extract glyph geometry + metadata for `charIndex`\n *\n * Returns device–space coordinates:\n * x,y → **top-left** corner (integer-pixels)\n * w,h → width / height (integer-pixels, ≥ 1)\n *\n * And two flags:\n * isSpace → true if the glyph\'s Unicode code-point is U+0020\n */\n readGlyphInfo(page, pagePtr, textPagePtr, charIndex) {\n const dx1Ptr = this.memoryManager.malloc(4);\n const dy1Ptr = this.memoryManager.malloc(4);\n const dx2Ptr = this.memoryManager.malloc(4);\n const dy2Ptr = this.memoryManager.malloc(4);\n const rectPtr = this.memoryManager.malloc(16);\n const tLeftPtr = this.memoryManager.malloc(8);\n const tRightPtr = this.memoryManager.malloc(8);\n const tBottomPtr = this.memoryManager.malloc(8);\n const tTopPtr = this.memoryManager.malloc(8);\n const allPtrs = [\n rectPtr,\n dx1Ptr,\n dy1Ptr,\n dx2Ptr,\n dy2Ptr,\n tLeftPtr,\n tRightPtr,\n tBottomPtr,\n tTopPtr\n ];\n let x = 0, y = 0, width = 0, height = 0, isSpace = false;\n let tightOrigin;\n let tightSize;\n if (this.pdfiumModule.FPDFText_GetLooseCharBox(textPagePtr, charIndex, rectPtr)) {\n const left = this.pdfiumModule.pdfium.getValue(rectPtr, "float");\n const top = this.pdfiumModule.pdfium.getValue(rectPtr + 4, "float");\n const right = this.pdfiumModule.pdfium.getValue(rectPtr + 8, "float");\n const bottom = this.pdfiumModule.pdfium.getValue(rectPtr + 12, "float");\n if (left === right || top === bottom) {\n allPtrs.forEach((p) => this.memoryManager.free(p));\n return {\n origin: { x: 0, y: 0 },\n size: { width: 0, height: 0 },\n isEmpty: true\n };\n }\n this.pdfiumModule.FPDF_PageToDevice(\n pagePtr,\n 0,\n 0,\n page.size.width,\n page.size.height,\n 0,\n left,\n top,\n dx1Ptr,\n dy1Ptr\n );\n this.pdfiumModule.FPDF_PageToDevice(\n pagePtr,\n 0,\n 0,\n page.size.width,\n page.size.height,\n 0,\n right,\n bottom,\n dx2Ptr,\n dy2Ptr\n );\n const x1 = this.pdfiumModule.pdfium.getValue(dx1Ptr, "i32");\n const y1 = this.pdfiumModule.pdfium.getValue(dy1Ptr, "i32");\n const x2 = this.pdfiumModule.pdfium.getValue(dx2Ptr, "i32");\n const y2 = this.pdfiumModule.pdfium.getValue(dy2Ptr, "i32");\n x = Math.min(x1, x2);\n y = Math.min(y1, y2);\n width = Math.max(1, Math.abs(x2 - x1));\n height = Math.max(1, Math.abs(y2 - y1));\n if (this.pdfiumModule.FPDFText_GetCharBox(\n textPagePtr,\n charIndex,\n tLeftPtr,\n tRightPtr,\n tBottomPtr,\n tTopPtr\n )) {\n const tLeft = this.pdfiumModule.pdfium.getValue(tLeftPtr, "double");\n const tRight = this.pdfiumModule.pdfium.getValue(tRightPtr, "double");\n const tBottom = this.pdfiumModule.pdfium.getValue(tBottomPtr, "double");\n const tTop = this.pdfiumModule.pdfium.getValue(tTopPtr, "double");\n this.pdfiumModule.FPDF_PageToDevice(\n pagePtr,\n 0,\n 0,\n page.size.width,\n page.size.height,\n 0,\n tLeft,\n tTop,\n dx1Ptr,\n dy1Ptr\n );\n this.pdfiumModule.FPDF_PageToDevice(\n pagePtr,\n 0,\n 0,\n page.size.width,\n page.size.height,\n 0,\n tRight,\n tBottom,\n dx2Ptr,\n dy2Ptr\n );\n const tx1 = this.pdfiumModule.pdfium.getValue(dx1Ptr, "i32");\n const ty1 = this.pdfiumModule.pdfium.getValue(dy1Ptr, "i32");\n const tx2 = this.pdfiumModule.pdfium.getValue(dx2Ptr, "i32");\n const ty2 = this.pdfiumModule.pdfium.getValue(dy2Ptr, "i32");\n tightOrigin = { x: Math.min(tx1, tx2), y: Math.min(ty1, ty2) };\n tightSize = {\n width: Math.max(1, Math.abs(tx2 - tx1)),\n height: Math.max(1, Math.abs(ty2 - ty1))\n };\n }\n const uc = this.pdfiumModule.FPDFText_GetUnicode(textPagePtr, charIndex);\n isSpace = uc === 32;\n }\n allPtrs.forEach((p) => this.memoryManager.free(p));\n return {\n origin: { x, y },\n size: { width, height },\n ...tightOrigin && { tightOrigin },\n ...tightSize && { tightSize },\n ...isSpace && { isSpace }\n };\n }\n /**\n * Geometry-only text extraction\n * ------------------------------------------\n * Returns every glyph on the requested page\n * in the logical order delivered by PDFium.\n *\n * The promise resolves to an array of objects:\n * {\n * idx: number; // glyph index on the page (0…n-1)\n * origin: { x: number; y: number };\n * size: { width: number; height: number };\n * angle: number; // degrees, counter-clock-wise\n * isSpace: boolean; // true → U+0020\n * }\n *\n * No Unicode is included; front-end decides whether to hydrate it.\n */\n getPageGlyphs(doc, page) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageGlyphs", doc, page);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageGlyphs", "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageGlyphs", "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const textPagePtr = pageCtx.getTextPage();\n const total = this.pdfiumModule.FPDFText_CountChars(textPagePtr);\n const glyphs = new Array(total);\n for (let i = 0; i < total; i++) {\n const g = this.readGlyphInfo(page, pageCtx.pagePtr, textPagePtr, i);\n if (g.isEmpty) {\n continue;\n }\n glyphs[i] = { ...g };\n }\n pageCtx.release();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageGlyphs", "End", doc.id);\n return PdfTaskHelper.resolve(glyphs);\n }\n readCharBox(page, pagePtr, textPagePtr, charIndex) {\n const topPtr = this.memoryManager.malloc(8);\n const leftPtr = this.memoryManager.malloc(8);\n const bottomPtr = this.memoryManager.malloc(8);\n const rightPtr = this.memoryManager.malloc(8);\n let x = 0;\n let y = 0;\n let width = 0;\n let height = 0;\n if (this.pdfiumModule.FPDFText_GetCharBox(\n textPagePtr,\n charIndex,\n leftPtr,\n rightPtr,\n bottomPtr,\n topPtr\n )) {\n const top = this.pdfiumModule.pdfium.getValue(topPtr, "double");\n const left = this.pdfiumModule.pdfium.getValue(leftPtr, "double");\n const bottom = this.pdfiumModule.pdfium.getValue(bottomPtr, "double");\n const right = this.pdfiumModule.pdfium.getValue(rightPtr, "double");\n const deviceXPtr = this.memoryManager.malloc(4);\n const deviceYPtr = this.memoryManager.malloc(4);\n this.pdfiumModule.FPDF_PageToDevice(\n pagePtr,\n 0,\n 0,\n page.size.width,\n page.size.height,\n 0,\n left,\n top,\n deviceXPtr,\n deviceYPtr\n );\n x = this.pdfiumModule.pdfium.getValue(deviceXPtr, "i32");\n y = this.pdfiumModule.pdfium.getValue(deviceYPtr, "i32");\n this.memoryManager.free(deviceXPtr);\n this.memoryManager.free(deviceYPtr);\n width = Math.ceil(Math.abs(right - left));\n height = Math.ceil(Math.abs(top - bottom));\n }\n this.memoryManager.free(topPtr);\n this.memoryManager.free(leftPtr);\n this.memoryManager.free(bottomPtr);\n this.memoryManager.free(rightPtr);\n return {\n origin: {\n x,\n y\n },\n size: {\n width,\n height\n }\n };\n }\n /**\n * Read page annotations\n *\n * @param doc - pdf document object\n * @param ctx - document context\n * @param page - page info\n * @returns annotations on the pdf page\n *\n * @private\n */\n readPageAnnotations(doc, ctx, page) {\n return ctx.borrowPage(page.index, (pageCtx) => {\n const annotationCount = this.pdfiumModule.FPDFPage_GetAnnotCount(pageCtx.pagePtr);\n const annotations = [];\n for (let i = 0; i < annotationCount; i++) {\n pageCtx.withAnnotation(i, (annotPtr) => {\n const anno = this.readPageAnnotation(doc, ctx.docPtr, page, annotPtr, pageCtx);\n if (anno) annotations.push(anno);\n });\n }\n return annotations;\n });\n }\n /**\n * Read page annotations without loading the page (raw approach)\n *\n * @param doc - pdf document object\n * @param ctx - document context\n * @param page - page info\n * @returns annotations on the pdf page\n *\n * @private\n */\n readPageAnnotationsRaw(doc, ctx, page) {\n const count = this.pdfiumModule.EPDFPage_GetAnnotCountRaw(ctx.docPtr, page.index);\n if (count <= 0) return [];\n const out = [];\n for (let i = 0; i < count; ++i) {\n const annotPtr = this.pdfiumModule.EPDFPage_GetAnnotRaw(ctx.docPtr, page.index, i);\n if (!annotPtr) continue;\n try {\n const anno = this.readPageAnnotation(doc, ctx.docPtr, page, annotPtr);\n if (anno) out.push(anno);\n } finally {\n this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);\n }\n }\n return out;\n }\n /**\n * Get page annotations (public API, returns Task)\n *\n * @param doc - pdf document\n * @param page - page info\n * @returns task with annotations on the pdf page\n *\n * @public\n */\n getPageAnnotationsRaw(doc, page) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageAnnotationsRaw", doc, page);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `GetPageAnnotationsRaw`,\n "Begin",\n `${doc.id}-${page.index}`\n );\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const out = this.readPageAnnotationsRaw(doc, ctx, page);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `GetPageAnnotationsRaw`,\n "End",\n `${doc.id}-${page.index}`\n );\n this.logger.debug(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "getPageAnnotationsRaw",\n `${doc.id}-${page.index}`,\n out\n );\n return PdfTaskHelper.resolve(out);\n }\n /**\n * Read pdf annotation from pdf document\n *\n * @param doc - pdf document object\n * @param docPtr - pointer to pdf document\n * @param page - page info\n * @param annotationPtr - pointer to pdf annotation\n * @param pageCtx - page context\n * @returns pdf annotation\n *\n * @private\n */\n readPageAnnotation(doc, docPtr, page, annotationPtr, pageCtx) {\n let index = this.getAnnotString(annotationPtr, "NM");\n if (!index || !isUuidV4(index)) {\n index = uuidV4();\n this.setAnnotString(annotationPtr, "NM", index);\n }\n const subType = this.pdfiumModule.FPDFAnnot_GetSubtype(\n annotationPtr\n );\n let annotation;\n switch (subType) {\n case PdfAnnotationSubtype.TEXT:\n {\n annotation = this.readPdfTextAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.FREETEXT:\n {\n annotation = this.readPdfFreeTextAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.LINK:\n {\n annotation = this.readPdfLinkAnno(doc, page, docPtr, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.WIDGET:\n if (pageCtx) {\n return this.readPdfWidgetAnno(doc, page, annotationPtr, pageCtx.getFormHandle(), index);\n }\n case PdfAnnotationSubtype.FILEATTACHMENT:\n {\n annotation = this.readPdfFileAttachmentAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.INK:\n {\n annotation = this.readPdfInkAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.POLYGON:\n {\n annotation = this.readPdfPolygonAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.POLYLINE:\n {\n annotation = this.readPdfPolylineAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.LINE:\n {\n annotation = this.readPdfLineAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.HIGHLIGHT:\n annotation = this.readPdfHighlightAnno(doc, page, annotationPtr, index);\n break;\n case PdfAnnotationSubtype.STAMP:\n {\n annotation = this.readPdfStampAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.SQUARE:\n {\n annotation = this.readPdfSquareAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.CIRCLE:\n {\n annotation = this.readPdfCircleAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.UNDERLINE:\n {\n annotation = this.readPdfUnderlineAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.SQUIGGLY:\n {\n annotation = this.readPdfSquigglyAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.STRIKEOUT:\n {\n annotation = this.readPdfStrikeOutAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.CARET:\n {\n annotation = this.readPdfCaretAnno(doc, page, annotationPtr, index);\n }\n break;\n case PdfAnnotationSubtype.REDACT:\n {\n annotation = this.readPdfRedactAnno(doc, page, annotationPtr, index);\n }\n break;\n default:\n {\n annotation = this.readPdfAnno(doc, page, subType, annotationPtr, index);\n }\n break;\n }\n if (annotation) {\n annotation = this.reverseRotateAnnotationOnLoad(annotation);\n }\n return annotation;\n }\n /**\n * On load, if a vertex-type annotation has rotation metadata in EPDFCustom,\n * reverse-rotate the PDF\'s physically rotated vertices by -rotation to recover\n * the unrotated vertices for runtime editing.\n */\n reverseRotateAnnotationOnLoad(annotation) {\n const rotation = annotation.rotation;\n const unrotatedRect = annotation.unrotatedRect;\n if (!rotation || rotation === 0 || !unrotatedRect) {\n return annotation;\n }\n const center = {\n x: unrotatedRect.origin.x + unrotatedRect.size.width / 2,\n y: unrotatedRect.origin.y + unrotatedRect.size.height / 2\n };\n switch (annotation.type) {\n case PdfAnnotationSubtype.INK: {\n const ink = annotation;\n const unrotatedInkList = ink.inkList.map((stroke) => ({\n points: stroke.points.map((p) => this.rotatePointForSave(p, center, -rotation))\n }));\n return { ...ink, inkList: unrotatedInkList };\n }\n case PdfAnnotationSubtype.LINE: {\n const line = annotation;\n return {\n ...line,\n linePoints: {\n start: this.rotatePointForSave(line.linePoints.start, center, -rotation),\n end: this.rotatePointForSave(line.linePoints.end, center, -rotation)\n }\n };\n }\n case PdfAnnotationSubtype.POLYGON: {\n const poly = annotation;\n return {\n ...poly,\n vertices: poly.vertices.map((v) => this.rotatePointForSave(v, center, -rotation))\n };\n }\n case PdfAnnotationSubtype.POLYLINE: {\n const polyline = annotation;\n return {\n ...polyline,\n vertices: polyline.vertices.map((v) => this.rotatePointForSave(v, center, -rotation))\n };\n }\n default:\n return annotation;\n }\n }\n /**\n * Return the colour stored directly in the annotation dictionary\'s `/C` entry.\n *\n * Most PDFs created by Acrobat, Microsoft Office, LaTeX, etc. include this entry.\n * When the key is absent (common in macOS Preview, Chrome, Drawboard) the call\n * fails and the function returns `undefined`.\n *\n * @param annotationPtr - pointer to an `FPDF_ANNOTATION`\n * @returns An RGBA tuple (0-255 channels) or `undefined` if no `/C` entry exists\n *\n * @private\n */\n readAnnotationColor(annotationPtr, colorType = PdfAnnotationColorType.Color) {\n const rPtr = this.memoryManager.malloc(4);\n const gPtr = this.memoryManager.malloc(4);\n const bPtr = this.memoryManager.malloc(4);\n const ok = this.pdfiumModule.EPDFAnnot_GetColor(annotationPtr, colorType, rPtr, gPtr, bPtr);\n let colour;\n if (ok) {\n colour = {\n red: this.pdfiumModule.pdfium.getValue(rPtr, "i32") & 255,\n green: this.pdfiumModule.pdfium.getValue(gPtr, "i32") & 255,\n blue: this.pdfiumModule.pdfium.getValue(bPtr, "i32") & 255\n };\n }\n this.memoryManager.free(rPtr);\n this.memoryManager.free(gPtr);\n this.memoryManager.free(bPtr);\n return colour;\n }\n /**\n * Get the fill/stroke colour annotation.\n *\n * @param annotationPtr - pointer to the annotation whose colour is being set\n * @param colorType - which colour to get (0 = fill, 1 = stroke)\n * @returns WebColor with hex color\n *\n * @private\n */\n getAnnotationColor(annotationPtr, colorType = PdfAnnotationColorType.Color) {\n const annotationColor = this.readAnnotationColor(annotationPtr, colorType);\n return annotationColor ? pdfColorToWebColor(annotationColor) : void 0;\n }\n /**\n * Set the fill/stroke colour for a **Highlight / Underline / StrikeOut / Squiggly** markup annotation.\n *\n * @param annotationPtr - pointer to the annotation whose colour is being set\n * @param webAlphaColor - WebAlphaColor with hex color and opacity (0-1)\n * @param shouldClearAP - whether to clear the /AP entry\n * @param which - which colour to set (0 = fill, 1 = stroke)\n * @returns `true` if the operation was successful\n *\n * @private\n */\n setAnnotationColor(annotationPtr, webColor, colorType = PdfAnnotationColorType.Color) {\n const pdfColor = webColorToPdfColor(webColor);\n return this.pdfiumModule.EPDFAnnot_SetColor(\n annotationPtr,\n colorType,\n pdfColor.red & 255,\n pdfColor.green & 255,\n pdfColor.blue & 255\n );\n }\n /**\n * Get the opacity of the annotation.\n *\n * @param annotationPtr - pointer to the annotation whose opacity is being set\n * @returns opacity (0-1)\n *\n * @private\n */\n getAnnotationOpacity(annotationPtr) {\n const opacityPtr = this.memoryManager.malloc(4);\n const ok = this.pdfiumModule.EPDFAnnot_GetOpacity(annotationPtr, opacityPtr);\n const opacity = ok ? this.pdfiumModule.pdfium.getValue(opacityPtr, "i32") : 255;\n this.memoryManager.free(opacityPtr);\n return pdfAlphaToWebOpacity(opacity);\n }\n /**\n * Set the opacity of the annotation.\n *\n * @param annotationPtr - pointer to the annotation whose opacity is being set\n * @param opacity - opacity (0-1)\n * @returns true on success\n *\n * @private\n */\n setAnnotationOpacity(annotationPtr, opacity) {\n const pdfOpacity = webOpacityToPdfAlpha(opacity);\n return this.pdfiumModule.EPDFAnnot_SetOpacity(annotationPtr, pdfOpacity & 255);\n }\n /**\n * Get the rotation angle (in degrees) from the annotation\'s /Rotate entry.\n * Returns 0 if no rotation is set or on error.\n *\n * @param annotationPtr - pointer to the annotation\n * @returns rotation in degrees (0 if not set)\n */\n getAnnotationRotation(annotationPtr) {\n const rotationPtr = this.memoryManager.malloc(4);\n const ok = this.pdfiumModule.EPDFAnnot_GetRotate(annotationPtr, rotationPtr);\n if (!ok) {\n this.memoryManager.free(rotationPtr);\n return 0;\n }\n const rotation = this.pdfiumModule.pdfium.getValue(rotationPtr, "float");\n this.memoryManager.free(rotationPtr);\n return rotation;\n }\n /**\n * Set the rotation angle (in degrees) on the annotation\'s /Rotate entry.\n * A value of 0 removes the /Rotate key.\n *\n * @param annotationPtr - pointer to the annotation\n * @param rotation - rotation in degrees (clockwise)\n * @returns true on success\n */\n setAnnotationRotation(annotationPtr, rotation) {\n return !!this.pdfiumModule.EPDFAnnot_SetRotate(annotationPtr, rotation);\n }\n /**\n * Get the EmbedPDF extended rotation (in degrees) from the annotation\'s\n * /EPDFRotate entry. Returns 0 if not set or on error.\n *\n * @param annotationPtr - pointer to the annotation\n * @returns rotation in degrees (0 if not set)\n */\n getAnnotExtendedRotation(annotationPtr) {\n const rotationPtr = this.memoryManager.malloc(4);\n const ok = this.pdfiumModule.EPDFAnnot_GetExtendedRotation(annotationPtr, rotationPtr);\n if (!ok) {\n this.memoryManager.free(rotationPtr);\n return 0;\n }\n const rotation = this.pdfiumModule.pdfium.getValue(rotationPtr, "float");\n this.memoryManager.free(rotationPtr);\n return rotation;\n }\n /**\n * Set the EmbedPDF extended rotation (in degrees) on the annotation\'s\n * /EPDFRotate entry. A value of 0 removes the key.\n *\n * @param annotationPtr - pointer to the annotation\n * @param rotation - rotation in degrees\n * @returns true on success\n */\n setAnnotExtendedRotation(annotationPtr, rotation) {\n return !!this.pdfiumModule.EPDFAnnot_SetExtendedRotation(annotationPtr, rotation);\n }\n /**\n * Read the EmbedPDF unrotated rect from the annotation\'s /EPDFUnrotatedRect\n * entry. Returns the raw page-space rect (same format as `readPageAnnoRect`)\n * or null if not set.\n *\n * @param annotationPtr - pointer to the annotation\n * @returns raw `{ left, top, right, bottom }` in page coords, or null\n */\n readAnnotUnrotatedRect(annotationPtr) {\n const rectPtr = this.memoryManager.malloc(4 * 4);\n const ok = this.pdfiumModule.EPDFAnnot_GetUnrotatedRect(annotationPtr, rectPtr);\n if (!ok) {\n this.memoryManager.free(rectPtr);\n return null;\n }\n const left = this.pdfiumModule.pdfium.getValue(rectPtr, "float");\n const top = this.pdfiumModule.pdfium.getValue(rectPtr + 4, "float");\n const right = this.pdfiumModule.pdfium.getValue(rectPtr + 8, "float");\n const bottom = this.pdfiumModule.pdfium.getValue(rectPtr + 12, "float");\n this.memoryManager.free(rectPtr);\n if (left === 0 && top === 0 && right === 0 && bottom === 0) {\n return null;\n }\n return { left, top, right, bottom };\n }\n /**\n * Write the EmbedPDF unrotated rect (/EPDFUnrotatedRect) for an annotation.\n * Accepts a device-space `Rect` and converts to page coordinates internally,\n * following the same pattern as `setPageAnnoRect`.\n *\n * @param doc - pdf document object\n * @param page - pdf page object\n * @param annotPtr - pointer to the annotation\n * @param rect - device-space rect to store as the unrotated rect\n * @returns true on success\n */\n setAnnotUnrotatedRect(doc, page, annotPtr, rect) {\n const x0d = Math.floor(rect.origin.x);\n const y0d = Math.floor(rect.origin.y);\n const x1d = Math.floor(rect.origin.x + rect.size.width);\n const y1d = Math.floor(rect.origin.y + rect.size.height);\n const TL = this.convertDevicePointToPagePoint(doc, page, { x: x0d, y: y0d });\n const TR = this.convertDevicePointToPagePoint(doc, page, { x: x1d, y: y0d });\n const BR = this.convertDevicePointToPagePoint(doc, page, { x: x1d, y: y1d });\n const BL = this.convertDevicePointToPagePoint(doc, page, { x: x0d, y: y1d });\n let left = Math.min(TL.x, TR.x, BR.x, BL.x);\n let right = Math.max(TL.x, TR.x, BR.x, BL.x);\n let bottom = Math.min(TL.y, TR.y, BR.y, BL.y);\n let top = Math.max(TL.y, TR.y, BR.y, BL.y);\n if (left > right) [left, right] = [right, left];\n if (bottom > top) [bottom, top] = [top, bottom];\n const ptr = this.memoryManager.malloc(16);\n const pdf = this.pdfiumModule.pdfium;\n pdf.setValue(ptr + 0, left, "float");\n pdf.setValue(ptr + 4, top, "float");\n pdf.setValue(ptr + 8, right, "float");\n pdf.setValue(ptr + 12, bottom, "float");\n const ok = this.pdfiumModule.EPDFAnnot_SetUnrotatedRect(annotPtr, ptr);\n this.memoryManager.free(ptr);\n return !!ok;\n }\n /**\n * Fetch the `/Q` text-alignment value from a **FreeText** annotation.\n *\n * @param annotationPtr pointer returned by `FPDFPage_GetAnnot`\n * @returns `PdfTextAlignment`\n */\n getAnnotationTextAlignment(annotationPtr) {\n return this.pdfiumModule.EPDFAnnot_GetTextAlignment(annotationPtr);\n }\n /**\n * Write the `/Q` text-alignment value into a **FreeText** annotation\n * and clear the existing appearance stream so it can be regenerated.\n *\n * @param annotationPtr pointer returned by `FPDFPage_GetAnnot`\n * @param alignment `PdfTextAlignment`\n * @returns `true` on success\n */\n setAnnotationTextAlignment(annotationPtr, alignment) {\n return !!this.pdfiumModule.EPDFAnnot_SetTextAlignment(annotationPtr, alignment);\n }\n /**\n * Fetch the `/EPDF:VerticalAlignment` vertical-alignment value from a **FreeText** annotation.\n *\n * @param annotationPtr pointer returned by `FPDFPage_GetAnnot`\n * @returns `PdfVerticalAlignment`\n */\n getAnnotationVerticalAlignment(annotationPtr) {\n return this.pdfiumModule.EPDFAnnot_GetVerticalAlignment(annotationPtr);\n }\n /**\n * Write the `/EPDF:VerticalAlignment` vertical-alignment value into a **FreeText** annotation\n * and clear the existing appearance stream so it can be regenerated.\n *\n * @param annotationPtr pointer returned by `FPDFPage_GetAnnot`\n * @param alignment `PdfVerticalAlignment`\n * @returns `true` on success\n */\n setAnnotationVerticalAlignment(annotationPtr, alignment) {\n return !!this.pdfiumModule.EPDFAnnot_SetVerticalAlignment(annotationPtr, alignment);\n }\n /**\n * Get the overlay text from a Redact annotation.\n *\n * @param annotationPtr pointer returned by `FPDFPage_GetAnnot`\n * @returns overlay text string or `undefined` if not set\n *\n * @private\n */\n getOverlayText(annotationPtr) {\n const len = this.pdfiumModule.EPDFAnnot_GetOverlayText(annotationPtr, 0, 0);\n if (len === 0) return void 0;\n const bytes = (len + 1) * 2;\n const ptr = this.memoryManager.malloc(bytes);\n this.pdfiumModule.EPDFAnnot_GetOverlayText(annotationPtr, ptr, bytes);\n const value = this.pdfiumModule.pdfium.UTF16ToString(ptr);\n this.memoryManager.free(ptr);\n return value || void 0;\n }\n /**\n * Set the overlay text on a Redact annotation.\n *\n * @param annotationPtr pointer returned by `FPDFPage_GetAnnot`\n * @param text overlay text to set, or undefined/empty to clear\n * @returns `true` on success\n *\n * @private\n */\n setOverlayText(annotationPtr, text) {\n if (!text) {\n return this.pdfiumModule.EPDFAnnot_SetOverlayText(annotationPtr, 0);\n }\n return this.withWString(text, (wPtr) => {\n return this.pdfiumModule.EPDFAnnot_SetOverlayText(annotationPtr, wPtr);\n });\n }\n /**\n * Get whether overlay text repeats in a Redact annotation.\n *\n * @param annotationPtr pointer returned by `FPDFPage_GetAnnot`\n * @returns `true` if overlay text repeats\n *\n * @private\n */\n getOverlayTextRepeat(annotationPtr) {\n return this.pdfiumModule.EPDFAnnot_GetOverlayTextRepeat(annotationPtr);\n }\n /**\n * Set whether overlay text repeats in a Redact annotation.\n *\n * @param annotationPtr pointer returned by `FPDFPage_GetAnnot`\n * @param repeat whether overlay text should repeat\n * @returns `true` on success\n *\n * @private\n */\n setOverlayTextRepeat(annotationPtr, repeat) {\n return this.pdfiumModule.EPDFAnnot_SetOverlayTextRepeat(annotationPtr, repeat);\n }\n /**\n * Return the **default appearance** (font, size, colour) declared in the\n * `/DA` string of a **FreeText** annotation.\n *\n * @param annotationPtr pointer to `FPDF_ANNOTATION`\n * @returns `{ font, fontSize, color }` or `undefined` when PDFium returns false\n *\n * NOTE – `font` is the raw `FPDF_STANDARD_FONT` enum value that PDFium uses\n * (same range as the C API: 0 = Courier, 12 = ZapfDingbats, …).\n */\n getAnnotationDefaultAppearance(annotationPtr) {\n const fontPtr = this.memoryManager.malloc(4);\n const sizePtr = this.memoryManager.malloc(4);\n const rPtr = this.memoryManager.malloc(4);\n const gPtr = this.memoryManager.malloc(4);\n const bPtr = this.memoryManager.malloc(4);\n const ok = !!this.pdfiumModule.EPDFAnnot_GetDefaultAppearance(\n annotationPtr,\n fontPtr,\n sizePtr,\n rPtr,\n gPtr,\n bPtr\n );\n if (!ok) {\n [fontPtr, sizePtr, rPtr, gPtr, bPtr].forEach((p) => this.memoryManager.free(p));\n return;\n }\n const pdf = this.pdfiumModule.pdfium;\n const font = pdf.getValue(fontPtr, "i32");\n const fontSize = pdf.getValue(sizePtr, "float");\n const red = pdf.getValue(rPtr, "i32") & 255;\n const green = pdf.getValue(gPtr, "i32") & 255;\n const blue = pdf.getValue(bPtr, "i32") & 255;\n [fontPtr, sizePtr, rPtr, gPtr, bPtr].forEach((p) => this.memoryManager.free(p));\n return {\n fontFamily: font,\n fontSize,\n fontColor: pdfColorToWebColor({ red, green, blue })\n };\n }\n /**\n * Write a **default appearance** (`/DA`) into a FreeText annotation.\n *\n * @param annotationPtr pointer to `FPDF_ANNOTATION`\n * @param font `FPDF_STANDARD_FONT` enum value\n * @param fontSize size in points (≥ 0)\n * @param color CSS-style `#rrggbb` string (alpha ignored)\n * @returns `true` on success\n */\n setAnnotationDefaultAppearance(annotationPtr, font, fontSize, color) {\n const resolvedFont = font === PdfStandardFont.Unknown ? PdfStandardFont.Helvetica : font;\n const { red, green, blue } = webColorToPdfColor(color);\n return !!this.pdfiumModule.EPDFAnnot_SetDefaultAppearance(\n annotationPtr,\n resolvedFont,\n fontSize,\n red & 255,\n green & 255,\n blue & 255\n );\n }\n /**\n * Border‐style + width helper\n *\n * Tries the new PDFium helper `EPDFAnnot_GetBorderStyle()` (patch series\n * 9 July 2025).\n *\n * @param annotationPtr pointer to an `FPDF_ANNOTATION`\n * @returns `{ ok, style, width }`\n * • `ok` – `true` when the call succeeded\n * • `style` – `PdfAnnotationBorderStyle` enum\n * • `width` – stroke-width in points (defaults to 0 pt)\n */\n getBorderStyle(annotationPtr) {\n const widthPtr = this.memoryManager.malloc(4);\n let width = 0;\n let style = PdfAnnotationBorderStyle.UNKNOWN;\n let ok = false;\n style = this.pdfiumModule.EPDFAnnot_GetBorderStyle(annotationPtr, widthPtr);\n width = this.pdfiumModule.pdfium.getValue(widthPtr, "float");\n ok = style !== PdfAnnotationBorderStyle.UNKNOWN;\n this.memoryManager.free(widthPtr);\n return { ok, style, width };\n }\n setBorderStyle(annotationPtr, style, width) {\n return this.pdfiumModule.EPDFAnnot_SetBorderStyle(annotationPtr, style, width);\n }\n /**\n * Get the icon of the annotation\n *\n * @param annotationPtr - pointer to an `FPDF_ANNOTATION`\n * @returns `PdfAnnotationIcon`\n */\n getAnnotationIcon(annotationPtr) {\n return this.pdfiumModule.EPDFAnnot_GetIcon(annotationPtr);\n }\n /**\n * Set the icon of the annotation\n *\n * @param annotationPtr - pointer to an `FPDF_ANNOTATION`\n * @param icon - `PdfAnnotationIcon`\n * @returns `true` on success\n */\n setAnnotationIcon(annotationPtr, icon) {\n return this.pdfiumModule.EPDFAnnot_SetIcon(annotationPtr, icon);\n }\n /**\n * Get the reply type of the annotation (RT property per ISO 32000-2)\n *\n * @param annotationPtr - pointer to an `FPDF_ANNOTATION`\n * @returns `PdfAnnotationReplyType`\n */\n getReplyType(annotationPtr) {\n return this.pdfiumModule.EPDFAnnot_GetReplyType(annotationPtr);\n }\n /**\n * Set the reply type of the annotation (RT property per ISO 32000-2)\n *\n * @param annotationPtr - pointer to an `FPDF_ANNOTATION`\n * @param replyType - `PdfAnnotationReplyType`\n * @returns `true` on success\n */\n setReplyType(annotationPtr, replyType) {\n return this.pdfiumModule.EPDFAnnot_SetReplyType(\n annotationPtr,\n replyType ?? PdfAnnotationReplyType.Unknown\n );\n }\n /**\n * Border-effect (“cloudy”) helper\n *\n * Calls the new PDFium function `EPDFAnnot_GetBorderEffect()` (July 2025).\n *\n * @param annotationPtr pointer to an `FPDF_ANNOTATION`\n * @returns `{ ok, intensity }`\n * • `ok` – `true` when the annotation *does* have a\n * valid cloudy-border effect\n * • `intensity` – radius/intensity value (0 when `ok` is false)\n */\n getBorderEffect(annotationPtr) {\n const intensityPtr = this.memoryManager.malloc(4);\n const ok = !!this.pdfiumModule.EPDFAnnot_GetBorderEffect(annotationPtr, intensityPtr);\n const intensity = ok ? this.pdfiumModule.pdfium.getValue(intensityPtr, "float") : 0;\n this.memoryManager.free(intensityPtr);\n return { ok, intensity };\n }\n /**\n * Rectangle-differences helper ( /RD array on Square / Circle annots )\n *\n * Calls `EPDFAnnot_GetRectangleDifferences()` introduced in July 2025.\n *\n * @param annotationPtr pointer to an `FPDF_ANNOTATION`\n * @returns `{ ok, left, top, right, bottom }`\n * • `ok` – `true` when the annotation *has* an /RD entry\n * • the four floats are 0 when `ok` is false\n */\n getRectangleDifferences(annotationPtr) {\n const lPtr = this.memoryManager.malloc(4);\n const tPtr = this.memoryManager.malloc(4);\n const rPtr = this.memoryManager.malloc(4);\n const bPtr = this.memoryManager.malloc(4);\n const ok = !!this.pdfiumModule.EPDFAnnot_GetRectangleDifferences(\n annotationPtr,\n lPtr,\n tPtr,\n rPtr,\n bPtr\n );\n const pdf = this.pdfiumModule.pdfium;\n const left = pdf.getValue(lPtr, "float");\n const top = pdf.getValue(tPtr, "float");\n const right = pdf.getValue(rPtr, "float");\n const bottom = pdf.getValue(bPtr, "float");\n this.memoryManager.free(lPtr);\n this.memoryManager.free(tPtr);\n this.memoryManager.free(rPtr);\n this.memoryManager.free(bPtr);\n return { ok, left, top, right, bottom };\n }\n /**\n * Get the date of the annotation\n *\n * @param annotationPtr - pointer to an `FPDF_ANNOTATION`\n * @param key - \'M\' for modified date, \'CreationDate\' for creation date\n * @returns `Date` or `undefined` when PDFium can\'t read the date\n */\n getAnnotationDate(annotationPtr, key) {\n const raw = this.getAnnotString(annotationPtr, key);\n return raw ? pdfDateToDate(raw) : void 0;\n }\n /**\n * Set the date of the annotation\n *\n * @param annotationPtr - pointer to an `FPDF_ANNOTATION`\n * @param key - \'M\' for modified date, \'CreationDate\' for creation date\n * @param date - `Date` to set\n * @returns `true` on success\n */\n setAnnotationDate(annotationPtr, key, date) {\n const raw = dateToPdfDate(date);\n return this.setAnnotString(annotationPtr, key, raw);\n }\n /**\n * Get the date of the attachment\n *\n * @param attachmentPtr - pointer to an `FPDF_ATTACHMENT`\n * @param key - \'ModDate\' for modified date, \'CreationDate\' for creation date\n * @returns `Date` or `undefined` when PDFium can\'t read the date\n */\n getAttachmentDate(attachmentPtr, key) {\n const raw = this.getAttachmentString(attachmentPtr, key);\n return raw ? pdfDateToDate(raw) : void 0;\n }\n /**\n * Set the date of the attachment\n *\n * @param attachmentPtr - pointer to an `FPDF_ATTACHMENT`\n * @param key - \'ModDate\' for modified date, \'CreationDate\' for creation date\n * @param date - `Date` to set\n * @returns `true` on success\n */\n setAttachmentDate(attachmentPtr, key, date) {\n const raw = dateToPdfDate(date);\n return this.setAttachmentString(attachmentPtr, key, raw);\n }\n /**\n * Dash-pattern helper ( /BS → /D array, dashed borders only )\n *\n * Uses the two new PDFium helpers:\n * • `EPDFAnnot_GetBorderDashPatternCount`\n * • `EPDFAnnot_GetBorderDashPattern`\n *\n * @param annotationPtr pointer to an `FPDF_ANNOTATION`\n * @returns `{ ok, pattern }`\n * • `ok` – `true` when the annot is dashed *and* the array\n * was retrieved successfully\n * • `pattern` – numeric array of dash/space lengths (empty when `ok` is false)\n */\n getBorderDashPattern(annotationPtr) {\n const count = this.pdfiumModule.EPDFAnnot_GetBorderDashPatternCount(annotationPtr);\n if (count === 0) {\n return { ok: false, pattern: [] };\n }\n const arrPtr = this.memoryManager.malloc(4 * count);\n const okNative = !!this.pdfiumModule.EPDFAnnot_GetBorderDashPattern(\n annotationPtr,\n arrPtr,\n count\n );\n const pattern = [];\n if (okNative) {\n const pdf = this.pdfiumModule.pdfium;\n for (let i = 0; i < count; i++) {\n pattern.push(pdf.getValue(arrPtr + 4 * i, "float"));\n }\n }\n this.memoryManager.free(arrPtr);\n return { ok: okNative, pattern };\n }\n /**\n * Write the /BS /D dash pattern array for an annotation border.\n *\n * @param annotationPtr Pointer to FPDF_ANNOTATION\n * @param pattern Array of dash/space lengths in *points* (e.g. [3, 2])\n * Empty array clears the pattern (solid line).\n * @returns true on success\n *\n * @private\n */\n setBorderDashPattern(annotationPtr, pattern) {\n if (!pattern || pattern.length === 0) {\n return this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(annotationPtr, 0, 0);\n }\n const clean = pattern.map((n) => Number.isFinite(n) && n > 0 ? n : 0).filter((n) => n > 0);\n if (clean.length === 0) {\n return this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(annotationPtr, 0, 0);\n }\n const bytes = 4 * clean.length;\n const bufPtr = this.memoryManager.malloc(bytes);\n for (let i = 0; i < clean.length; i++) {\n this.pdfiumModule.pdfium.setValue(bufPtr + 4 * i, clean[i], "float");\n }\n const ok = !!this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(\n annotationPtr,\n bufPtr,\n clean.length\n );\n this.memoryManager.free(bufPtr);\n return ok;\n }\n /**\n * Return the `/LE` array (start/end line-ending styles) for a LINE / POLYLINE annot.\n *\n * @param annotationPtr - pointer to an `FPDF_ANNOTATION`\n * @returns `{ start, end }` or `undefined` when PDFium can\'t read them\n *\n * @private\n */\n getLineEndings(annotationPtr) {\n const startPtr = this.memoryManager.malloc(4);\n const endPtr = this.memoryManager.malloc(4);\n const ok = !!this.pdfiumModule.EPDFAnnot_GetLineEndings(annotationPtr, startPtr, endPtr);\n if (!ok) {\n this.memoryManager.free(startPtr);\n this.memoryManager.free(endPtr);\n return void 0;\n }\n const start = this.pdfiumModule.pdfium.getValue(startPtr, "i32");\n const end = this.pdfiumModule.pdfium.getValue(endPtr, "i32");\n this.memoryManager.free(startPtr);\n this.memoryManager.free(endPtr);\n return { start, end };\n }\n /**\n * Write the `/LE` array (start/end line-ending styles) for a LINE / POLYLINE annot.\n * @param annotationPtr - pointer to an `FPDF_ANNOTATION`\n * @param start - start line ending style\n * @param end - end line ending style\n * @returns `true` on success\n */\n setLineEndings(annotationPtr, start, end) {\n return !!this.pdfiumModule.EPDFAnnot_SetLineEndings(annotationPtr, start, end);\n }\n /**\n * Get the start and end points of a LINE / POLYLINE annot.\n * @param doc - pdf document object\n * @param annotationPtr - pointer to an `FPDF_ANNOTATION`\n * @param page - logical page info object (`PdfPageObject`)\n * @returns `{ start, end }` or `undefined` when PDFium can\'t read them\n */\n getLinePoints(doc, page, annotationPtr) {\n const startPtr = this.memoryManager.malloc(8);\n const endPtr = this.memoryManager.malloc(8);\n const ok = this.pdfiumModule.FPDFAnnot_GetLine(annotationPtr, startPtr, endPtr);\n if (!ok) {\n this.memoryManager.free(startPtr);\n this.memoryManager.free(endPtr);\n return void 0;\n }\n const pdf = this.pdfiumModule.pdfium;\n const sx = pdf.getValue(startPtr + 0, "float");\n const sy = pdf.getValue(startPtr + 4, "float");\n const ex = pdf.getValue(endPtr + 0, "float");\n const ey = pdf.getValue(endPtr + 4, "float");\n this.memoryManager.free(startPtr);\n this.memoryManager.free(endPtr);\n const start = this.convertPagePointToDevicePoint(doc, page, { x: sx, y: sy });\n const end = this.convertPagePointToDevicePoint(doc, page, { x: ex, y: ey });\n return { start, end };\n }\n /**\n * Set the two end‑points of a **Line** annotation\n * by writing a new /L array `[ x1 y1 x2 y2 ]`.\n * @param doc - pdf document object\n * @param page - logical page info object (`PdfPageObject`)\n * @param annotPtr - pointer to the annotation whose line points are needed\n * @param start - start point\n * @param end - end point\n * @returns true on success\n */\n setLinePoints(doc, page, annotPtr, start, end) {\n const p1 = this.convertDevicePointToPagePoint(doc, page, start);\n const p2 = this.convertDevicePointToPagePoint(doc, page, end);\n if (!p1 || !p2) return false;\n const buf = this.memoryManager.malloc(16);\n const pdf = this.pdfiumModule.pdfium;\n pdf.setValue(buf + 0, p1.x, "float");\n pdf.setValue(buf + 4, p1.y, "float");\n pdf.setValue(buf + 8, p2.x, "float");\n pdf.setValue(buf + 12, p2.y, "float");\n const ok = this.pdfiumModule.EPDFAnnot_SetLine(annotPtr, buf, buf + 8);\n this.memoryManager.free(buf);\n return !!ok;\n }\n /**\n * Read `/QuadPoints` from any annotation and convert each quadrilateral to\n * device-space coordinates.\n *\n * The four points are returned in natural reading order:\n * `p1 → p2` (top edge) and `p4 → p3` (bottom edge).\n * This preserves the true shape for rotated / skewed text, whereas callers\n * that only need axis-aligned boxes can collapse each quad themselves.\n *\n * @param doc - pdf document object\n * @param page - logical page info object (`PdfPageObject`)\n * @param annotationPtr - pointer to the annotation whose quads are needed\n * @returns Array of `Rect` objects (`[]` if the annotation has no quads)\n *\n * @private\n */\n getQuadPointsAnno(doc, page, annotationPtr) {\n const quadCount = this.pdfiumModule.FPDFAnnot_CountAttachmentPoints(annotationPtr);\n if (quadCount === 0) return [];\n const FS_QUADPOINTSF_SIZE = 8 * 4;\n const quads = [];\n for (let qi = 0; qi < quadCount; qi++) {\n const quadPtr = this.memoryManager.malloc(FS_QUADPOINTSF_SIZE);\n const ok = this.pdfiumModule.FPDFAnnot_GetAttachmentPoints(annotationPtr, qi, quadPtr);\n if (ok) {\n const xs = [];\n const ys = [];\n for (let i = 0; i < 4; i++) {\n const base = quadPtr + i * 8;\n xs.push(this.pdfiumModule.pdfium.getValue(base, "float"));\n ys.push(this.pdfiumModule.pdfium.getValue(base + 4, "float"));\n }\n const p1 = this.convertPagePointToDevicePoint(doc, page, { x: xs[0], y: ys[0] });\n const p2 = this.convertPagePointToDevicePoint(doc, page, { x: xs[1], y: ys[1] });\n const p3 = this.convertPagePointToDevicePoint(doc, page, { x: xs[2], y: ys[2] });\n const p4 = this.convertPagePointToDevicePoint(doc, page, { x: xs[3], y: ys[3] });\n quads.push({ p1, p2, p3, p4 });\n }\n this.memoryManager.free(quadPtr);\n }\n return quads.map(quadToRect);\n }\n /**\n * Set the quadrilaterals for a **Highlight / Underline / StrikeOut / Squiggly** markup annotation.\n *\n * @param doc - pdf document object\n * @param page - logical page info object (`PdfPageObject`)\n * @param annotationPtr - pointer to the annotation whose quads are needed\n * @param rects - array of `Rect` objects (`[]` if the annotation has no quads)\n * @returns `true` if the operation was successful\n *\n * @private\n */\n syncQuadPointsAnno(doc, page, annotPtr, rects) {\n const FS_QUADPOINTSF_SIZE = 8 * 4;\n const pdf = this.pdfiumModule.pdfium;\n const count = this.pdfiumModule.FPDFAnnot_CountAttachmentPoints(annotPtr);\n const buf = this.memoryManager.malloc(FS_QUADPOINTSF_SIZE);\n const writeQuad = (r) => {\n const q = rectToQuad(r);\n const p1 = this.convertDevicePointToPagePoint(doc, page, q.p1);\n const p2 = this.convertDevicePointToPagePoint(doc, page, q.p2);\n const p3 = this.convertDevicePointToPagePoint(doc, page, q.p3);\n const p4 = this.convertDevicePointToPagePoint(doc, page, q.p4);\n pdf.setValue(buf + 0, p1.x, "float");\n pdf.setValue(buf + 4, p1.y, "float");\n pdf.setValue(buf + 8, p2.x, "float");\n pdf.setValue(buf + 12, p2.y, "float");\n pdf.setValue(buf + 16, p4.x, "float");\n pdf.setValue(buf + 20, p4.y, "float");\n pdf.setValue(buf + 24, p3.x, "float");\n pdf.setValue(buf + 28, p3.y, "float");\n };\n const min = Math.min(count, rects.length);\n for (let i = 0; i < min; i++) {\n writeQuad(rects[i]);\n if (!this.pdfiumModule.FPDFAnnot_SetAttachmentPoints(annotPtr, i, buf)) {\n this.memoryManager.free(buf);\n return false;\n }\n }\n for (let i = count; i < rects.length; i++) {\n writeQuad(rects[i]);\n if (!this.pdfiumModule.FPDFAnnot_AppendAttachmentPoints(annotPtr, buf)) {\n this.memoryManager.free(buf);\n return false;\n }\n }\n this.memoryManager.free(buf);\n return true;\n }\n /**\n * Redact text that intersects ANY of the provided **quads** (device-space).\n * Returns `true` if the page changed. Always regenerates the page stream.\n */\n redactTextInRects(doc, page, rects, options) {\n const { recurseForms = true, drawBlackBoxes = false } = options ?? {};\n this.logger.debug(\n "PDFiumEngine",\n "Engine",\n "redactTextInQuads",\n doc.id,\n page.index,\n rects.length\n );\n const label = "RedactTextInQuads";\n this.logger.perf("PDFiumEngine", "Engine", label, "Begin", `${doc.id}-${page.index}`);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf("PDFiumEngine", "Engine", label, "End", `${doc.id}-${page.index}`);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const clean = (rects ?? []).filter(\n (r) => {\n var _a, _b, _c, _d;\n return r && Number.isFinite((_a = r.origin) == null ? void 0 : _a.x) && Number.isFinite((_b = r.origin) == null ? void 0 : _b.y) && Number.isFinite((_c = r.size) == null ? void 0 : _c.width) && Number.isFinite((_d = r.size) == null ? void 0 : _d.height) && r.size.width > 0 && r.size.height > 0;\n }\n );\n if (clean.length === 0) {\n this.logger.perf("PDFiumEngine", "Engine", label, "End", `${doc.id}-${page.index}`);\n return PdfTaskHelper.resolve(false);\n }\n const pageCtx = ctx.acquirePage(page.index);\n const { ptr, count } = this.allocFSQuadsBufferFromRects(doc, page, clean);\n let ok = false;\n try {\n ok = !!this.pdfiumModule.EPDFText_RedactInQuads(\n pageCtx.pagePtr,\n ptr,\n count,\n recurseForms ? true : false,\n false\n );\n } finally {\n this.memoryManager.free(ptr);\n }\n if (ok) {\n ok = !!this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);\n }\n pageCtx.disposeImmediate();\n this.logger.perf("PDFiumEngine", "Engine", label, "End", `${doc.id}-${page.index}`);\n return PdfTaskHelper.resolve(!!ok);\n }\n /**\n * Apply a single redaction annotation, permanently removing content underneath\n * and flattening the RO (Redact Overlay) appearance stream if present.\n * The annotation is removed after successful application.\n *\n * @param doc - document object\n * @param page - page object\n * @param annotation - the redact annotation to apply\n * @returns true if successful\n */\n applyRedaction(doc, page, annotation) {\n this.logger.debug(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "applyRedaction",\n doc.id,\n page.index,\n annotation.id\n );\n const label = "ApplyRedaction";\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", `${doc.id}-${page.index}`);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", `${doc.id}-${page.index}`);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const annotPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);\n if (!annotPtr) {\n pageCtx.release();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", `${doc.id}-${page.index}`);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.NotFound,\n message: "annotation not found"\n });\n }\n const ok = this.pdfiumModule.EPDFAnnot_ApplyRedaction(pageCtx.pagePtr, annotPtr);\n this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);\n if (ok) {\n this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);\n }\n pageCtx.disposeImmediate();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", `${doc.id}-${page.index}`);\n return PdfTaskHelper.resolve(!!ok);\n }\n /**\n * Apply all redaction annotations on a page, permanently removing content\n * underneath each one and flattening RO streams if present.\n * All redact annotations are removed after successful application.\n *\n * @param doc - document object\n * @param page - page object\n * @returns true if any redactions were applied\n */\n applyAllRedactions(doc, page) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "applyAllRedactions", doc.id, page.index);\n const label = "ApplyAllRedactions";\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", `${doc.id}-${page.index}`);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", `${doc.id}-${page.index}`);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const ok = this.pdfiumModule.EPDFPage_ApplyRedactions(pageCtx.pagePtr);\n if (ok) {\n this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);\n }\n pageCtx.disposeImmediate();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", `${doc.id}-${page.index}`);\n return PdfTaskHelper.resolve(!!ok);\n }\n /**\n * Flatten an annotation\'s appearance (AP/N) to page content.\n * The annotation\'s visual appearance becomes part of the page itself.\n * The annotation is automatically removed after flattening.\n *\n * @param doc - document object\n * @param page - page object\n * @param annotation - the annotation to flatten\n * @returns true if successful\n */\n flattenAnnotation(doc, page, annotation) {\n this.logger.debug(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "flattenAnnotation",\n doc.id,\n page.index,\n annotation.id\n );\n const label = "FlattenAnnotation";\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", `${doc.id}-${page.index}`);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", `${doc.id}-${page.index}`);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const annotPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);\n if (!annotPtr) {\n pageCtx.release();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", `${doc.id}-${page.index}`);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.NotFound,\n message: "annotation not found"\n });\n }\n const ok = this.pdfiumModule.EPDFAnnot_Flatten(pageCtx.pagePtr, annotPtr);\n this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);\n if (ok) {\n this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);\n }\n pageCtx.disposeImmediate();\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", `${doc.id}-${page.index}`);\n return PdfTaskHelper.resolve(!!ok);\n }\n /** Pack device-space Rects into an FS_QUADPOINTSF[] buffer (page space). */\n allocFSQuadsBufferFromRects(doc, page, rects) {\n const STRIDE = 32;\n const count = rects.length;\n const ptr = this.memoryManager.malloc(STRIDE * count);\n const pdf = this.pdfiumModule.pdfium;\n for (let i = 0; i < count; i++) {\n const r = rects[i];\n const q = rectToQuad(r);\n const p1 = this.convertDevicePointToPagePoint(doc, page, q.p1);\n const p2 = this.convertDevicePointToPagePoint(doc, page, q.p2);\n const p3 = this.convertDevicePointToPagePoint(doc, page, q.p3);\n const p4 = this.convertDevicePointToPagePoint(doc, page, q.p4);\n const base = ptr + i * STRIDE;\n pdf.setValue(base + 0, p1.x, "float");\n pdf.setValue(base + 4, p1.y, "float");\n pdf.setValue(base + 8, p2.x, "float");\n pdf.setValue(base + 12, p2.y, "float");\n pdf.setValue(base + 16, p4.x, "float");\n pdf.setValue(base + 20, p4.y, "float");\n pdf.setValue(base + 24, p3.x, "float");\n pdf.setValue(base + 28, p3.y, "float");\n }\n return { ptr, count };\n }\n /**\n * Read ink list from annotation\n * @param doc - pdf document object\n * @param page - logical page info object (`PdfPageObject`)\n * @param pagePtr - pointer to the page\n * @param annotationPtr - pointer to the annotation whose ink list is needed\n * @returns ink list\n */\n getInkList(doc, page, annotationPtr) {\n const inkList = [];\n const pathCount = this.pdfiumModule.FPDFAnnot_GetInkListCount(annotationPtr);\n if (pathCount <= 0) return inkList;\n const pdf = this.pdfiumModule.pdfium;\n const POINT_STRIDE = 8;\n for (let i = 0; i < pathCount; i++) {\n const points = [];\n const n = this.pdfiumModule.FPDFAnnot_GetInkListPath(annotationPtr, i, 0, 0);\n if (n > 0) {\n const buf = this.memoryManager.malloc(n * POINT_STRIDE);\n this.pdfiumModule.FPDFAnnot_GetInkListPath(annotationPtr, i, buf, n);\n for (let j = 0; j < n; j++) {\n const base = buf + j * POINT_STRIDE;\n const px = pdf.getValue(base + 0, "float");\n const py = pdf.getValue(base + 4, "float");\n const d = this.convertPagePointToDevicePoint(doc, page, { x: px, y: py });\n points.push({ x: d.x, y: d.y });\n }\n this.memoryManager.free(buf);\n }\n inkList.push({ points });\n }\n return inkList;\n }\n /**\n * Add ink list to annotation\n * @param doc - pdf document object\n * @param page - logical page info object (`PdfPageObject`)\n * @param pagePtr - pointer to the page\n * @param annotationPtr - pointer to the annotation whose ink list is needed\n * @param inkList - ink list array of `PdfInkListObject`\n * @returns `true` if the operation was successful\n */\n setInkList(doc, page, annotationPtr, inkList) {\n const pdf = this.pdfiumModule.pdfium;\n const POINT_STRIDE = 8;\n for (const stroke of inkList) {\n const n = stroke.points.length;\n if (n === 0) continue;\n const buf = this.memoryManager.malloc(n * POINT_STRIDE);\n for (let i = 0; i < n; i++) {\n const pDev = stroke.points[i];\n const pPage = this.convertDevicePointToPagePoint(doc, page, pDev);\n pdf.setValue(buf + i * POINT_STRIDE + 0, pPage.x, "float");\n pdf.setValue(buf + i * POINT_STRIDE + 4, pPage.y, "float");\n }\n const idx = this.pdfiumModule.FPDFAnnot_AddInkStroke(annotationPtr, buf, n);\n this.memoryManager.free(buf);\n if (idx === -1) {\n return false;\n }\n }\n return true;\n }\n /**\n * Read pdf text annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf text annotation\n *\n * @private\n */\n readPdfTextAnno(doc, page, annotationPtr, index) {\n const annoRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, annoRect);\n const state = this.getAnnotString(annotationPtr, "State");\n const stateModel = this.getAnnotString(annotationPtr, "StateModel");\n const color = this.getAnnotationColor(annotationPtr);\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const icon = this.getAnnotationIcon(annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.TEXT,\n rect,\n color: color ?? "#FFFF00",\n opacity,\n state,\n stateModel,\n icon,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf freetext annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf freetext annotation\n *\n * @private\n */\n readPdfFreeTextAnno(doc, page, annotationPtr, index) {\n const annoRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, annoRect);\n const defaultStyle = this.getAnnotString(annotationPtr, "DS");\n const da = this.getAnnotationDefaultAppearance(annotationPtr);\n const bgColor = this.getAnnotationColor(annotationPtr);\n const textAlign = this.getAnnotationTextAlignment(annotationPtr);\n const verticalAlign = this.getAnnotationVerticalAlignment(annotationPtr);\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const richContent = this.getAnnotRichContent(annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.FREETEXT,\n rect,\n fontFamily: (da == null ? void 0 : da.fontFamily) ?? PdfStandardFont.Unknown,\n fontSize: (da == null ? void 0 : da.fontSize) ?? 12,\n fontColor: (da == null ? void 0 : da.fontColor) ?? "#000000",\n verticalAlign,\n color: bgColor,\n // fill color (matches shape convention)\n backgroundColor: bgColor,\n // deprecated alias\n opacity,\n textAlign,\n defaultStyle,\n richContent,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf link annotation from pdf document\n * @param page - pdf page infor\n * @param docPtr - pointer to pdf document object\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf link annotation\n *\n * @private\n */\n readPdfLinkAnno(doc, page, docPtr, annotationPtr, index) {\n const linkPtr = this.pdfiumModule.FPDFAnnot_GetLink(annotationPtr);\n if (!linkPtr) {\n return;\n }\n const annoRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, annoRect);\n const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);\n const strokeColor = this.getAnnotationColor(annotationPtr, PdfAnnotationColorType.Color);\n let strokeDashArray;\n if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {\n const { ok, pattern } = this.getBorderDashPattern(annotationPtr);\n if (ok) {\n strokeDashArray = pattern;\n }\n }\n const target = this.readPdfLinkAnnoTarget(\n docPtr,\n () => {\n return this.pdfiumModule.FPDFLink_GetAction(linkPtr);\n },\n () => {\n return this.pdfiumModule.FPDFLink_GetDest(docPtr, linkPtr);\n }\n );\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.LINK,\n rect,\n target,\n strokeColor,\n strokeWidth,\n strokeStyle,\n strokeDashArray,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf widget annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param formHandle - form handle\n * @param index - index of annotation in the pdf page\n * @returns pdf widget annotation\n *\n * @private\n */\n readPdfWidgetAnno(doc, page, annotationPtr, formHandle, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const field = this.readPdfWidgetAnnoField(formHandle, annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.WIDGET,\n rect,\n field,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf file attachment annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf file attachment annotation\n *\n * @private\n */\n readPdfFileAttachmentAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.FILEATTACHMENT,\n rect,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf ink annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf ink annotation\n *\n * @private\n */\n readPdfInkAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const strokeColor = this.getAnnotationColor(annotationPtr) ?? "#FF0000";\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const { width: strokeWidth } = this.getBorderStyle(annotationPtr);\n const inkList = this.getInkList(doc, page, annotationPtr);\n const blendMode = this.pdfiumModule.EPDFAnnot_GetBlendMode(annotationPtr);\n const intent = this.getAnnotIntent(annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.INK,\n rect,\n ...intent && { intent },\n blendMode,\n strokeColor,\n color: strokeColor,\n // deprecated alias\n opacity,\n strokeWidth: strokeWidth === 0 ? 1 : strokeWidth,\n inkList,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf polygon annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf polygon annotation\n *\n * @private\n */\n readPdfPolygonAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const vertices = this.readPdfAnnoVertices(doc, page, annotationPtr);\n const strokeColor = this.getAnnotationColor(annotationPtr);\n const interiorColor = this.getAnnotationColor(\n annotationPtr,\n PdfAnnotationColorType.InteriorColor\n );\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);\n let strokeDashArray;\n if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {\n const { ok, pattern } = this.getBorderDashPattern(annotationPtr);\n if (ok) {\n strokeDashArray = pattern;\n }\n }\n if (vertices.length > 1) {\n const first = vertices[0];\n const last = vertices[vertices.length - 1];\n if (first.x === last.x && first.y === last.y) {\n vertices.pop();\n }\n }\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.POLYGON,\n rect,\n strokeColor: strokeColor ?? "#FF0000",\n color: interiorColor ?? "transparent",\n opacity,\n strokeWidth: strokeWidth === 0 ? 1 : strokeWidth,\n strokeStyle,\n strokeDashArray,\n vertices,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf polyline annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf polyline annotation\n *\n * @private\n */\n readPdfPolylineAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const vertices = this.readPdfAnnoVertices(doc, page, annotationPtr);\n const strokeColor = this.getAnnotationColor(annotationPtr);\n const interiorColor = this.getAnnotationColor(\n annotationPtr,\n PdfAnnotationColorType.InteriorColor\n );\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);\n let strokeDashArray;\n if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {\n const { ok, pattern } = this.getBorderDashPattern(annotationPtr);\n if (ok) {\n strokeDashArray = pattern;\n }\n }\n const lineEndings = this.getLineEndings(annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.POLYLINE,\n rect,\n strokeColor: strokeColor ?? "#FF0000",\n color: interiorColor ?? "transparent",\n opacity,\n strokeWidth: strokeWidth === 0 ? 1 : strokeWidth,\n strokeStyle,\n strokeDashArray,\n lineEndings,\n vertices,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf line annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf line annotation\n *\n * @private\n */\n readPdfLineAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const linePoints = this.getLinePoints(doc, page, annotationPtr);\n const lineEndings = this.getLineEndings(annotationPtr);\n const strokeColor = this.getAnnotationColor(annotationPtr);\n const interiorColor = this.getAnnotationColor(\n annotationPtr,\n PdfAnnotationColorType.InteriorColor\n );\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);\n let strokeDashArray;\n if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {\n const { ok, pattern } = this.getBorderDashPattern(annotationPtr);\n if (ok) {\n strokeDashArray = pattern;\n }\n }\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.LINE,\n rect,\n strokeWidth: strokeWidth === 0 ? 1 : strokeWidth,\n strokeStyle,\n strokeDashArray,\n strokeColor: strokeColor ?? "#FF0000",\n color: interiorColor ?? "transparent",\n opacity,\n linePoints: linePoints || { start: { x: 0, y: 0 }, end: { x: 0, y: 0 } },\n lineEndings: lineEndings || {\n start: PdfAnnotationLineEnding.None,\n end: PdfAnnotationLineEnding.None\n },\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf highlight annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf highlight annotation\n *\n * @private\n */\n readPdfHighlightAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const segmentRects = this.getQuadPointsAnno(doc, page, annotationPtr);\n const strokeColor = this.getAnnotationColor(annotationPtr) ?? "#FFFF00";\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const blendMode = this.pdfiumModule.EPDFAnnot_GetBlendMode(annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.HIGHLIGHT,\n rect,\n blendMode,\n segmentRects,\n strokeColor,\n color: strokeColor,\n // deprecated alias\n opacity,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf underline annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf underline annotation\n *\n * @private\n */\n readPdfUnderlineAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const segmentRects = this.getQuadPointsAnno(doc, page, annotationPtr);\n const strokeColor = this.getAnnotationColor(annotationPtr) ?? "#FF0000";\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const blendMode = this.pdfiumModule.EPDFAnnot_GetBlendMode(annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.UNDERLINE,\n rect,\n blendMode,\n segmentRects,\n strokeColor,\n color: strokeColor,\n // deprecated alias\n opacity,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read strikeout annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf strikeout annotation\n *\n * @private\n */\n readPdfStrikeOutAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const segmentRects = this.getQuadPointsAnno(doc, page, annotationPtr);\n const strokeColor = this.getAnnotationColor(annotationPtr) ?? "#FF0000";\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const blendMode = this.pdfiumModule.EPDFAnnot_GetBlendMode(annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.STRIKEOUT,\n rect,\n blendMode,\n segmentRects,\n strokeColor,\n color: strokeColor,\n // deprecated alias\n opacity,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf squiggly annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf squiggly annotation\n *\n * @private\n */\n readPdfSquigglyAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const segmentRects = this.getQuadPointsAnno(doc, page, annotationPtr);\n const strokeColor = this.getAnnotationColor(annotationPtr) ?? "#FF0000";\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const blendMode = this.pdfiumModule.EPDFAnnot_GetBlendMode(annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.SQUIGGLY,\n rect,\n blendMode,\n segmentRects,\n strokeColor,\n color: strokeColor,\n // deprecated alias\n opacity,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf caret annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf caret annotation\n *\n * @private\n */\n readPdfCaretAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.CARET,\n rect,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf redact annotation\n * @param page - pdf page info\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf redact annotation\n *\n * @private\n */\n readPdfRedactAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const segmentRects = this.getQuadPointsAnno(doc, page, annotationPtr);\n const color = this.getAnnotationColor(annotationPtr, PdfAnnotationColorType.InteriorColor);\n const overlayColor = this.getAnnotationColor(\n annotationPtr,\n PdfAnnotationColorType.OverlayColor\n );\n const strokeColor = this.getAnnotationColor(annotationPtr, PdfAnnotationColorType.Color);\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const overlayText = this.getOverlayText(annotationPtr);\n const overlayTextRepeat = this.getOverlayTextRepeat(annotationPtr);\n const da = this.getAnnotationDefaultAppearance(annotationPtr);\n const textAlign = this.getAnnotationTextAlignment(annotationPtr);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.REDACT,\n rect,\n segmentRects,\n color,\n overlayColor,\n strokeColor,\n opacity,\n overlayText,\n overlayTextRepeat,\n fontFamily: da == null ? void 0 : da.fontFamily,\n fontSize: da == null ? void 0 : da.fontSize,\n fontColor: da == null ? void 0 : da.fontColor,\n textAlign,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf stamp annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf stamp annotation\n *\n * @private\n */\n readPdfStampAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.STAMP,\n rect,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read pdf object in pdf page\n * @param pageObjectPtr - pointer to pdf object in page\n * @returns pdf object in page\n *\n * @private\n */\n readPdfPageObject(pageObjectPtr) {\n const type = this.pdfiumModule.FPDFPageObj_GetType(pageObjectPtr);\n switch (type) {\n case PdfPageObjectType.PATH:\n return this.readPathObject(pageObjectPtr);\n case PdfPageObjectType.IMAGE:\n return this.readImageObject(pageObjectPtr);\n case PdfPageObjectType.FORM:\n return this.readFormObject(pageObjectPtr);\n }\n }\n /**\n * Read pdf path object\n * @param pathObjectPtr - pointer to pdf path object in page\n * @returns pdf path object\n *\n * @private\n */\n readPathObject(pathObjectPtr) {\n const segmentCount = this.pdfiumModule.FPDFPath_CountSegments(pathObjectPtr);\n const leftPtr = this.memoryManager.malloc(4);\n const bottomPtr = this.memoryManager.malloc(4);\n const rightPtr = this.memoryManager.malloc(4);\n const topPtr = this.memoryManager.malloc(4);\n this.pdfiumModule.FPDFPageObj_GetBounds(pathObjectPtr, leftPtr, bottomPtr, rightPtr, topPtr);\n const left = this.pdfiumModule.pdfium.getValue(leftPtr, "float");\n const bottom = this.pdfiumModule.pdfium.getValue(bottomPtr, "float");\n const right = this.pdfiumModule.pdfium.getValue(rightPtr, "float");\n const top = this.pdfiumModule.pdfium.getValue(topPtr, "float");\n const bounds = { left, bottom, right, top };\n this.memoryManager.free(leftPtr);\n this.memoryManager.free(bottomPtr);\n this.memoryManager.free(rightPtr);\n this.memoryManager.free(topPtr);\n const segments = [];\n for (let i = 0; i < segmentCount; i++) {\n const segment = this.readPdfSegment(pathObjectPtr, i);\n segments.push(segment);\n }\n const matrix = this.readPdfPageObjectTransformMatrix(pathObjectPtr);\n return {\n type: PdfPageObjectType.PATH,\n bounds,\n segments,\n matrix\n };\n }\n /**\n * Read segment of pdf path object\n * @param annotationObjectPtr - pointer to pdf path object\n * @param segmentIndex - index of segment\n * @returns pdf segment in pdf path\n *\n * @private\n */\n readPdfSegment(annotationObjectPtr, segmentIndex) {\n const segmentPtr = this.pdfiumModule.FPDFPath_GetPathSegment(annotationObjectPtr, segmentIndex);\n const segmentType = this.pdfiumModule.FPDFPathSegment_GetType(segmentPtr);\n const isClosed = this.pdfiumModule.FPDFPathSegment_GetClose(segmentPtr);\n const pointXPtr = this.memoryManager.malloc(4);\n const pointYPtr = this.memoryManager.malloc(4);\n this.pdfiumModule.FPDFPathSegment_GetPoint(segmentPtr, pointXPtr, pointYPtr);\n const pointX = this.pdfiumModule.pdfium.getValue(pointXPtr, "float");\n const pointY = this.pdfiumModule.pdfium.getValue(pointYPtr, "float");\n this.memoryManager.free(pointXPtr);\n this.memoryManager.free(pointYPtr);\n return {\n type: segmentType,\n point: { x: pointX, y: pointY },\n isClosed\n };\n }\n /**\n * Read pdf image object from pdf document\n * @param pageObjectPtr - pointer to pdf image object in page\n * @returns pdf image object\n *\n * @private\n */\n readImageObject(imageObjectPtr) {\n const bitmapPtr = this.pdfiumModule.FPDFImageObj_GetBitmap(imageObjectPtr);\n const bitmapBufferPtr = this.pdfiumModule.FPDFBitmap_GetBuffer(bitmapPtr);\n const bitmapWidth = this.pdfiumModule.FPDFBitmap_GetWidth(bitmapPtr);\n const bitmapHeight = this.pdfiumModule.FPDFBitmap_GetHeight(bitmapPtr);\n const format = this.pdfiumModule.FPDFBitmap_GetFormat(bitmapPtr);\n const pixelCount = bitmapWidth * bitmapHeight;\n const bytesPerPixel = 4;\n const array = new Uint8ClampedArray(pixelCount * bytesPerPixel);\n for (let i = 0; i < pixelCount; i++) {\n switch (format) {\n case 2:\n {\n const blue = this.pdfiumModule.pdfium.getValue(bitmapBufferPtr + i * 3, "i8");\n const green = this.pdfiumModule.pdfium.getValue(bitmapBufferPtr + i * 3 + 1, "i8");\n const red = this.pdfiumModule.pdfium.getValue(bitmapBufferPtr + i * 3 + 2, "i8");\n array[i * bytesPerPixel] = red;\n array[i * bytesPerPixel + 1] = green;\n array[i * bytesPerPixel + 2] = blue;\n array[i * bytesPerPixel + 3] = 100;\n }\n break;\n }\n }\n const imageDataLike = {\n data: array,\n width: bitmapWidth,\n height: bitmapHeight\n };\n const matrix = this.readPdfPageObjectTransformMatrix(imageObjectPtr);\n return {\n type: PdfPageObjectType.IMAGE,\n imageData: imageDataLike,\n matrix\n };\n }\n /**\n * Read form object from pdf document\n * @param formObjectPtr - pointer to pdf form object in page\n * @returns pdf form object\n *\n * @private\n */\n readFormObject(formObjectPtr) {\n const objectCount = this.pdfiumModule.FPDFFormObj_CountObjects(formObjectPtr);\n const objects = [];\n for (let i = 0; i < objectCount; i++) {\n const pageObjectPtr = this.pdfiumModule.FPDFFormObj_GetObject(formObjectPtr, i);\n const pageObj = this.readPdfPageObject(pageObjectPtr);\n if (pageObj) {\n objects.push(pageObj);\n }\n }\n const matrix = this.readPdfPageObjectTransformMatrix(formObjectPtr);\n return {\n type: PdfPageObjectType.FORM,\n objects,\n matrix\n };\n }\n /**\n * Read pdf object in pdf page\n * @param pageObjectPtr - pointer to pdf object in page\n * @returns pdf object in page\n *\n * @private\n */\n readPdfPageObjectTransformMatrix(pageObjectPtr) {\n const matrixPtr = this.memoryManager.malloc(4 * 6);\n if (this.pdfiumModule.FPDFPageObj_GetMatrix(pageObjectPtr, matrixPtr)) {\n const a = this.pdfiumModule.pdfium.getValue(matrixPtr, "float");\n const b = this.pdfiumModule.pdfium.getValue(matrixPtr + 4, "float");\n const c = this.pdfiumModule.pdfium.getValue(matrixPtr + 8, "float");\n const d = this.pdfiumModule.pdfium.getValue(matrixPtr + 12, "float");\n const e = this.pdfiumModule.pdfium.getValue(matrixPtr + 16, "float");\n const f = this.pdfiumModule.pdfium.getValue(matrixPtr + 20, "float");\n this.memoryManager.free(matrixPtr);\n return { a, b, c, d, e, f };\n }\n this.memoryManager.free(matrixPtr);\n return { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };\n }\n /**\n * Read contents of a stamp annotation\n * @param annotationPtr - pointer to pdf annotation\n * @returns contents of the stamp annotation\n *\n * @private\n */\n readStampAnnotationContents(annotationPtr) {\n const contents = [];\n const objectCount = this.pdfiumModule.FPDFAnnot_GetObjectCount(annotationPtr);\n for (let i = 0; i < objectCount; i++) {\n const annotationObjectPtr = this.pdfiumModule.FPDFAnnot_GetObject(annotationPtr, i);\n const pageObj = this.readPdfPageObject(annotationObjectPtr);\n if (pageObj) {\n contents.push(pageObj);\n }\n }\n return contents;\n }\n /**\n * Return the stroke-width declared in the annotation’s /Border or /BS entry.\n * Falls back to 1 pt when nothing is defined.\n *\n * @param annotationPtr - pointer to pdf annotation\n * @returns stroke-width\n *\n * @private\n */\n getStrokeWidth(annotationPtr) {\n const hPtr = this.memoryManager.malloc(4);\n const vPtr = this.memoryManager.malloc(4);\n const wPtr = this.memoryManager.malloc(4);\n const ok = this.pdfiumModule.FPDFAnnot_GetBorder(annotationPtr, hPtr, vPtr, wPtr);\n const width = ok ? this.pdfiumModule.pdfium.getValue(wPtr, "float") : 1;\n this.memoryManager.free(hPtr);\n this.memoryManager.free(vPtr);\n this.memoryManager.free(wPtr);\n return width;\n }\n /**\n * Fetches the `/F` flag bit-field from an annotation.\n *\n * @param annotationPtr pointer to an `FPDF_ANNOTATION`\n * @returns `{ raw, flags }`\n * • `raw` – the 32-bit integer returned by PDFium\n * • `flags` – object with individual booleans\n */\n getAnnotationFlags(annotationPtr) {\n const rawFlags = this.pdfiumModule.FPDFAnnot_GetFlags(annotationPtr);\n return flagsToNames(rawFlags);\n }\n setAnnotationFlags(annotationPtr, flags) {\n const rawFlags = namesToFlags(flags);\n return this.pdfiumModule.FPDFAnnot_SetFlags(annotationPtr, rawFlags);\n }\n /**\n * Read circle annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf circle annotation\n *\n * @private\n */\n readPdfCircleAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const interiorColor = this.getAnnotationColor(\n annotationPtr,\n PdfAnnotationColorType.InteriorColor\n );\n const strokeColor = this.getAnnotationColor(annotationPtr);\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);\n let strokeDashArray;\n if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {\n const { ok, pattern } = this.getBorderDashPattern(annotationPtr);\n if (ok) {\n strokeDashArray = pattern;\n }\n }\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.CIRCLE,\n rect,\n color: interiorColor ?? "transparent",\n opacity,\n strokeWidth,\n strokeColor: strokeColor ?? "#FF0000",\n strokeStyle,\n ...strokeDashArray !== void 0 && { strokeDashArray },\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read square annotation\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf square annotation\n *\n * @private\n */\n readPdfSquareAnno(doc, page, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n const interiorColor = this.getAnnotationColor(\n annotationPtr,\n PdfAnnotationColorType.InteriorColor\n );\n const strokeColor = this.getAnnotationColor(annotationPtr);\n const opacity = this.getAnnotationOpacity(annotationPtr);\n const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);\n let strokeDashArray;\n if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {\n const { ok, pattern } = this.getBorderDashPattern(annotationPtr);\n if (ok) {\n strokeDashArray = pattern;\n }\n }\n return {\n pageIndex: page.index,\n id: index,\n type: PdfAnnotationSubtype.SQUARE,\n rect,\n color: interiorColor ?? "transparent",\n opacity,\n strokeColor: strokeColor ?? "#FF0000",\n strokeWidth,\n strokeStyle,\n ...strokeDashArray !== void 0 && { strokeDashArray },\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Read basic info of unsupported pdf annotation\n * @param page - pdf page infor\n * @param type - type of annotation\n * @param annotationPtr - pointer to pdf annotation\n * @param index - index of annotation in the pdf page\n * @returns pdf annotation\n *\n * @private\n */\n readPdfAnno(doc, page, type, annotationPtr, index) {\n const pageRect = this.readPageAnnoRect(annotationPtr);\n const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);\n return {\n pageIndex: page.index,\n id: index,\n type,\n rect,\n ...this.readBaseAnnotationProperties(doc, page, annotationPtr)\n };\n }\n /**\n * Resolve `/IRT` → parent-annotation index on the same page.\n *\n * @param pagePtr - pointer to FPDF_PAGE\n * @param annotationPtr - pointer to FPDF_ANNOTATION\n * @returns index (`0…count-1`) or `undefined` when the annotation is *not* a reply\n *\n * @private\n */\n getInReplyToId(annotationPtr) {\n const parentPtr = this.pdfiumModule.FPDFAnnot_GetLinkedAnnot(annotationPtr, "IRT");\n if (!parentPtr) return;\n return this.getAnnotString(parentPtr, "NM");\n }\n /**\n * Set the in reply to id of the annotation\n *\n * @param annotationPtr - pointer to an `FPDF_ANNOTATION`\n * @param id - the id of the parent annotation\n * @returns `true` on success\n */\n setInReplyToId(pagePtr, annotationPtr, id) {\n if (!id) {\n return this.pdfiumModule.EPDFAnnot_SetLinkedAnnot(annotationPtr, "IRT", 0);\n }\n const parentPtr = this.getAnnotationByName(pagePtr, id);\n if (!parentPtr) return false;\n return this.pdfiumModule.EPDFAnnot_SetLinkedAnnot(annotationPtr, "IRT", parentPtr);\n }\n /**\n * Rotate a point around a center by the given angle in degrees.\n * Used to rotate vertices for PDF storage.\n */\n rotatePointForSave(point, center, angleDegrees) {\n const rad = angleDegrees * Math.PI / 180;\n const cos = Math.cos(rad);\n const sin = Math.sin(rad);\n const dx = point.x - center.x;\n const dy = point.y - center.y;\n return {\n x: center.x + dx * cos - dy * sin,\n y: center.y + dx * sin + dy * cos\n };\n }\n /**\n * Prepare an annotation for saving to PDF.\n * For vertex types (ink, line, polygon, polyline) with rotation,\n * physically rotates the vertices by +rotation so that other PDF viewers\n * see the correct visual result. Our viewer reverse-rotates on load.\n */\n prepareAnnotationForSave(annotation) {\n const rotation = annotation.rotation;\n const unrotatedRect = annotation.unrotatedRect;\n if (!rotation || rotation === 0 || !unrotatedRect) {\n return annotation;\n }\n const center = {\n x: unrotatedRect.origin.x + unrotatedRect.size.width / 2,\n y: unrotatedRect.origin.y + unrotatedRect.size.height / 2\n };\n switch (annotation.type) {\n case PdfAnnotationSubtype.INK: {\n const ink = annotation;\n const rotatedInkList = ink.inkList.map((stroke) => ({\n points: stroke.points.map((p) => this.rotatePointForSave(p, center, rotation))\n }));\n return { ...ink, inkList: rotatedInkList };\n }\n case PdfAnnotationSubtype.LINE: {\n const line = annotation;\n return {\n ...line,\n linePoints: {\n start: this.rotatePointForSave(line.linePoints.start, center, rotation),\n end: this.rotatePointForSave(line.linePoints.end, center, rotation)\n }\n };\n }\n case PdfAnnotationSubtype.POLYGON: {\n const poly = annotation;\n return {\n ...poly,\n vertices: poly.vertices.map((v) => this.rotatePointForSave(v, center, rotation))\n };\n }\n case PdfAnnotationSubtype.POLYLINE: {\n const polyline = annotation;\n return {\n ...polyline,\n vertices: polyline.vertices.map((v) => this.rotatePointForSave(v, center, rotation))\n };\n }\n default:\n return annotation;\n }\n }\n /**\n * Apply all base annotation properties from PdfAnnotationObjectBase.\n * The setInReplyToId and setReplyType functions handle clearing when undefined.\n *\n * @param pagePtr - pointer to page object\n * @param annotationPtr - pointer to annotation object\n * @param annotation - the annotation object containing properties to apply\n * @returns `true` on success\n */\n applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation) {\n if (!this.setAnnotString(annotationPtr, "T", annotation.author || "")) {\n return false;\n }\n if (!this.setAnnotString(annotationPtr, "Contents", annotation.contents ?? "")) {\n return false;\n }\n if (annotation.modified) {\n if (!this.setAnnotationDate(annotationPtr, "M", annotation.modified)) {\n return false;\n }\n }\n if (annotation.created) {\n if (!this.setAnnotationDate(annotationPtr, "CreationDate", annotation.created)) {\n return false;\n }\n }\n if (annotation.flags) {\n if (!this.setAnnotationFlags(annotationPtr, annotation.flags)) {\n return false;\n }\n }\n const existingCustom = this.getAnnotCustom(annotationPtr) ?? {};\n const customData = {\n ...existingCustom,\n ...annotation.custom ?? {}\n };\n delete customData.unrotatedRect;\n delete customData.rotation;\n const hasCustomData = Object.keys(customData).length > 0;\n if (hasCustomData) {\n if (!this.setAnnotCustom(annotationPtr, customData)) {\n return false;\n }\n } else if (Object.keys(existingCustom).length > 0) {\n if (!this.setAnnotCustom(annotationPtr, null)) {\n return false;\n }\n }\n if (annotation.rotation !== void 0) {\n const pdfRotation = annotation.rotation ? (360 - annotation.rotation) % 360 : 0;\n this.setAnnotExtendedRotation(annotationPtr, pdfRotation);\n }\n if (annotation.unrotatedRect) {\n this.setAnnotUnrotatedRect(doc, page, annotationPtr, annotation.unrotatedRect);\n } else if (annotation.rotation && annotation.rotation !== 0) {\n this.setAnnotUnrotatedRect(doc, page, annotationPtr, annotation.rect);\n }\n if (!this.setInReplyToId(pagePtr, annotationPtr, annotation.inReplyToId)) {\n return false;\n }\n if (!this.setReplyType(annotationPtr, annotation.replyType)) {\n return false;\n }\n return true;\n }\n /**\n * Read all base annotation properties from PdfAnnotationObjectBase.\n * Returns an object that can be spread into the annotation return value.\n *\n * @param doc - pdf document object\n * @param page - pdf page object\n * @param annotationPtr - pointer to annotation object\n * @returns object with base annotation properties\n */\n readBaseAnnotationProperties(doc, page, annotationPtr) {\n const author = this.getAnnotString(annotationPtr, "T");\n const contents = this.getAnnotString(annotationPtr, "Contents") || "";\n const modified = this.getAnnotationDate(annotationPtr, "M");\n const created = this.getAnnotationDate(annotationPtr, "CreationDate");\n const flags = this.getAnnotationFlags(annotationPtr);\n const custom = this.getAnnotCustom(annotationPtr);\n const inReplyToId = this.getInReplyToId(annotationPtr);\n const replyType = this.getReplyType(annotationPtr);\n const pdfRotation = this.getAnnotExtendedRotation(annotationPtr);\n const rotation = pdfRotation !== 0 ? (360 - pdfRotation) % 360 : 0;\n const rawUnrotatedRect = this.readAnnotUnrotatedRect(annotationPtr);\n const unrotatedRect = rawUnrotatedRect ? this.convertPageRectToDeviceRect(doc, page, rawUnrotatedRect) : void 0;\n return {\n author,\n contents,\n modified,\n created,\n flags,\n custom,\n // Only include IRT if present\n ...inReplyToId && { inReplyToId },\n // Only include RT if present and not the default (Reply)\n ...replyType && replyType !== PdfAnnotationReplyType.Reply && { replyType },\n ...rotation !== 0 && { rotation },\n ...unrotatedRect !== void 0 && { unrotatedRect }\n };\n }\n /**\n * Fetch a string value (`/T`, `/M`, `/State`, …) from an annotation.\n *\n * @returns decoded UTF-8 string or `undefined` when the key is absent\n *\n * @private\n */\n getAnnotString(annotationPtr, key) {\n const len = this.pdfiumModule.FPDFAnnot_GetStringValue(annotationPtr, key, 0, 0);\n if (len === 0) return;\n const bytes = (len + 1) * 2;\n const ptr = this.memoryManager.malloc(bytes);\n this.pdfiumModule.FPDFAnnot_GetStringValue(annotationPtr, key, ptr, bytes);\n const value = this.pdfiumModule.pdfium.UTF16ToString(ptr);\n this.memoryManager.free(ptr);\n return value || void 0;\n }\n /**\n * Get a string value (`/T`, `/M`, `/State`, …) from an attachment.\n *\n * @returns decoded UTF-8 string or `undefined` when the key is absent\n *\n * @private\n */\n getAttachmentString(attachmentPtr, key) {\n const len = this.pdfiumModule.FPDFAttachment_GetStringValue(attachmentPtr, key, 0, 0);\n if (len === 0) return;\n const bytes = (len + 1) * 2;\n const ptr = this.memoryManager.malloc(bytes);\n this.pdfiumModule.FPDFAttachment_GetStringValue(attachmentPtr, key, ptr, bytes);\n const value = this.pdfiumModule.pdfium.UTF16ToString(ptr);\n this.memoryManager.free(ptr);\n return value || void 0;\n }\n /**\n * Get a number value (`/Size`) from an attachment.\n *\n * @returns number or `null` when the key is absent\n *\n * @private\n */\n getAttachmentNumber(attachmentPtr, key) {\n const outPtr = this.memoryManager.malloc(4);\n try {\n const ok = this.pdfiumModule.EPDFAttachment_GetIntegerValue(\n attachmentPtr,\n key,\n // FPDF_BYTESTRING → ASCII JS string is fine in your glue\n outPtr\n );\n if (!ok) return void 0;\n return this.pdfiumModule.pdfium.getValue(outPtr, "i32") >>> 0;\n } finally {\n this.memoryManager.free(outPtr);\n }\n }\n /**\n * Get custom data of the annotation\n * @param annotationPtr - pointer to pdf annotation\n * @returns custom data of the annotation\n *\n * @private\n */\n getAnnotCustom(annotationPtr) {\n const custom = this.getAnnotString(annotationPtr, "EPDFCustom");\n if (!custom) return;\n try {\n return JSON.parse(custom);\n } catch (error) {\n console.warn("Failed to parse annotation custom data as JSON:", error);\n console.warn("Invalid JSON string:", custom);\n return void 0;\n }\n }\n /**\n * Sets custom data for an annotation by safely stringifying and storing JSON\n * @private\n */\n setAnnotCustom(annotationPtr, data) {\n if (data === void 0 || data === null) {\n return this.setAnnotString(annotationPtr, "EPDFCustom", "");\n }\n try {\n const jsonString = JSON.stringify(data);\n return this.setAnnotString(annotationPtr, "EPDFCustom", jsonString);\n } catch (error) {\n console.warn("Failed to stringify annotation custom data as JSON:", error);\n console.warn("Invalid data object:", data);\n return false;\n }\n }\n /**\n * Fetches the /IT (Intent) name from an annotation as a UTF-8 JS string.\n *\n * Mirrors getAnnotString(): calls EPDFAnnot_GetIntent twice (length probe + copy).\n * Returns `undefined` if no intent present.\n */\n getAnnotIntent(annotationPtr) {\n const len = this.pdfiumModule.EPDFAnnot_GetIntent(annotationPtr, 0, 0);\n if (len === 0) return;\n const codeUnits = len + 1;\n const bytes = codeUnits * 2;\n const ptr = this.memoryManager.malloc(bytes);\n this.pdfiumModule.EPDFAnnot_GetIntent(annotationPtr, ptr, bytes);\n const value = this.pdfiumModule.pdfium.UTF16ToString(ptr);\n this.memoryManager.free(ptr);\n return value && value !== "undefined" ? value : void 0;\n }\n /**\n * Write the `/IT` (Intent) name into an annotation dictionary.\n *\n * Mirrors EPDFAnnot_SetIntent in PDFium (expects a UTF‑8 FPDF_BYTESTRING).\n *\n * @param annotationPtr Pointer returned by FPDFPage_GetAnnot\n * @param intent Name without leading slash, e.g. `"PolygonCloud"`\n * A leading “/” will be stripped for convenience.\n * @returns true on success, false otherwise\n */\n setAnnotIntent(annotationPtr, intent) {\n return this.pdfiumModule.EPDFAnnot_SetIntent(annotationPtr, intent);\n }\n /**\n * Returns the rich‑content string stored in the annotation’s `/RC` entry.\n *\n * Works like `getAnnotIntent()`: first probe for length, then copy.\n * `undefined` when the annotation has no rich content.\n */\n getAnnotRichContent(annotationPtr) {\n const len = this.pdfiumModule.EPDFAnnot_GetRichContent(annotationPtr, 0, 0);\n if (len === 0) return;\n const codeUnits = len + 1;\n const bytes = codeUnits * 2;\n const ptr = this.memoryManager.malloc(bytes);\n this.pdfiumModule.EPDFAnnot_GetRichContent(annotationPtr, ptr, bytes);\n const value = this.pdfiumModule.pdfium.UTF16ToString(ptr);\n this.memoryManager.free(ptr);\n return value || void 0;\n }\n /**\n * Get annotation by name\n * @param pagePtr - pointer to pdf page object\n * @param name - name of annotation\n * @returns pointer to pdf annotation\n *\n * @private\n */\n getAnnotationByName(pagePtr, name) {\n return this.withWString(name, (wNamePtr) => {\n return this.pdfiumModule.EPDFPage_GetAnnotByName(pagePtr, wNamePtr);\n });\n }\n /**\n * Remove annotation by name\n * @param pagePtr - pointer to pdf page object\n * @param name - name of annotation\n * @returns true on success\n *\n * @private\n */\n removeAnnotationByName(pagePtr, name) {\n return this.withWString(name, (wNamePtr) => {\n return this.pdfiumModule.EPDFPage_RemoveAnnotByName(pagePtr, wNamePtr);\n });\n }\n /**\n * Set a string value (`/T`, `/M`, `/State`, …) to an annotation.\n *\n * @returns `true` if the operation was successful\n *\n * @private\n */\n setAnnotString(annotationPtr, key, value) {\n return this.withWString(value, (wValPtr) => {\n return this.pdfiumModule.FPDFAnnot_SetStringValue(annotationPtr, key, wValPtr);\n });\n }\n /**\n * Set a string value (`/T`, `/M`, `/State`, …) to an attachment.\n *\n * @returns `true` if the operation was successful\n *\n * @private\n */\n setAttachmentString(attachmentPtr, key, value) {\n return this.withWString(value, (wValPtr) => {\n return this.pdfiumModule.FPDFAttachment_SetStringValue(attachmentPtr, key, wValPtr);\n });\n }\n /**\n * Read vertices of pdf annotation\n * @param doc - pdf document object\n * @param page - pdf page infor\n * @param annotationPtr - pointer to pdf annotation\n * @returns vertices of pdf annotation\n *\n * @private\n */\n readPdfAnnoVertices(doc, page, annotationPtr) {\n const vertices = [];\n const count = this.pdfiumModule.FPDFAnnot_GetVertices(annotationPtr, 0, 0);\n const pointMemorySize = 8;\n const pointsPtr = this.memoryManager.malloc(count * pointMemorySize);\n this.pdfiumModule.FPDFAnnot_GetVertices(annotationPtr, pointsPtr, count);\n for (let i = 0; i < count; i++) {\n const pointX = this.pdfiumModule.pdfium.getValue(pointsPtr + i * pointMemorySize, "float");\n const pointY = this.pdfiumModule.pdfium.getValue(\n pointsPtr + i * pointMemorySize + 4,\n "float"\n );\n const { x, y } = this.convertPagePointToDevicePoint(doc, page, {\n x: pointX,\n y: pointY\n });\n const last = vertices[vertices.length - 1];\n if (!last || last.x !== x || last.y !== y) {\n vertices.push({ x, y });\n }\n }\n this.memoryManager.free(pointsPtr);\n return vertices;\n }\n /**\n * Sync the vertices of a polygon or polyline annotation.\n *\n * @param doc - pdf document object\n * @param page - pdf page infor\n * @param annotPtr - pointer to pdf annotation\n * @param vertices - the vertices to be set\n * @returns true on success\n *\n * @private\n */\n setPdfAnnoVertices(doc, page, annotPtr, vertices) {\n const pdf = this.pdfiumModule.pdfium;\n const FS_POINTF_SIZE = 8;\n const buf = this.memoryManager.malloc(FS_POINTF_SIZE * vertices.length);\n vertices.forEach((v, i) => {\n const pagePt = this.convertDevicePointToPagePoint(doc, page, v);\n pdf.setValue(buf + i * FS_POINTF_SIZE + 0, pagePt.x, "float");\n pdf.setValue(buf + i * FS_POINTF_SIZE + 4, pagePt.y, "float");\n });\n const ok = this.pdfiumModule.EPDFAnnot_SetVertices(annotPtr, buf, vertices.length);\n this.memoryManager.free(buf);\n return ok;\n }\n /**\n * Read the target of pdf bookmark\n * @param docPtr - pointer to pdf document object\n * @param getActionPtr - callback function to retrive the pointer of action\n * @param getDestinationPtr - callback function to retrive the pointer of destination\n * @returns target of pdf bookmark\n *\n * @private\n */\n readPdfBookmarkTarget(docPtr, getActionPtr, getDestinationPtr) {\n const actionPtr = getActionPtr();\n if (actionPtr) {\n const action = this.readPdfAction(docPtr, actionPtr);\n return {\n type: "action",\n action\n };\n } else {\n const destinationPtr = getDestinationPtr();\n if (destinationPtr) {\n const destination = this.readPdfDestination(docPtr, destinationPtr);\n return {\n type: "destination",\n destination\n };\n }\n }\n }\n /**\n * Read field of pdf widget annotation\n * @param formHandle - form handle\n * @param annotationPtr - pointer to pdf annotation\n * @returns field of pdf widget annotation\n *\n * @private\n */\n readPdfWidgetAnnoField(formHandle, annotationPtr) {\n const flag = this.pdfiumModule.FPDFAnnot_GetFormFieldFlags(\n formHandle,\n annotationPtr\n );\n const type = this.pdfiumModule.FPDFAnnot_GetFormFieldType(\n formHandle,\n annotationPtr\n );\n const name = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFAnnot_GetFormFieldName(\n formHandle,\n annotationPtr,\n buffer,\n bufferLength\n );\n },\n this.pdfiumModule.pdfium.UTF16ToString\n );\n const alternateName = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFAnnot_GetFormFieldAlternateName(\n formHandle,\n annotationPtr,\n buffer,\n bufferLength\n );\n },\n this.pdfiumModule.pdfium.UTF16ToString\n );\n const value = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFAnnot_GetFormFieldValue(\n formHandle,\n annotationPtr,\n buffer,\n bufferLength\n );\n },\n this.pdfiumModule.pdfium.UTF16ToString\n );\n const options = [];\n if (type === PDF_FORM_FIELD_TYPE.COMBOBOX || type === PDF_FORM_FIELD_TYPE.LISTBOX) {\n const count = this.pdfiumModule.FPDFAnnot_GetOptionCount(formHandle, annotationPtr);\n for (let i = 0; i < count; i++) {\n const label = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFAnnot_GetOptionLabel(\n formHandle,\n annotationPtr,\n i,\n buffer,\n bufferLength\n );\n },\n this.pdfiumModule.pdfium.UTF16ToString\n );\n const isSelected = this.pdfiumModule.FPDFAnnot_IsOptionSelected(\n formHandle,\n annotationPtr,\n i\n );\n options.push({\n label,\n isSelected\n });\n }\n }\n let isChecked = false;\n if (type === PDF_FORM_FIELD_TYPE.CHECKBOX || type === PDF_FORM_FIELD_TYPE.RADIOBUTTON) {\n isChecked = this.pdfiumModule.FPDFAnnot_IsChecked(formHandle, annotationPtr);\n }\n return {\n flag,\n type,\n name,\n alternateName,\n value,\n isChecked,\n options\n };\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.renderAnnotation}\n *\n * @public\n */\n renderPageAnnotationRaw(doc, page, annotation, options) {\n const {\n scaleFactor = 1,\n rotation = Rotation.Degree0,\n dpr = 1,\n mode = AppearanceMode.Normal\n } = options ?? {};\n this.logger.debug(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n "renderPageAnnotation",\n doc,\n page,\n annotation,\n options\n );\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RenderPageAnnotation`,\n "Begin",\n `${doc.id}-${page.index}-${annotation.id}`\n );\n const task = new Task();\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RenderPageAnnotation`,\n "End",\n `${doc.id}-${page.index}-${annotation.id}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const pageCtx = ctx.acquirePage(page.index);\n const annotPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);\n if (!annotPtr) {\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RenderPageAnnotation`,\n "End",\n `${doc.id}-${page.index}-${annotation.id}`\n );\n pageCtx.release();\n return PdfTaskHelper.reject({ code: PdfErrorCode.NotFound, message: "annotation not found" });\n }\n const finalScale = Math.max(0.01, scaleFactor * dpr);\n const unrotated = !!(options == null ? void 0 : options.unrotated) && !!annotation.unrotatedRect;\n const renderRect = unrotated ? annotation.unrotatedRect : annotation.rect;\n const rect = toIntRect(renderRect);\n const devRect = toIntRect(transformRect(page.size, rect, rotation, finalScale));\n const wDev = Math.max(1, devRect.size.width);\n const hDev = Math.max(1, devRect.size.height);\n const stride = wDev * 4;\n const bytes = stride * hDev;\n const heapPtr = this.memoryManager.malloc(bytes);\n const bitmapPtr = this.pdfiumModule.FPDFBitmap_CreateEx(\n wDev,\n hDev,\n 4,\n heapPtr,\n stride\n );\n this.pdfiumModule.FPDFBitmap_FillRect(bitmapPtr, 0, 0, wDev, hDev, 0);\n const M = buildUserToDeviceMatrix(\n rect,\n // {origin:{L,B}, size:{W,H}}\n rotation,\n wDev,\n hDev\n );\n const mPtr = this.memoryManager.malloc(6 * 4);\n const mView = new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer, mPtr, 6);\n mView.set([M.a, M.b, M.c, M.d, M.e, M.f]);\n const FLAGS = 16;\n let ok = false;\n try {\n if (unrotated) {\n ok = !!this.pdfiumModule.EPDF_RenderAnnotBitmapUnrotated(\n bitmapPtr,\n pageCtx.pagePtr,\n annotPtr,\n mode,\n mPtr,\n FLAGS\n );\n } else {\n ok = !!this.pdfiumModule.EPDF_RenderAnnotBitmap(\n bitmapPtr,\n pageCtx.pagePtr,\n annotPtr,\n mode,\n mPtr,\n FLAGS\n );\n }\n } finally {\n this.memoryManager.free(mPtr);\n this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);\n this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);\n pageCtx.release();\n }\n if (!ok) {\n this.memoryManager.free(heapPtr);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RenderPageAnnotation`,\n "End",\n `${doc.id}-${page.index}-${annotation.id}`\n );\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: "EPDF_RenderAnnotBitmap failed"\n });\n }\n const data = this.pdfiumModule.pdfium.HEAPU8.subarray(heapPtr, heapPtr + bytes);\n const imageDataLike = {\n data: new Uint8ClampedArray(data),\n width: wDev,\n height: hDev\n };\n task.resolve(imageDataLike);\n this.memoryManager.free(heapPtr);\n return task;\n }\n renderRectEncoded(doc, page, rect, options) {\n const task = new Task();\n const rotation = (options == null ? void 0 : options.rotation) ?? Rotation.Degree0;\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "document does not open"\n });\n }\n const scale = Math.max(0.01, (options == null ? void 0 : options.scaleFactor) ?? 1);\n const dpr = Math.max(1, (options == null ? void 0 : options.dpr) ?? 1);\n const finalScale = scale * dpr;\n const baseW = rect.size.width;\n const baseH = rect.size.height;\n const swap2 = (rotation & 1) === 1;\n const wDev = Math.max(1, Math.round((swap2 ? baseH : baseW) * finalScale));\n const hDev = Math.max(1, Math.round((swap2 ? baseW : baseH) * finalScale));\n const stride = wDev * 4;\n const bytes = stride * hDev;\n const pageCtx = ctx.acquirePage(page.index);\n const shouldRenderForms = (options == null ? void 0 : options.withForms) ?? false;\n const formHandle = shouldRenderForms ? pageCtx.getFormHandle() : void 0;\n const heapPtr = this.memoryManager.malloc(bytes);\n const bitmapPtr = this.pdfiumModule.FPDFBitmap_CreateEx(\n wDev,\n hDev,\n 4,\n heapPtr,\n stride\n );\n this.pdfiumModule.FPDFBitmap_FillRect(bitmapPtr, 0, 0, wDev, hDev, 4294967295);\n const M = buildUserToDeviceMatrix(rect, rotation, wDev, hDev);\n const mPtr = this.memoryManager.malloc(6 * 4);\n const mView = new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer, mPtr, 6);\n mView.set([M.a, M.b, M.c, M.d, M.e, M.f]);\n const clipPtr = this.memoryManager.malloc(4 * 4);\n const clipView = new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer, clipPtr, 4);\n clipView.set([0, 0, wDev, hDev]);\n let flags = 16;\n if ((options == null ? void 0 : options.withAnnotations) ?? false) flags |= 1;\n try {\n this.pdfiumModule.FPDF_RenderPageBitmapWithMatrix(\n bitmapPtr,\n pageCtx.pagePtr,\n mPtr,\n clipPtr,\n flags\n );\n if (formHandle !== void 0) {\n const formParams = computeFormDrawParams(M, rect, page.size, rotation);\n const { startX, startY, formsWidth, formsHeight, scaleX, scaleY } = formParams;\n this.pdfiumModule.FPDF_FFLDraw(\n formHandle,\n bitmapPtr,\n pageCtx.pagePtr,\n startX,\n startY,\n formsWidth,\n formsHeight,\n rotation,\n flags\n );\n }\n } finally {\n pageCtx.release();\n this.memoryManager.free(mPtr);\n this.memoryManager.free(clipPtr);\n }\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RenderRectEncodedData`,\n "Begin",\n `${doc.id}-${page.index}`\n );\n const data = this.pdfiumModule.pdfium.HEAPU8.subarray(heapPtr, heapPtr + bytes);\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RenderRectEncodedData`,\n "End",\n `${doc.id}-${page.index}`\n );\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RenderRectEncodedImageData`,\n "Begin",\n `${doc.id}-${page.index}`\n );\n const imageDataLike = {\n data: new Uint8ClampedArray(data),\n width: wDev,\n height: hDev\n };\n this.logger.perf(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `RenderRectEncodedImageData`,\n "End",\n `${doc.id}-${page.index}`\n );\n task.resolve(imageDataLike);\n this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);\n this.memoryManager.free(heapPtr);\n return task;\n }\n /**\n * Read the target of pdf link annotation\n * @param docPtr - pointer to pdf document object\n * @param getActionPtr - callback function to retrive the pointer of action\n * @param getDestinationPtr - callback function to retrive the pointer of destination\n * @returns target of link\n *\n * @private\n */\n readPdfLinkAnnoTarget(docPtr, getActionPtr, getDestinationPtr) {\n const destinationPtr = getDestinationPtr();\n if (destinationPtr) {\n const destination = this.readPdfDestination(docPtr, destinationPtr);\n return {\n type: "destination",\n destination\n };\n } else {\n const actionPtr = getActionPtr();\n if (actionPtr) {\n const action = this.readPdfAction(docPtr, actionPtr);\n return {\n type: "action",\n action\n };\n }\n }\n }\n createLocalDestPtr(docPtr, dest) {\n var _a, _b;\n const pagePtr = this.pdfiumModule.FPDF_LoadPage(docPtr, dest.pageIndex);\n if (!pagePtr) return 0;\n try {\n if (dest.zoom.mode === PdfZoomMode.XYZ) {\n const { x, y, zoom } = dest.zoom.params;\n return this.pdfiumModule.EPDFDest_CreateXYZ(\n pagePtr,\n /*has_left*/\n true,\n x,\n /*has_top*/\n true,\n y,\n /*has_zoom*/\n true,\n zoom\n );\n }\n let viewEnum;\n let params = [];\n switch (dest.zoom.mode) {\n case PdfZoomMode.FitPage:\n viewEnum = PdfZoomMode.FitPage;\n break;\n case PdfZoomMode.FitHorizontal:\n viewEnum = PdfZoomMode.FitHorizontal;\n params = [((_a = dest.view) == null ? void 0 : _a[0]) ?? 0];\n break;\n case PdfZoomMode.FitVertical:\n viewEnum = PdfZoomMode.FitVertical;\n params = [((_b = dest.view) == null ? void 0 : _b[0]) ?? 0];\n break;\n case PdfZoomMode.FitRectangle:\n {\n const v = dest.view ?? [];\n params = [v[0] ?? 0, v[1] ?? 0, v[2] ?? 0, v[3] ?? 0];\n viewEnum = PdfZoomMode.FitRectangle;\n }\n break;\n case PdfZoomMode.Unknown:\n default:\n return 0;\n }\n return this.withFloatArray(\n params,\n (ptr, count) => this.pdfiumModule.EPDFDest_CreateView(pagePtr, viewEnum, ptr, count)\n );\n } finally {\n this.pdfiumModule.FPDF_ClosePage(pagePtr);\n }\n }\n applyBookmarkTarget(docPtr, bmPtr, target) {\n if (target.type === "destination") {\n const destPtr = this.createLocalDestPtr(docPtr, target.destination);\n if (!destPtr) return false;\n const ok = this.pdfiumModule.EPDFBookmark_SetDest(docPtr, bmPtr, destPtr);\n return !!ok;\n }\n const action = target.action;\n switch (action.type) {\n case PdfActionType.Goto: {\n const destPtr = this.createLocalDestPtr(docPtr, action.destination);\n if (!destPtr) return false;\n const actPtr = this.pdfiumModule.EPDFAction_CreateGoTo(docPtr, destPtr);\n if (!actPtr) return false;\n return !!this.pdfiumModule.EPDFBookmark_SetAction(docPtr, bmPtr, actPtr);\n }\n case PdfActionType.URI: {\n const actPtr = this.pdfiumModule.EPDFAction_CreateURI(docPtr, action.uri);\n if (!actPtr) return false;\n return !!this.pdfiumModule.EPDFBookmark_SetAction(docPtr, bmPtr, actPtr);\n }\n case PdfActionType.LaunchAppOrOpenFile: {\n const actPtr = this.withWString(\n action.path,\n (wptr) => this.pdfiumModule.EPDFAction_CreateLaunch(docPtr, wptr)\n );\n if (!actPtr) return false;\n return !!this.pdfiumModule.EPDFBookmark_SetAction(docPtr, bmPtr, actPtr);\n }\n case PdfActionType.RemoteGoto:\n return false;\n case PdfActionType.Unsupported:\n default:\n return false;\n }\n }\n /**\n * Apply a link target (action or destination) to a link annotation\n * @param docPtr - pointer to pdf document\n * @param annotationPtr - pointer to the link annotation\n * @param target - the link target to apply\n * @returns true if successful\n *\n * @private\n */\n applyLinkTarget(docPtr, annotationPtr, target) {\n if (target.type === "destination") {\n const destPtr = this.createLocalDestPtr(docPtr, target.destination);\n if (!destPtr) return false;\n const actPtr = this.pdfiumModule.EPDFAction_CreateGoTo(docPtr, destPtr);\n if (!actPtr) return false;\n return !!this.pdfiumModule.EPDFAnnot_SetAction(annotationPtr, actPtr);\n }\n const action = target.action;\n switch (action.type) {\n case PdfActionType.Goto: {\n const destPtr = this.createLocalDestPtr(docPtr, action.destination);\n if (!destPtr) return false;\n const actPtr = this.pdfiumModule.EPDFAction_CreateGoTo(docPtr, destPtr);\n if (!actPtr) return false;\n return !!this.pdfiumModule.EPDFAnnot_SetAction(annotationPtr, actPtr);\n }\n case PdfActionType.URI: {\n const actPtr = this.pdfiumModule.EPDFAction_CreateURI(docPtr, action.uri);\n if (!actPtr) return false;\n return !!this.pdfiumModule.EPDFAnnot_SetAction(annotationPtr, actPtr);\n }\n case PdfActionType.LaunchAppOrOpenFile: {\n const actPtr = this.withWString(\n action.path,\n (wptr) => this.pdfiumModule.EPDFAction_CreateLaunch(docPtr, wptr)\n );\n if (!actPtr) return false;\n return !!this.pdfiumModule.EPDFAnnot_SetAction(annotationPtr, actPtr);\n }\n case PdfActionType.RemoteGoto:\n case PdfActionType.Unsupported:\n default:\n return false;\n }\n }\n /**\n * Read pdf action from pdf document\n * @param docPtr - pointer to pdf document object\n * @param actionPtr - pointer to pdf action object\n * @returns pdf action object\n *\n * @private\n */\n readPdfAction(docPtr, actionPtr) {\n const actionType = this.pdfiumModule.FPDFAction_GetType(actionPtr);\n let action;\n switch (actionType) {\n case PdfActionType.Unsupported:\n action = {\n type: PdfActionType.Unsupported\n };\n break;\n case PdfActionType.Goto:\n {\n const destinationPtr = this.pdfiumModule.FPDFAction_GetDest(docPtr, actionPtr);\n if (destinationPtr) {\n const destination = this.readPdfDestination(docPtr, destinationPtr);\n action = {\n type: PdfActionType.Goto,\n destination\n };\n } else {\n action = {\n type: PdfActionType.Unsupported\n };\n }\n }\n break;\n case PdfActionType.RemoteGoto:\n {\n action = {\n type: PdfActionType.Unsupported\n };\n }\n break;\n case PdfActionType.URI:\n {\n const uri = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFAction_GetURIPath(\n docPtr,\n actionPtr,\n buffer,\n bufferLength\n );\n },\n this.pdfiumModule.pdfium.UTF8ToString\n );\n action = {\n type: PdfActionType.URI,\n uri\n };\n }\n break;\n case PdfActionType.LaunchAppOrOpenFile:\n {\n const path = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFAction_GetFilePath(actionPtr, buffer, bufferLength);\n },\n this.pdfiumModule.pdfium.UTF8ToString\n );\n action = {\n type: PdfActionType.LaunchAppOrOpenFile,\n path\n };\n }\n break;\n }\n return action;\n }\n /**\n * Read pdf destination object\n * @param docPtr - pointer to pdf document object\n * @param destinationPtr - pointer to pdf destination\n * @returns pdf destination object\n *\n * @private\n */\n readPdfDestination(docPtr, destinationPtr) {\n const pageIndex = this.pdfiumModule.FPDFDest_GetDestPageIndex(docPtr, destinationPtr);\n const maxParmamsCount = 4;\n const paramsCountPtr = this.memoryManager.malloc(maxParmamsCount);\n const paramsPtr = this.memoryManager.malloc(maxParmamsCount * 4);\n const zoomMode = this.pdfiumModule.FPDFDest_GetView(\n destinationPtr,\n paramsCountPtr,\n paramsPtr\n );\n const paramsCount = this.pdfiumModule.pdfium.getValue(paramsCountPtr, "i32");\n const view = [];\n for (let i = 0; i < paramsCount; i++) {\n const paramPtr = paramsPtr + i * 4;\n view.push(this.pdfiumModule.pdfium.getValue(paramPtr, "float"));\n }\n this.memoryManager.free(paramsCountPtr);\n this.memoryManager.free(paramsPtr);\n if (zoomMode === PdfZoomMode.XYZ) {\n const hasXPtr = this.memoryManager.malloc(1);\n const hasYPtr = this.memoryManager.malloc(1);\n const hasZPtr = this.memoryManager.malloc(1);\n const xPtr = this.memoryManager.malloc(4);\n const yPtr = this.memoryManager.malloc(4);\n const zPtr = this.memoryManager.malloc(4);\n const isSucceed = this.pdfiumModule.FPDFDest_GetLocationInPage(\n destinationPtr,\n hasXPtr,\n hasYPtr,\n hasZPtr,\n xPtr,\n yPtr,\n zPtr\n );\n if (isSucceed) {\n const hasX = this.pdfiumModule.pdfium.getValue(hasXPtr, "i8");\n const hasY = this.pdfiumModule.pdfium.getValue(hasYPtr, "i8");\n const hasZ = this.pdfiumModule.pdfium.getValue(hasZPtr, "i8");\n const x = hasX ? this.pdfiumModule.pdfium.getValue(xPtr, "float") : 0;\n const y = hasY ? this.pdfiumModule.pdfium.getValue(yPtr, "float") : 0;\n const zoom = hasZ ? this.pdfiumModule.pdfium.getValue(zPtr, "float") : 0;\n this.memoryManager.free(hasXPtr);\n this.memoryManager.free(hasYPtr);\n this.memoryManager.free(hasZPtr);\n this.memoryManager.free(xPtr);\n this.memoryManager.free(yPtr);\n this.memoryManager.free(zPtr);\n return {\n pageIndex,\n zoom: {\n mode: zoomMode,\n params: {\n x,\n y,\n zoom\n }\n },\n view\n };\n }\n this.memoryManager.free(hasXPtr);\n this.memoryManager.free(hasYPtr);\n this.memoryManager.free(hasZPtr);\n this.memoryManager.free(xPtr);\n this.memoryManager.free(yPtr);\n this.memoryManager.free(zPtr);\n return {\n pageIndex,\n zoom: {\n mode: zoomMode,\n params: {\n x: 0,\n y: 0,\n zoom: 0\n }\n },\n view\n };\n }\n return {\n pageIndex,\n zoom: {\n mode: zoomMode\n },\n view\n };\n }\n /**\n * Read attachmet from pdf document\n * @param docPtr - pointer to pdf document object\n * @param index - index of attachment\n * @returns attachment content\n *\n * @private\n */\n readPdfAttachment(docPtr, index) {\n const attachmentPtr = this.pdfiumModule.FPDFDoc_GetAttachment(docPtr, index);\n const name = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFAttachment_GetName(attachmentPtr, buffer, bufferLength);\n },\n this.pdfiumModule.pdfium.UTF16ToString\n );\n const description = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.EPDFAttachment_GetDescription(attachmentPtr, buffer, bufferLength);\n },\n this.pdfiumModule.pdfium.UTF16ToString\n );\n const mimeType = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFAttachment_GetSubtype(attachmentPtr, buffer, bufferLength);\n },\n this.pdfiumModule.pdfium.UTF16ToString\n );\n const creationDate = this.getAttachmentDate(attachmentPtr, "CreationDate");\n const checksum = readString(\n this.pdfiumModule.pdfium,\n (buffer, bufferLength) => {\n return this.pdfiumModule.FPDFAttachment_GetStringValue(\n attachmentPtr,\n "Checksum",\n buffer,\n bufferLength\n );\n },\n this.pdfiumModule.pdfium.UTF16ToString\n );\n const size = this.getAttachmentNumber(attachmentPtr, "Size");\n return {\n index,\n name,\n description,\n mimeType,\n size,\n creationDate,\n checksum\n };\n }\n /**\n * Convert coordinate of point from device coordinate to page coordinate\n * @param doc - pdf document object\n * @param page - pdf page infor\n * @param position - position of point\n * @returns converted position\n *\n * @private\n */\n convertDevicePointToPagePoint(doc, page, position) {\n const DW = page.size.width;\n const DH = page.size.height;\n const r = doc.normalizedRotation ? 0 : page.rotation & 3;\n if (r === 0) {\n return { x: position.x, y: DH - position.y };\n }\n if (r === 1) {\n return { x: position.y, y: position.x };\n }\n if (r === 2) {\n return { x: DW - position.x, y: position.y };\n }\n {\n return { x: DH - position.y, y: DW - position.x };\n }\n }\n /**\n * Convert coordinate of point from page coordinate to device coordinate\n * @param doc - pdf document object\n * @param page - pdf page infor\n * @param position - position of point\n * @returns converted position\n *\n * @private\n */\n convertPagePointToDevicePoint(doc, page, position) {\n const DW = page.size.width;\n const DH = page.size.height;\n const r = doc.normalizedRotation ? 0 : page.rotation & 3;\n if (r === 0) {\n return { x: position.x, y: DH - position.y };\n }\n if (r === 1) {\n return { x: position.y, y: position.x };\n }\n if (r === 2) {\n return { x: DW - position.x, y: position.y };\n }\n {\n return { x: DW - position.y, y: DH - position.x };\n }\n }\n /**\n * Convert coordinate of rectangle from page coordinate to device coordinate\n * @param doc - pdf document object\n * @param page - pdf page infor\n * @param pagePtr - pointer to pdf page object\n * @param pageRect - rectangle that needs to be converted\n * @returns converted rectangle\n *\n * @private\n */\n convertPageRectToDeviceRect(doc, page, pageRect) {\n const { x, y } = this.convertPagePointToDevicePoint(doc, page, {\n x: pageRect.left,\n y: pageRect.top\n });\n const rect = {\n origin: {\n x,\n y\n },\n size: {\n width: Math.abs(pageRect.right - pageRect.left),\n height: Math.abs(pageRect.top - pageRect.bottom)\n }\n };\n return rect;\n }\n /**\n * Read the appearance stream of annotation\n * @param annotationPtr - pointer to pdf annotation\n * @param mode - appearance mode\n * @returns appearance stream\n *\n * @private\n */\n readPageAnnoAppearanceStreams(annotationPtr) {\n return {\n normal: this.readPageAnnoAppearanceStream(annotationPtr, AppearanceMode.Normal),\n rollover: this.readPageAnnoAppearanceStream(annotationPtr, AppearanceMode.Rollover),\n down: this.readPageAnnoAppearanceStream(annotationPtr, AppearanceMode.Down)\n };\n }\n /**\n * Read the appearance stream of annotation\n * @param annotationPtr - pointer to pdf annotation\n * @param mode - appearance mode\n * @returns appearance stream\n *\n * @private\n */\n readPageAnnoAppearanceStream(annotationPtr, mode = AppearanceMode.Normal) {\n const utf16Length = this.pdfiumModule.FPDFAnnot_GetAP(annotationPtr, mode, 0, 0);\n const bytesCount = (utf16Length + 1) * 2;\n const bufferPtr = this.memoryManager.malloc(bytesCount);\n this.pdfiumModule.FPDFAnnot_GetAP(annotationPtr, mode, bufferPtr, bytesCount);\n const ap = this.pdfiumModule.pdfium.UTF16ToString(bufferPtr);\n this.memoryManager.free(bufferPtr);\n return ap;\n }\n /**\n * Set the appearance stream of annotation\n * @param annotationPtr - pointer to pdf annotation\n * @param mode - appearance mode\n * @param apContent - appearance stream content (null to remove)\n * @returns whether the appearance stream was set successfully\n *\n * @private\n */\n setPageAnnoAppearanceStream(annotationPtr, mode = AppearanceMode.Normal, apContent) {\n const bytes = 2 * (apContent.length + 1);\n const ptr = this.memoryManager.malloc(bytes);\n try {\n this.pdfiumModule.pdfium.stringToUTF16(apContent, ptr, bytes);\n const ok = this.pdfiumModule.FPDFAnnot_SetAP(annotationPtr, mode, ptr);\n return !!ok;\n } finally {\n this.memoryManager.free(ptr);\n }\n }\n /**\n * Set the rect of specified annotation\n * @param doc - pdf document object\n * @param page - page info that the annotation is belonged to\n * @param annotationPtr - pointer to annotation object\n * @param rect - target rectangle\n * @returns whether the rect is setted\n *\n * @private\n */\n setPageAnnoRect(doc, page, annotPtr, rect) {\n const x0d = Math.floor(rect.origin.x);\n const y0d = Math.floor(rect.origin.y);\n const x1d = Math.floor(rect.origin.x + rect.size.width);\n const y1d = Math.floor(rect.origin.y + rect.size.height);\n const TL = this.convertDevicePointToPagePoint(doc, page, { x: x0d, y: y0d });\n const TR = this.convertDevicePointToPagePoint(doc, page, { x: x1d, y: y0d });\n const BR = this.convertDevicePointToPagePoint(doc, page, { x: x1d, y: y1d });\n const BL = this.convertDevicePointToPagePoint(doc, page, { x: x0d, y: y1d });\n let left = Math.min(TL.x, TR.x, BR.x, BL.x);\n let right = Math.max(TL.x, TR.x, BR.x, BL.x);\n let bottom = Math.min(TL.y, TR.y, BR.y, BL.y);\n let top = Math.max(TL.y, TR.y, BR.y, BL.y);\n if (left > right) [left, right] = [right, left];\n if (bottom > top) [bottom, top] = [top, bottom];\n const ptr = this.memoryManager.malloc(16);\n const pdf = this.pdfiumModule.pdfium;\n pdf.setValue(ptr + 0, left, "float");\n pdf.setValue(ptr + 4, top, "float");\n pdf.setValue(ptr + 8, right, "float");\n pdf.setValue(ptr + 12, bottom, "float");\n const ok = this.pdfiumModule.FPDFAnnot_SetRect(annotPtr, ptr);\n this.memoryManager.free(ptr);\n return !!ok;\n }\n /**\n * Read the rectangle of annotation\n * @param annotationPtr - pointer to pdf annotation\n * @returns rectangle of annotation\n *\n * @private\n */\n readPageAnnoRect(annotationPtr) {\n const pageRectPtr = this.memoryManager.malloc(4 * 4);\n const pageRect = {\n left: 0,\n top: 0,\n right: 0,\n bottom: 0\n };\n if (this.pdfiumModule.EPDFAnnot_GetRect(annotationPtr, pageRectPtr)) {\n pageRect.left = this.pdfiumModule.pdfium.getValue(pageRectPtr, "float");\n pageRect.top = this.pdfiumModule.pdfium.getValue(pageRectPtr + 4, "float");\n pageRect.right = this.pdfiumModule.pdfium.getValue(pageRectPtr + 8, "float");\n pageRect.bottom = this.pdfiumModule.pdfium.getValue(pageRectPtr + 12, "float");\n }\n this.memoryManager.free(pageRectPtr);\n return pageRect;\n }\n /**\n * Get highlight rects for a specific character range (for search highlighting)\n * @param doc - pdf document object\n * @param page - pdf page info\n * @param pagePtr - pointer to pdf page\n * @param textPagePtr - pointer to pdf text page\n * @param startIndex - starting character index\n * @param charCount - number of characters in the range\n * @returns array of rectangles for highlighting the specified character range\n *\n * @private\n */\n getHighlightRects(doc, page, textPagePtr, startIndex, charCount) {\n const rectsCount = this.pdfiumModule.FPDFText_CountRects(textPagePtr, startIndex, charCount);\n const highlightRects = [];\n const l = this.memoryManager.malloc(8);\n const t = this.memoryManager.malloc(8);\n const r = this.memoryManager.malloc(8);\n const b = this.memoryManager.malloc(8);\n for (let i = 0; i < rectsCount; i++) {\n const ok = this.pdfiumModule.FPDFText_GetRect(textPagePtr, i, l, t, r, b);\n if (!ok) continue;\n const left = this.pdfiumModule.pdfium.getValue(l, "double");\n const top = this.pdfiumModule.pdfium.getValue(t, "double");\n const right = this.pdfiumModule.pdfium.getValue(r, "double");\n const bottom = this.pdfiumModule.pdfium.getValue(b, "double");\n const p1 = this.convertPagePointToDevicePoint(doc, page, { x: left, y: top });\n const p2 = this.convertPagePointToDevicePoint(doc, page, { x: right, y: top });\n const p3 = this.convertPagePointToDevicePoint(doc, page, { x: right, y: bottom });\n const p4 = this.convertPagePointToDevicePoint(doc, page, { x: left, y: bottom });\n const xs = [p1.x, p2.x, p3.x, p4.x];\n const ys = [p1.y, p2.y, p3.y, p4.y];\n const x = Math.min(...xs);\n const y = Math.min(...ys);\n const width = Math.max(...xs) - x;\n const height = Math.max(...ys) - y;\n highlightRects.push({\n origin: { x, y },\n size: { width: Math.ceil(width), height: Math.ceil(height) }\n });\n }\n this.memoryManager.free(l);\n this.memoryManager.free(t);\n this.memoryManager.free(r);\n this.memoryManager.free(b);\n return highlightRects;\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.searchAllPages}\n *\n * Runs inside the worker.\n * Emits per-page progress: { page, results }\n *\n * @public\n */\n searchInPage(doc, page, keyword, flags) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "searchInPage", doc, page, keyword, flags);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `SearchInPage`, "Begin", `${doc.id}-${page.index}`);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `PreparePrintDocument`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "Document is not open"\n });\n }\n const length = 2 * (keyword.length + 1);\n const keywordPtr = this.memoryManager.malloc(length);\n this.pdfiumModule.pdfium.stringToUTF16(keyword, keywordPtr, length);\n try {\n const results = this.searchAllInPage(doc, ctx, page, keywordPtr, flags);\n return PdfTaskHelper.resolve(results);\n } finally {\n this.memoryManager.free(keywordPtr);\n }\n }\n /**\n * Get annotations for multiple pages in a single batch.\n * Emits progress per page for streaming updates.\n *\n * @param doc - PDF document\n * @param pages - Array of pages to process\n * @returns Task with results keyed by page index, with per-page progress\n *\n * @public\n */\n getAnnotationsBatch(doc, pages) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getAnnotationsBatch", doc.id, pages.length);\n const task = new Task();\n queueMicrotask(() => {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetAnnotationsBatch", "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n task.reject({ code: PdfErrorCode.DocNotOpen, message: "Document is not open" });\n return;\n }\n const results = {};\n const total = pages.length;\n for (let i = 0; i < pages.length; i++) {\n const page = pages[i];\n const annotations = this.readPageAnnotationsRaw(doc, ctx, page);\n results[page.index] = annotations;\n task.progress({\n pageIndex: page.index,\n result: annotations,\n completed: i + 1,\n total\n });\n }\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetAnnotationsBatch", "End", doc.id);\n task.resolve(results);\n });\n return task;\n }\n /**\n * Search across multiple pages in a single batch.\n * Emits progress per page for streaming updates.\n *\n * @param doc - PDF document\n * @param pages - Array of pages to search\n * @param keyword - Search keyword\n * @param flags - Search flags\n * @returns Task with results keyed by page index, with per-page progress\n *\n * @public\n */\n searchBatch(doc, pages, keyword, flags) {\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "searchBatch", doc.id, pages.length, keyword);\n const task = new Task();\n queueMicrotask(() => {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "SearchBatch", "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n task.reject({ code: PdfErrorCode.DocNotOpen, message: "Document is not open" });\n return;\n }\n const length = 2 * (keyword.length + 1);\n const keywordPtr = this.memoryManager.malloc(length);\n this.pdfiumModule.pdfium.stringToUTF16(keyword, keywordPtr, length);\n try {\n const results = {};\n const total = pages.length;\n for (let i = 0; i < pages.length; i++) {\n const page = pages[i];\n const pageResults = this.searchAllInPage(doc, ctx, page, keywordPtr, flags);\n results[page.index] = pageResults;\n task.progress({\n pageIndex: page.index,\n result: pageResults,\n completed: i + 1,\n total\n });\n }\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "SearchBatch", "End", doc.id);\n task.resolve(results);\n } finally {\n this.memoryManager.free(keywordPtr);\n }\n });\n return task;\n }\n /**\n * Extract word-aligned context for a search hit.\n *\n * @param fullText full UTF-16 page text (fetch this once per page!)\n * @param start index of 1st char that matched\n * @param count number of chars in the match\n * @param windowChars minimum context chars to keep left & right\n */\n buildContext(fullText, start, count, windowChars = 30) {\n const WORD_BREAK = /[\\s\\u00A0.,;:!?()\\[\\]{}<>/\\\\\\-"\'`"”\\u2013\\u2014]/;\n const findWordStart = (index) => {\n while (index > 0 && !WORD_BREAK.test(fullText[index - 1])) index--;\n return index;\n };\n const findWordEnd = (index) => {\n while (index < fullText.length && !WORD_BREAK.test(fullText[index])) index++;\n return index;\n };\n let left = start;\n while (left > 0 && WORD_BREAK.test(fullText[left - 1])) left--;\n let collected = 0;\n while (left > 0 && collected < windowChars) {\n left--;\n if (!WORD_BREAK.test(fullText[left])) collected++;\n }\n left = findWordStart(left);\n let right = start + count;\n while (right < fullText.length && WORD_BREAK.test(fullText[right])) right++;\n collected = 0;\n while (right < fullText.length && collected < windowChars) {\n if (!WORD_BREAK.test(fullText[right])) collected++;\n right++;\n }\n right = findWordEnd(right);\n const before = fullText.slice(left, start).replace(/\\s+/g, " ").trimStart();\n const match = fullText.slice(start, start + count);\n const after = fullText.slice(start + count, right).replace(/\\s+/g, " ").trimEnd();\n return {\n before: this.tidy(before),\n match: this.tidy(match),\n after: this.tidy(after),\n truncatedLeft: left > 0,\n truncatedRight: right < fullText.length\n };\n }\n /**\n * Tidy the text to remove any non-printable characters and whitespace\n * @param s - text to tidy\n * @returns tidied text\n *\n * @private\n */\n tidy(s) {\n return s.replace(/-\\uFFFE\\s*/g, "").replace(/[\\uFFFE\\u00AD\\u200B\\u2060\\uFEFF]/g, "").replace(/\\s+/g, " ");\n }\n /**\n * Search for all occurrences of a keyword on a single page\n * This method efficiently loads the page only once and finds all matches\n *\n * @param docPtr - pointer to pdf document\n * @param page - pdf page object\n * @param pageIndex - index of the page\n * @param keywordPtr - pointer to the search keyword\n * @param flag - search flags\n * @returns array of search results on this page\n *\n * @private\n */\n searchAllInPage(doc, ctx, page, keywordPtr, flag) {\n return ctx.borrowPage(page.index, (pageCtx) => {\n const textPagePtr = pageCtx.getTextPage();\n const total = this.pdfiumModule.FPDFText_CountChars(textPagePtr);\n const bufPtr = this.memoryManager.malloc(2 * (total + 1));\n this.pdfiumModule.FPDFText_GetText(textPagePtr, 0, total, bufPtr);\n const fullText = this.pdfiumModule.pdfium.UTF16ToString(bufPtr);\n this.memoryManager.free(bufPtr);\n const pageResults = [];\n const searchHandle = this.pdfiumModule.FPDFText_FindStart(\n textPagePtr,\n keywordPtr,\n flag,\n 0\n // Start from the beginning of the page\n );\n while (this.pdfiumModule.FPDFText_FindNext(searchHandle)) {\n const charIndex = this.pdfiumModule.FPDFText_GetSchResultIndex(searchHandle);\n const charCount = this.pdfiumModule.FPDFText_GetSchCount(searchHandle);\n const rects = this.getHighlightRects(doc, page, textPagePtr, charIndex, charCount);\n const context = this.buildContext(fullText, charIndex, charCount);\n pageResults.push({\n pageIndex: page.index,\n charIndex,\n charCount,\n rects,\n context\n });\n }\n this.pdfiumModule.FPDFText_FindClose(searchHandle);\n return pageResults;\n });\n }\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.preparePrintDocument}\n *\n * Prepares a PDF document for printing with specified options.\n * Creates a new document with selected pages and optionally removes annotations\n * for optimal printing performance.\n *\n * @public\n */\n preparePrintDocument(doc, options) {\n const { includeAnnotations = true, pageRange = null } = options ?? {};\n this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "preparePrintDocument", doc, options);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `PreparePrintDocument`, "Begin", doc.id);\n const ctx = this.cache.getContext(doc.id);\n if (!ctx) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `PreparePrintDocument`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: "Document is not open"\n });\n }\n const printDocPtr = this.pdfiumModule.FPDF_CreateNewDocument();\n if (!printDocPtr) {\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `PreparePrintDocument`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantCreateNewDoc,\n message: "Cannot create print document"\n });\n }\n try {\n const sanitizedPageRange = this.sanitizePageRange(pageRange, doc.pageCount);\n if (!this.pdfiumModule.FPDF_ImportPages(\n printDocPtr,\n ctx.docPtr,\n sanitizedPageRange ?? "",\n 0\n // Insert at beginning\n )) {\n this.pdfiumModule.FPDF_CloseDocument(printDocPtr);\n this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, "Failed to import pages for printing");\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `PreparePrintDocument`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.CantImportPages,\n message: "Failed to import pages for printing"\n });\n }\n if (!includeAnnotations) {\n const removalResult = this.removeAnnotationsFromPrintDocument(printDocPtr);\n if (!removalResult.success) {\n this.pdfiumModule.FPDF_CloseDocument(printDocPtr);\n this.logger.error(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `Failed to remove annotations: ${removalResult.error}`\n );\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `PreparePrintDocument`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: `Failed to prepare print document: ${removalResult.error}`\n });\n }\n this.logger.debug(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `Removed ${removalResult.annotationsRemoved} annotations from ${removalResult.pagesProcessed} pages`\n );\n }\n const buffer = this.saveDocument(printDocPtr);\n this.pdfiumModule.FPDF_CloseDocument(printDocPtr);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `PreparePrintDocument`, "End", doc.id);\n return PdfTaskHelper.resolve(buffer);\n } catch (error) {\n if (printDocPtr) {\n this.pdfiumModule.FPDF_CloseDocument(printDocPtr);\n }\n this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, "preparePrintDocument failed", error);\n this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, `PreparePrintDocument`, "End", doc.id);\n return PdfTaskHelper.reject({\n code: PdfErrorCode.Unknown,\n message: error instanceof Error ? error.message : "Failed to prepare print document"\n });\n }\n }\n /**\n * Removes all annotations from a print document using fast raw annotation functions.\n * This method is optimized for performance by avoiding full page loading.\n *\n * @param printDocPtr - Pointer to the print document\n * @returns Result object with success status and statistics\n *\n * @private\n */\n removeAnnotationsFromPrintDocument(printDocPtr) {\n let totalAnnotationsRemoved = 0;\n let pagesProcessed = 0;\n try {\n const pageCount = this.pdfiumModule.FPDF_GetPageCount(printDocPtr);\n for (let pageIndex = 0; pageIndex < pageCount; pageIndex++) {\n const annotCount = this.pdfiumModule.EPDFPage_GetAnnotCountRaw(printDocPtr, pageIndex);\n if (annotCount <= 0) {\n pagesProcessed++;\n continue;\n }\n let annotationsRemovedFromPage = 0;\n for (let annotIndex = annotCount - 1; annotIndex >= 0; annotIndex--) {\n const removed = this.pdfiumModule.EPDFPage_RemoveAnnotRaw(\n printDocPtr,\n pageIndex,\n annotIndex\n );\n if (removed) {\n annotationsRemovedFromPage++;\n totalAnnotationsRemoved++;\n } else {\n this.logger.warn(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `Failed to remove annotation ${annotIndex} from page ${pageIndex}`\n );\n }\n }\n if (annotationsRemovedFromPage > 0) {\n const pagePtr = this.pdfiumModule.FPDF_LoadPage(printDocPtr, pageIndex);\n if (pagePtr) {\n this.pdfiumModule.FPDFPage_GenerateContent(pagePtr);\n this.pdfiumModule.FPDF_ClosePage(pagePtr);\n }\n }\n pagesProcessed++;\n }\n return {\n success: true,\n annotationsRemoved: totalAnnotationsRemoved,\n pagesProcessed\n };\n } catch (error) {\n return {\n success: false,\n annotationsRemoved: totalAnnotationsRemoved,\n pagesProcessed,\n error: error instanceof Error ? error.message : "Unknown error during annotation removal"\n };\n }\n }\n /**\n * Sanitizes and validates a page range string.\n * Ensures page numbers are within valid bounds and properly formatted.\n *\n * @param pageRange - Page range string (e.g., "1,3,5-7") or null for all pages\n * @param totalPages - Total number of pages in the document\n * @returns Sanitized page range string or null for all pages\n *\n * @private\n */\n sanitizePageRange(pageRange, totalPages) {\n if (!pageRange || pageRange.trim() === "") {\n return null;\n }\n try {\n const sanitized = [];\n const parts = pageRange.split(",");\n for (const part of parts) {\n const trimmed = part.trim();\n if (trimmed.includes("-")) {\n const [startStr, endStr] = trimmed.split("-").map((s) => s.trim());\n const start = parseInt(startStr, 10);\n const end = parseInt(endStr, 10);\n if (isNaN(start) || isNaN(end)) {\n this.logger.warn(LOG_SOURCE$1, LOG_CATEGORY$1, `Invalid range: ${trimmed}`);\n continue;\n }\n const validStart = Math.max(1, Math.min(start, totalPages));\n const validEnd = Math.max(1, Math.min(end, totalPages));\n for (let i = validStart; i <= validEnd; i++) {\n if (!sanitized.includes(i)) {\n sanitized.push(i);\n }\n }\n } else {\n const pageNum = parseInt(trimmed, 10);\n if (isNaN(pageNum)) {\n this.logger.warn(LOG_SOURCE$1, LOG_CATEGORY$1, `Invalid page number: ${trimmed}`);\n continue;\n }\n const validPageNum = Math.max(1, Math.min(pageNum, totalPages));\n if (!sanitized.includes(validPageNum)) {\n sanitized.push(validPageNum);\n }\n }\n }\n if (sanitized.length === 0) {\n this.logger.warn(LOG_SOURCE$1, LOG_CATEGORY$1, "No valid pages in range, using all pages");\n return null;\n }\n sanitized.sort((a, b) => a - b);\n const optimized = [];\n let rangeStart = sanitized[0];\n let rangeEnd = sanitized[0];\n for (let i = 1; i < sanitized.length; i++) {\n if (sanitized[i] === rangeEnd + 1) {\n rangeEnd = sanitized[i];\n } else {\n if (rangeStart === rangeEnd) {\n optimized.push(rangeStart.toString());\n } else if (rangeEnd - rangeStart === 1) {\n optimized.push(rangeStart.toString());\n optimized.push(rangeEnd.toString());\n } else {\n optimized.push(`${rangeStart}-${rangeEnd}`);\n }\n rangeStart = sanitized[i];\n rangeEnd = sanitized[i];\n }\n }\n if (rangeStart === rangeEnd) {\n optimized.push(rangeStart.toString());\n } else if (rangeEnd - rangeStart === 1) {\n optimized.push(rangeStart.toString());\n optimized.push(rangeEnd.toString());\n } else {\n optimized.push(`${rangeStart}-${rangeEnd}`);\n }\n const result = optimized.join(",");\n this.logger.debug(\n LOG_SOURCE$1,\n LOG_CATEGORY$1,\n `Sanitized page range: "${pageRange}" -> "${result}"`\n );\n return result;\n } catch (error) {\n this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, `Error sanitizing page range: ${error}`);\n return null;\n }\n }\n}\nconst LOG_SOURCE = "PdfiumNativeRunner";\nconst LOG_CATEGORY = "Worker";\nclass PdfiumNativeRunner {\n constructor(logger) {\n this.native = null;\n this.activeTasks = /* @__PURE__ */ new Map();\n this.logger = logger ?? new NoopLogger();\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "PdfiumNativeRunner created");\n }\n /**\n * Initialize PDFium with WASM binary\n */\n async prepare(wasmBinary, logger) {\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "Preparing PDFium...");\n try {\n const module = await init({ wasmBinary });\n this.native = new PdfiumNative(module, { logger: logger ?? this.logger });\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "PDFium initialized successfully");\n } catch (error) {\n this.logger.error(LOG_SOURCE, LOG_CATEGORY, "Failed to initialize PDFium:", error);\n throw error;\n }\n }\n /**\n * Start listening for messages\n */\n listen() {\n self.onmessage = (evt) => {\n this.handle(evt);\n };\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "Listening for messages");\n }\n /**\n * Handle incoming messages\n */\n handle(evt) {\n const request = evt.data;\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "Received message:", request.type);\n try {\n switch (request.type) {\n case "init":\n this.handleInit(request);\n break;\n case "execute":\n this.handleExecute(request);\n break;\n default:\n this.logger.warn(LOG_SOURCE, LOG_CATEGORY, "Unknown message type:", request.type);\n }\n } catch (error) {\n this.logger.error(LOG_SOURCE, LOG_CATEGORY, "Error handling message:", error);\n this.respond({\n id: request.id,\n type: "error",\n error: {\n type: "reject",\n reason: { code: PdfErrorCode.Unknown, message: String(error) }\n }\n });\n }\n }\n /**\n * Handle initialization request\n */\n async handleInit(request) {\n if (!request.wasmUrl) {\n this.respond({\n id: request.id,\n type: "error",\n error: {\n type: "reject",\n reason: { code: PdfErrorCode.Unknown, message: "Missing wasmUrl" }\n }\n });\n return;\n }\n try {\n const response = await fetch(request.wasmUrl);\n const wasmBinary = await response.arrayBuffer();\n await this.prepare(wasmBinary);\n this.respond({\n id: request.id,\n type: "ready"\n });\n } catch (error) {\n this.respond({\n id: request.id,\n type: "error",\n error: {\n type: "reject",\n reason: { code: PdfErrorCode.Unknown, message: String(error) }\n }\n });\n }\n }\n /**\n * Handle method execution request\n */\n async handleExecute(request) {\n if (!this.native) {\n this.respond({\n id: request.id,\n type: "error",\n error: {\n type: "reject",\n reason: { code: PdfErrorCode.NotReady, message: "PDFium not initialized" }\n }\n });\n return;\n }\n if (!request.method) {\n this.respond({\n id: request.id,\n type: "error",\n error: {\n type: "reject",\n reason: { code: PdfErrorCode.Unknown, message: "Missing method name" }\n }\n });\n return;\n }\n const method = request.method;\n const args = request.args ?? [];\n if (!(method in this.native) || typeof this.native[method] !== "function") {\n this.respond({\n id: request.id,\n type: "error",\n error: {\n type: "reject",\n reason: { code: PdfErrorCode.NotSupport, message: `Method ${method} not supported` }\n }\n });\n return;\n }\n try {\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, `Executing method: ${method}`);\n const result = this.native[method](...args);\n if (result && typeof result === "object" && "wait" in result) {\n const task = result;\n this.activeTasks.set(request.id, task);\n task.onProgress((progress) => {\n this.respond({\n id: request.id,\n type: "progress",\n progress\n });\n });\n task.wait(\n (data) => {\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, `Method ${method} resolved`);\n this.respond({\n id: request.id,\n type: "result",\n data\n });\n this.activeTasks.delete(request.id);\n },\n (error) => {\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, `Method ${method} failed:`, error);\n this.respond({\n id: request.id,\n type: "error",\n error\n });\n this.activeTasks.delete(request.id);\n }\n );\n } else {\n this.respond({\n id: request.id,\n type: "result",\n data: result\n });\n }\n } catch (error) {\n this.logger.error(LOG_SOURCE, LOG_CATEGORY, `Error executing ${method}:`, error);\n this.respond({\n id: request.id,\n type: "error",\n error: {\n type: "reject",\n reason: { code: PdfErrorCode.Unknown, message: String(error) }\n }\n });\n }\n }\n /**\n * Send response back to main thread\n */\n respond(response) {\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "Sending response:", response.type);\n self.postMessage(response);\n }\n /**\n * Ready notification\n */\n ready() {\n this.listen();\n this.respond({\n id: "0",\n type: "ready"\n });\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "Runner is ready");\n }\n}\nclass PdfiumEngineRunner extends PdfiumNativeRunner {\n /**\n * Create an instance of PdfiumEngineRunner\n * @param wasmBinary - wasm binary that contains the pdfium wasm file\n * @param logger - optional logger instance\n * @param fontFallback - optional font fallback configuration\n */\n constructor(wasmBinary, logger, fontFallback) {\n super(logger);\n this.wasmBinary = wasmBinary;\n this.fontFallback = fontFallback;\n }\n /**\n * Initialize runner\n */\n async prepare() {\n const wasmBinary = this.wasmBinary;\n const wasmModule = await init({ wasmBinary });\n this.native = new PdfiumNative(wasmModule, {\n logger: this.logger,\n fontFallback: this.fontFallback\n });\n this.ready();\n }\n}\nconst fonts$6 = [\n { file: "NotoSansJP-Thin.otf", weight: 100 },\n { file: "NotoSansJP-Light.otf", weight: 300 },\n { file: "NotoSansJP-DemiLight.otf", weight: 350 },\n { file: "NotoSansJP-Regular.otf", weight: 400 },\n { file: "NotoSansJP-Medium.otf", weight: 500 },\n { file: "NotoSansJP-Bold.otf", weight: 700 },\n { file: "NotoSansJP-Black.otf", weight: 900 }\n];\nconst fonts$5 = [\n { file: "NotoSansKR-Thin.otf", weight: 100 },\n { file: "NotoSansKR-Light.otf", weight: 300 },\n { file: "NotoSansKR-DemiLight.otf", weight: 350 },\n { file: "NotoSansKR-Regular.otf", weight: 400 },\n { file: "NotoSansKR-Medium.otf", weight: 500 },\n { file: "NotoSansKR-Bold.otf", weight: 700 },\n { file: "NotoSansKR-Black.otf", weight: 900 }\n];\nconst fonts$4 = [\n { file: "NotoSansHans-Light.otf", weight: 300 },\n { file: "NotoSansHans-DemiLight.otf", weight: 350 },\n { file: "NotoSansHans-Regular.otf", weight: 400 },\n { file: "NotoSansHans-Medium.otf", weight: 500 },\n { file: "NotoSansHans-Bold.otf", weight: 700 }\n];\nconst fonts$3 = [\n { file: "NotoSansHant-Thin.otf", weight: 100 },\n { file: "NotoSansHant-Light.otf", weight: 300 },\n { file: "NotoSansHant-DemiLight.otf", weight: 350 },\n { file: "NotoSansHant-Regular.otf", weight: 400 },\n { file: "NotoSansHant-Medium.otf", weight: 500 },\n { file: "NotoSansHant-Bold.otf", weight: 700 },\n { file: "NotoSansHant-Black.otf", weight: 900 }\n];\nconst fonts$2 = [\n { file: "NotoNaskhArabic-Regular.ttf", weight: 400 },\n { file: "NotoNaskhArabic-Bold.ttf", weight: 700 }\n];\nconst fonts$1 = [\n { file: "NotoSansHebrew-Regular.ttf", weight: 400 },\n { file: "NotoSansHebrew-Bold.ttf", weight: 700 }\n];\nconst fonts = [\n // Thin (100)\n { file: "NotoSans-Thin.ttf", weight: 100 },\n { file: "NotoSans-ThinItalic.ttf", weight: 100, italic: true },\n // ExtraLight (200)\n { file: "NotoSans-ExtraLight.ttf", weight: 200 },\n { file: "NotoSans-ExtraLightItalic.ttf", weight: 200, italic: true },\n // Light (300)\n { file: "NotoSans-Light.ttf", weight: 300 },\n { file: "NotoSans-LightItalic.ttf", weight: 300, italic: true },\n // Regular (400)\n { file: "NotoSans-Regular.ttf", weight: 400 },\n { file: "NotoSans-Italic.ttf", weight: 400, italic: true },\n // Medium (500)\n { file: "NotoSans-Medium.ttf", weight: 500 },\n { file: "NotoSans-MediumItalic.ttf", weight: 500, italic: true },\n // SemiBold (600)\n { file: "NotoSans-SemiBold.ttf", weight: 600 },\n { file: "NotoSans-SemiBoldItalic.ttf", weight: 600, italic: true },\n // Bold (700)\n { file: "NotoSans-Bold.ttf", weight: 700 },\n { file: "NotoSans-BoldItalic.ttf", weight: 700, italic: true },\n // ExtraBold (800)\n { file: "NotoSans-ExtraBold.ttf", weight: 800 },\n { file: "NotoSans-ExtraBoldItalic.ttf", weight: 800, italic: true },\n // Black (900)\n { file: "NotoSans-Black.ttf", weight: 900 },\n { file: "NotoSans-BlackItalic.ttf", weight: 900, italic: true }\n];\nfunction buildCdnUrls(version = "latest") {\n return {\n jp: `https://cdn.jsdelivr.net/npm/@embedpdf/fonts-jp@${version}/fonts`,\n kr: `https://cdn.jsdelivr.net/npm/@embedpdf/fonts-kr@${version}/fonts`,\n sc: `https://cdn.jsdelivr.net/npm/@embedpdf/fonts-sc@${version}/fonts`,\n tc: `https://cdn.jsdelivr.net/npm/@embedpdf/fonts-tc@${version}/fonts`,\n arabic: `https://cdn.jsdelivr.net/npm/@embedpdf/fonts-arabic@${version}/fonts`,\n hebrew: `https://cdn.jsdelivr.net/npm/@embedpdf/fonts-hebrew@${version}/fonts`,\n latin: `https://cdn.jsdelivr.net/npm/@embedpdf/fonts-latin@${version}/fonts`\n };\n}\nfunction toFontVariants(fonts2, baseUrl) {\n return fonts2.map((f) => ({\n url: `${baseUrl}/${f.file}`,\n weight: f.weight,\n italic: f.italic\n }));\n}\nfunction buildCdnFontConfig(urls) {\n return {\n fonts: {\n [FontCharset.SHIFTJIS]: toFontVariants(fonts$6, urls.jp),\n [FontCharset.HANGEUL]: toFontVariants(fonts$5, urls.kr),\n [FontCharset.GB2312]: toFontVariants(fonts$4, urls.sc),\n [FontCharset.CHINESEBIG5]: toFontVariants(fonts$3, urls.tc),\n [FontCharset.ARABIC]: toFontVariants(fonts$2, urls.arabic),\n [FontCharset.HEBREW]: toFontVariants(fonts$1, urls.hebrew),\n [FontCharset.CYRILLIC]: toFontVariants(fonts, urls.latin),\n [FontCharset.GREEK]: toFontVariants(fonts, urls.latin),\n [FontCharset.VIETNAMESE]: toFontVariants(fonts, urls.latin)\n }\n };\n}\nconst FONT_CDN_URLS = buildCdnUrls("latest");\nconst cdnFontConfig = buildCdnFontConfig(FONT_CDN_URLS);\nlet runner = null;\nself.onmessage = async (event) => {\n const { type, wasmUrl, logger: serializedLogger, fontFallback } = event.data;\n if (type === "wasmInit" && wasmUrl && !runner) {\n try {\n const response = await fetch(wasmUrl);\n const wasmBinary = await response.arrayBuffer();\n const logger = serializedLogger ? deserializeLogger(serializedLogger) : void 0;\n const effectiveFontFallback = fontFallback === null ? void 0 : fontFallback ?? cdnFontConfig;\n runner = new PdfiumEngineRunner(wasmBinary, logger, effectiveFontFallback);\n await runner.prepare();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n self.postMessage({ type: "wasmError", error: message });\n }\n }\n};\n'],{type:"application/javascript"})),{type:"module"}),u=new l(d,{wasmUrl:t,logger:a,fontFallback:s}),c=URL.createObjectURL(new Blob(['async function encodeImage(imageData, imageType, quality) {\n if (typeof OffscreenCanvas === "undefined") {\n throw new Error("OffscreenCanvas is not available in this worker environment");\n }\n const { data, width, height } = imageData;\n const imgData = new ImageData(new Uint8ClampedArray(data), width, height);\n const canvas = new OffscreenCanvas(width, height);\n const ctx = canvas.getContext("2d");\n if (!ctx) {\n throw new Error("Failed to get 2D context from OffscreenCanvas");\n }\n ctx.putImageData(imgData, 0, 0);\n return canvas.convertToBlob({ type: imageType, quality });\n}\nself.onmessage = async (event) => {\n const request = event.data;\n if (request.type !== "encode") {\n return;\n }\n try {\n const { imageData, imageType, quality } = request.data;\n const blob = await encodeImage(imageData, imageType, quality);\n const response = {\n id: request.id,\n type: "result",\n data: blob\n };\n self.postMessage(response);\n } catch (error) {\n const response = {\n id: request.id,\n type: "error",\n data: {\n message: error instanceof Error ? error.message : String(error)\n }\n };\n self.postMessage(response);\n }\n};\n'],{type:"application/javascript"})),m=new p(i??2,c,a);return new n(u,{imageConverter:e(m),logger:a})}export{m as createPdfiumEngine};