/*!
 * Nutrient Web SDK 1.12.0 (https://www.nutrient.io/sdk/web)
 *
 * Copyright (c) 2016-2026 PSPDFKit GmbH. All rights reserved.
 *
 * THIS SOURCE CODE AND ANY ACCOMPANYING DOCUMENTATION ARE PROTECTED BY INTERNATIONAL COPYRIGHT LAW
 * AND MAY NOT BE RESOLD OR REDISTRIBUTED. USAGE IS BOUND TO THE PSPDFKIT LICENSE AGREEMENT.
 * UNAUTHORIZED REPRODUCTION OR DISTRIBUTION IS SUBJECT TO CIVIL AND CRIMINAL PENALTIES.
 * This notice may not be removed from this file.
 *
 * PSPDFKit uses several open source third-party components: https://www.nutrient.io/legal/acknowledgements/web-acknowledgements/
 */
"use strict";(globalThis.webpackChunkNutrientViewer=globalThis.webpackChunkNutrientViewer||[]).push([[42],{5232:(e,t,n)=>{n.d(t,{mG:()=>ce,Ay:()=>le,DO:()=>de,mn:()=>he});var i=n(34724),a=n(64836),s=n(26128),r=n(66080),o=n(57191),c=n(13803),l=n(84008),d=n(86682),h=n(58970),u=n(52967),m=n(59179),p=n(92079),g=n(67057),f=n(14023),y=n(80354),b=n(35167),A=n(53598),S=n(38116),v=n(80626),w=n(34964),P=n(50236),_=n(13069),F=n(70191),k=n(94110),C=n(10023),D=n(20569),T=n(35960),I=n(86223),R=n(22215),E=n(38468),x=n(98888);class O{constructor(e,t){this.identifier=e,this.callback=t}request(){return this.callback()}}var V=n(92042),B=n(34518),L=n(12446),U=n(49105),N=n(25668),z=n(86708),q=n(77734),j=n(63796),M=n(17231);class $ extends((0,o.mS)({alreadyLoadedPages:(0,o.T5)(),isLoaded:!1,isDestroyed:!1})){}const K={skippedPdfObjectIds:[],skippedPdfBookmarkIds:[],annotations:[],bookmarks:[],formFieldValues:[],formFields:[],attachments:{}};class W{constructor(e,t){(0,i.A)(this,"_state",new $),(0,i.A)(this,"_formFieldsLoadedPromise",null),(0,i.A)(this,"_objectCreationPromises",(0,o.T5)()),(0,i.A)(this,"_loadBookmarksPromise",null),(0,i.A)(this,"_commentsLoadedPromise",null),(0,i.A)(this,"canCreateBackendOrphanWidgets",!1),(0,i.A)(this,"updateTabOrderTimeout",null),(0,i.A)(this,"pagesTabOrderToUpdate",(0,o.NZ)()),this._core=e,this._json=t?(0,r.$y)(t):null,this._setReadStateCallbacksPromise=new Promise(e=>{this._setReadStateCallbacksPromiseResolve=e})}async load(){if(this._state=this._state.set("isLoaded",!0),!this._formFieldCallbacks&&await this._loadFormFieldValues(),!this._json)return this;await this._core.importInstantJSON({...K,...this._json}),(0,r.V1)(this._json);const{annotations:e,attachments:t}=this._json;if(this._isDestroyed()||!t||0===Object.entries(t).length)return this;if(e)for(let n=0;n<e.length;n++){let i=null;const a=e[n];if("imageAttachmentId"in a&&a.imageAttachmentId){const e=t?t[a.imageAttachmentId]:null;if(e)try{i=(0,q.lj)(atob(e.binary),e.contentType),(0,r.V1)(this._annotationCallbacks),this._annotationCallbacks.createAttachment(a.imageAttachmentId,i)}catch(e){(0,r.pq)(`Skipped attachment with id ${a.imageAttachmentId} from payload because an error occurred while converting the binary image to blob.`),(0,r.pq)(e)}}}return this}destroy(){this._state=this._state.set("isDestroyed",!0),this._annotationCallbacks=null,this._readStateCallbacks=null,this._bookmarkCallbacks=null,this._formFieldCallbacks=null,this._formFieldValueCallbacks=null,this._commentCallbacks=null}setReadStateCallbacks(e){this._readStateCallbacks=e,this._setReadStateCallbacksPromiseResolve?.()}setAnnotationCallbacks(e){this._annotationCallbacks=e}setBookmarkCallbacks(e){this._bookmarkCallbacks=e}setFormFieldCallbacks(e){this._formFieldCallbacks=e}setFormFieldValueCallbacks(e){this._formFieldValueCallbacks=e}setCommentCallbacks(e){this._commentCallbacks=e}createComment(e,t,n){return this._core.applyComments(t.map(e=>H(e,n)).toArray())}updateComment(e,t,n){return this._core.applyComments(t.map(e=>H(e,n)).toArray())}deleteComment(e,t,n){return this._core.applyComments(t.map(e=>H(e,n)).toArray())}async loadComments(){return this._commentsLoadedPromise||(this._commentsLoadedPromise=this._loadComments()),this._commentsLoadedPromise}async _loadComments(){this._verifyLoaded();const e=await this._core.getComments()??[],t=(0,o.B8)(e.map(e=>{let t;return t=e.pdfObjectId?e.id||e.pdfObjectId?.toString():(0,_.K1)(),(0,L.XL)(t,e)}));await Promise.all(t.map(e=>"number"==typeof e.pageIndex&&this.loadAnnotationsForPageIndex(e.pageIndex)).filter(Boolean).toArray()),this._commentCallbacks?.createComments(t,M.n),this._commentsLoadedPromise=Promise.resolve()}async updateTabOrder(e){this.pagesTabOrderToUpdate=this.pagesTabOrderToUpdate.add(e),this.updateTabOrderTimeout&&clearTimeout(this.updateTabOrderTimeout),this.updateTabOrderTimeout=setTimeout(async()=>{const e=this.pagesTabOrderToUpdate.toArray();if(this.pagesTabOrderToUpdate=(0,o.NZ)(),this._isDestroyed())return;const t=await Promise.all(e.map(e=>this._core.getTabOrder(e)));this._isDestroyed()||((0,r.V1)(this._annotationCallbacks),(0,N.vA)(()=>{e.forEach((e,n)=>{this._annotationCallbacks?.setPageTabOrder(e,t[n])})}))},1e3)}async setTabOrder(e,t){return this._core.setTabOrder(e,t)}async createAnnotation(e,t){this._verifyLoaded();const n=t.find((t,n)=>((0,r.V1)("imageAttachmentId"in e,"Annotation must have imageAttachmentId."),n===e.imageAttachmentId)),i=await this._core.createAnnotation((0,L.eq)(e),n?n.data:null);"number"!=typeof i||"number"!=typeof e.pdfObjectId||e.pdfObjectId===i||this._isDestroyed()||((0,r.V1)(this._annotationCallbacks),this._annotationCallbacks.updateAnnotations((0,o.B8)([e.set("pdfObjectId",i)]))),await this.updateTabOrder(e.pageIndex)}async updateAnnotation(e){this._verifyLoaded(),await this._core.updateAnnotation((0,L.eq)(e)),await this.updateTabOrder(e.pageIndex)}deleteAnnotation(e){return this._verifyLoaded(),this._core.deleteAnnotation((0,L.eq)(e))}createBookmark(e){return this._verifyLoaded(),this._core.createBookmark((0,z.U)(e))}updateBookmark(e){return this._verifyLoaded(),this._core.updateBookmark((0,z.U)(e))}deleteBookmark(e){return this._verifyLoaded(),this._core.deleteBookmark(e)}createFormField(e){this._verifyLoaded(),(0,r.V1)(this._readStateCallbacks);const t=this._readStateCallbacks.getFormFieldWidgets(e);return this._core.createFormField((0,L.T7)(e),t.map(e=>(0,L.eq)(e)).toArray()).then(async e=>{(0,N.vA)(()=>{e.forEach((e,n)=>{const i=t.get(n);(0,r.V1)(i),(0,r.V1)(this._annotationCallbacks),"number"!=typeof e||"number"!=typeof i.pdfObjectId||i.pdfObjectId===e||this._isDestroyed()||this._annotationCallbacks.updateAnnotations((0,o.B8)([i.set("pdfObjectId",e)]))})})})}updateFormField(e){this._verifyLoaded(),(0,r.V1)(this._readStateCallbacks);const t=this._readStateCallbacks.getFormFieldWidgets(e);return this._core.updateFormField((0,L.T7)(e),t.map(e=>(0,L.eq)(e)).toArray())}deleteFormField(e){return this._verifyLoaded(),this._core.deleteFormField((0,L.T7)(e))}loadFormFields(){return this._formFieldsLoadedPromise||(this._formFieldsLoadedPromise=this._loadFormFields()),this._formFieldsLoadedPromise}async _loadFormFields(){this._verifyLoaded();const e=await this._core.readFormJSONObjects();if(this._isDestroyed())return;let t=(0,o.B8)(),n=(0,o.B8)().withMutations(n=>{e.forEach(e=>{const{formField:i,widgets:a,value:s}=e;try{let e;e=i.pdfObjectId?i.pdfObjectId.toString():(0,_.K1)();const o=(0,L.mh)(e,i);(0,r.V1)(this._readStateCallbacks),this._readStateCallbacks.isFormFieldInState(o.name)||n.push(o.set("value",s)),a.forEach(e=>{if(e.formFieldName!==o.name)return;let n;n=e.pdfObjectId?e.id||e.pdfObjectId.toString():(0,_.K1)(),(0,r.V1)(this._readStateCallbacks),t=t.push((0,L.h8)(n,e))})}catch(e){(0,r.pq)(`Skipped creating form field #${i.pdfObjectId} from payload because an error occurred while deserializing.`),(0,r.pq)(e)}})});const i={},a={};t.forEach(e=>{a[e.id]||(a[e.id]=[]),a[e.id].push(e.pdfObjectId)}),t=t.map(e=>{if(a[e.id].filter(t=>t!==e.pdfObjectId).length>0&&e.pdfObjectId?.toString()!==e.id||this._readStateCallbacks?.isAnnotationInState(e.id)){const t=(0,_.K1)();return i[e.formFieldName]?i[e.formFieldName].push({[e.id]:t}):i[e.formFieldName]=[{[e.id]:t}],n=n.map(n=>n.name===e.formFieldName?n.update("annotationIds",n=>n?.map(n=>n===e.id?t:n)):n),e.set("id",t)}return e}),Object.keys(i).forEach(e=>{const i=n.find(t=>t.name===e);(0,r.V1)(i);const a=t.filter(t=>t.formFieldName===e).toArray().map(e=>(0,L.eq)(e));this._core.updateFormField((0,L.T7)(i),a)}),n.size>0&&!this._isDestroyed()&&((0,r.V1)(this._formFieldCallbacks),this._formFieldCallbacks.createFormFields(n,M.n)),await this._loadFormFieldValues(),t.size>0&&!this._isDestroyed()&&((0,r.V1)(this._annotationCallbacks),this._annotationCallbacks.createAnnotations(t,(0,o.T5)(),M.n)),this._formFieldsLoadedPromise=Promise.resolve()}createFormFieldValue(e){return this._verifyLoaded(),this.setFormFieldValue(e)}setFormFieldValue(e){return this._verifyLoaded(),this._core.setFormFieldValue((0,L.cA)(e))}deleteFormFieldValue(e){return this._verifyLoaded(),this._core.deleteFormFieldValue(e.replace("form-field-value/",""))}loadAnnotationsForPageIndex(e){const t=this._state.alreadyLoadedPages.get(e);if(t)return t;const n=this._loadAnnotationsForPageIndex(e);return this._state=this._state.setIn(["alreadyLoadedPages",e],n),n}async _loadAnnotationsForPageIndex(e){this._verifyLoaded();const[t,n]=await Promise.all([this._core.annotationsForPageIndex(e),this._core.getTabOrder(e)]);if(this._isDestroyed())return;const i=[],a=[],s=t.map(e=>{let{rollover:t,down:n,...s}=e;return t&&"number"==typeof s.pdfObjectId&&i.push(s.pdfObjectId),n&&"number"==typeof s.pdfObjectId&&a.push(s.pdfObjectId),s}).filter(e=>"number"==typeof e.pageIndex);this._formFieldCallbacks&&await this.loadFormFields();const c=(0,o.B8)().withMutations(e=>{s.filter(e=>!e.id||this._readStateCallbacks&&!this._readStateCallbacks.isAnnotationInState(e.id)).forEach(t=>{t.pdfObjectId;try{let n;n=function(e){return"pspdfkit/link"===e.type&&0===e.pdfObjectId}(t)?t.id||(0,_.K1)():t.id||t.pdfObjectId.toString(),(e.some(e=>e.id===n)||this._readStateCallbacks?.isAnnotationInState(n))&&(n=(0,_.K1)(),t.id=n,this._core.updateAnnotation(t));const i=(0,L.h8)(n,t);e.push(i)}catch(e){(0,r.pq)(`Skipped creating annotation #${t.pdfObjectId} from payload because an error occurred while deserializing.`),(0,r.pq)(e)}})});(0,N.vA)(()=>{(0,r.V1)(this._annotationCallbacks),c.size>0&&this._annotationCallbacks.createAnnotations(c,(0,o.T5)(),M.n),this._annotationCallbacks.setPageTabOrder(e,n),i.length>0&&this._annotationCallbacks.addAnnotationVariants("rollover",i),a.length>0&&this._annotationCallbacks.addAnnotationVariants("down",a)}),this._state=this._state.setIn(["alreadyLoadedPages",e],Promise.resolve())}async _loadFormFieldValues(){this._verifyLoaded();const e=await this._core.getFormValues();if(this._isDestroyed())return;const t=(0,o.B8)().withMutations(t=>{e.forEach(e=>{try{t.push((0,L.R5)(e))}catch(t){(0,r.pq)(`Skipped creating form field value #${e.pdfObjectId} from payload because an error occurred while deserializing.`),(0,r.pq)(t)}})});t.size>0&&!this._isDestroyed()&&((0,r.V1)(this._formFieldValueCallbacks),this._formFieldValueCallbacks.setFormFieldValues(t))}async loadBookmarks(){this._verifyLoaded();const e=await this._core.getBookmarks();if(this._isDestroyed())return;const t=(0,o.B8)().withMutations(t=>{e.forEach(e=>{let n;n=e.id?e.id:e.pdfBookmarkId?e.pdfBookmarkId:(0,j.z)();try{t.push((0,z.r)(n,e))}catch(e){(0,r.pq)(`Skipped creating bookmark #${n} from payload because an error occurred while deserializing.`),(0,r.pq)(e)}})});t.size>0&&!this._isDestroyed()&&((0,r.V1)(this._bookmarkCallbacks),this._bookmarkCallbacks.createBookmarks(t,M.n))}_verifyLoaded(){(0,r.V1)(this._state.isLoaded,"StandaloneProvider not properly initialized.")}_isDestroyed(){return this._state.isDestroyed}async syncChanges(){}}function H(e,t){(0,r.V1)(e.rootId,"A new comment must have `rootId` present");const n=t.get(e.rootId);return(0,r.V1)(n,"An annotation must be present linked to the comment to create"),(0,L.wG)(e,n.pdfObjectId?.toString()===n.id?parseInt(e.rootId):e.rootId)}function Q(e){return"string"==typeof e?.serialNumber&&e.body instanceof ArrayBuffer}function J(e){return e?.pkcs7 instanceof ArrayBuffer&&(!("ocspResponses"in e)||Array.isArray(e.ocspResponses)&&e.ocspResponses.every(e=>Q(e)))}function G(e){if(!e)return!1;const{signedData:t,timestampResponse:n,ocspResponses:i}=e;if(!(t instanceof ArrayBuffer))return!1;if(n&&!(n instanceof ArrayBuffer))return!1;if(i){if(!Array.isArray(i))return!1;if(!i.every(e=>Q(e)))return!1}return!0}var X=n(23111),Y=n(65276);class Z{constructor(e){this.backend=e}async signDocumentAndReload(e,t){const n=e?.signingData,i=n?.certificates;(0,r.V1)(void 0===t||"function"==typeof t,"On a Standalone deployment, when `signaturePreparationData.signingData.privateKey` is not provided, `twoStepSignatureCallbackOrSigningServiceData` must be a function or `NutrientViewer.StandaloneSigningServiceData`."),(0,r.V1)(!n?.timestamp||"string"==typeof n?.timestamp?.url,"The `url` property of `signingData.timestamp` must be a string."),(0,r.V1)(!n?.timestamp||!n?.timestamp?.password||"string"==typeof n?.timestamp?.password,"The `password` property of `signingData.timestamp` must be a string."),(0,r.V1)(!n?.timestamp||!n?.timestamp?.username||"string"==typeof n?.timestamp?.username,"The `username` property of `signingData.timestamp` must be a string."),(0,r.V1)(void 0===n?.ltv||"boolean"==typeof n?.ltv,"The `ltv` property of `signingData` must be a boolean if set."),(0,r.V1)(void 0===n?.ltv||"boolean"==typeof n?.ltv,"The `ltv` property of `signingData` must be a boolean if set."),(0,r.V1)(!n||!n.signatureType||n.signatureType===X.D.CMS||Array.isArray(i)&&i.length>0&&i.every(e=>Boolean(e instanceof ArrayBuffer&&e.byteLength>0||"string"==typeof e&&e.length>0)),"For signatures of type `NutrientViewer.SignatureType.CAdES` an `Array` of certificates must be provided in `signaturePreparationData.signingData.certificates`.");const a={signatureType:n?.signatureType||(Array.isArray(i)&&i.length>0?X.D.CAdES:X.D.CMS),...i&&{certificates:i.map(e=>e instanceof ArrayBuffer?c.o4.fromUint8Array(new Uint8Array(e)):c.o4.encode(e))},...e?.placeholderSize?{estimatedSize:e.placeholderSize}:null};try{const{hash:i,signatureFormFieldName:s,file:o,fileContents:l,dataToBeSigned:d}=await this.backend.client.prepareSign((0,L.Y6)(a),e?.signatureMetadata?(0,L.sZ)(e.signatureMetadata):null,Boolean(e?.flatten),e?.formFieldName,(0,L.qN)(e?.position),await(0,L.z8)(e?.appearance)),h=function(e){const t=e.trim(),n=t.length/2,i=new Uint8Array(n);for(let e=0;e<n;e++)i[e]=parseInt(t.substr(2*e,2),16);return i}(d);let u,m,p;if(t){try{u=await t({hash:i,fileContents:l,dataToBeSigned:h})}catch(e){throw new r.uE(`\`twoStepSignatureCallback\` threw an error: ${e}`)}if(!(u instanceof ArrayBuffer||J(u)||G(u)))throw new r.uE(`The resolved value from \`twoStepSignatureCallback\` should be a an \`ArrayBuffer\`, \`SignatureCallbackResponsePkcs7\`, or \`SignatureCallbackResponseRaw\`, but is of type \`${typeof u}\` instead.`);p=u}else{if(!n?.privateKey)throw new r.uE("No `twoStepSignatureCallback` or `signingData.privateKey` was provided.");{const e={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"},modulusLength:2048,extractable:!1,publicExponent:new Uint8Array([1,0,1])},t=await globalThis.crypto.subtle.importKey("pkcs8",function(e){const t=e.split("\n");let n="";for(let e=0;e<t.length;e++){t[e].trim().length>0&&t[e].indexOf("-BEGIN RSA PRIVATE KEY-")<0&&t[e].indexOf("-BEGIN PRIVATE KEY-")<0&&t[e].indexOf("-BEGIN RSA PUBLIC KEY-")<0&&t[e].indexOf("-BEGIN CERTIFICATE-")<0&&t[e].indexOf("-END RSA PRIVATE KEY-")<0&&t[e].indexOf("-END PRIVATE KEY-")<0&&t[e].indexOf("-END RSA PUBLIC KEY-")<0&&t[e].indexOf("-END CERTIFICATE-")<0&&(n+=t[e].trim())}return c.o4.toUint8Array(n).buffer}(n.privateKey),e,!0,["sign"]);m=await globalThis.crypto.subtle.sign(e,t,h),p=m}}let g="",f=a.certificates||[];if(p instanceof ArrayBuffer)g=c.o4.fromUint8Array(new Uint8Array(p))||"";else if(J(p)){const e=p;g=c.o4.fromUint8Array(new Uint8Array(e.pkcs7))||""}else if(G(p)){const e=p;g=c.o4.fromUint8Array(new Uint8Array(e.signedData))||"",f=e.certificates.map(e=>e instanceof ArrayBuffer?c.o4.fromUint8Array(new Uint8Array(e)):c.o4.encode(e))}let y=null,b=[];if(n?.ltv&&(p instanceof ArrayBuffer?b=await this.backend.getRevocationResponses(f):(J(p)||G(p))&&((0,r.V1)(null==p.ocspResponses||Array.isArray(p.ocspResponses)&&p.ocspResponses.every(e=>Q(e)),"The `ocspResponses` property of `signatureData` must be a array of `OCSPResponses`."),b=p.ocspResponses?.map(e=>({response_code:200,body:c.o4.fromUint8Array(new Uint8Array(e.body)),token:e.serialNumber}))??[],b.length||((0,r.R8)("The `TwoStepSignatureCallback` didn't return certificate revocation responses; trying to fetch them online."),b=await this.backend.getRevocationResponses(f)))),G(p)){const e=p;(0,r.V1)(null==e.timestampResponse||e.timestampResponse instanceof ArrayBuffer,"The `timestampResponse` property of `signatureData` must be an `ArrayBuffer`."),e.timestampResponse&&(y={response_code:200,body:c.o4.fromUint8Array(new Uint8Array(e.timestampResponse)),token:"1234"})}if(!y&&n?.timestamp&&p instanceof ArrayBuffer){const e=c.o4.toUint8Array(g).buffer;y=await this.backend.timestampData(e,n.timestamp)}const A=await this.backend.client.sign(o,s,i,L.xz[a.signatureType],g,f,J(p)?"pkcs7":G(p)?"raw":n?.signatureContainer?n.signatureContainer:null,y,b);return n?.ltv&&A.signature.certificateChainValidationStatus===Y.k.ok_but_could_not_check_revocation&&(0,r.R8)("Document signed, but couldn't add certificate revocation information so the signature may not be LTV-enabled."),await this.backend.reloadDocument(),s}catch(e){throw await this.backend.client.restoreToOriginalState(),e}}}var ee=n(74075),te=n(97732),ne=n(95836);class ie extends Z{constructor(e){super(e)}async signDocumentAndReload(e,t){t=(0,S.k)(t),(0,r.V1)(t,"`twoStepSignatureCallbackOrStandaloneSigningServiceData` must be a `NutrientViewer.StandaloneSigningServiceData` object when performing signing via a backend service.");const{jwt:n,signingToken:i}=t,a=this.resolveApiBasePath(t),s=this.resolveServerUrl(t),o=await this.getCertificates(s,n,`${a}get_certificates`,i),c=this.signatureCallbackFactory(s,n,o,e,t,`${a}sign_hash`);return await super.signDocumentAndReload({...e,signingData:{...e?.signingData,signatureType:e?.signingData?.signatureType||X.D.CAdES,certificates:o}},c)}async getCertificates(e,t,n,i){let a;const s=`${e}${n}`;try{a=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${t}`,Accept:"application/json","Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({signingToken:i})})}catch(e){throw new r.uE(`The signing service failed to retrieve certificates: Failed to fetch from ${s}`)}if(!a.ok)throw new r.uE(`The signing service failed to retrieve certificates: ${await a.json()}`);const o=(await a.json())?.data||{};return o.certificates.concat(o.ca_certificates).map(e=>c.o4.fromBase64(e))}resolveApiBasePath(e){return(0,ee.i)(e.jwt).api_base_path||"/api/"}resolveServerUrl(e){const t=e.serverUrl||(0,ee.i)(e.jwt).server_url;return(0,r.V1)(t,"`twoStepSignatureCallbackOrStandaloneSigningServiceData.jwt` must contain claim `server_url` or the `twoStepSignatureCallbackOrStandaloneSigningServiceData.serverUrl` should be set"),t}signatureCallbackFactory(e,t,n,i,a,s){return async o=>{let l,{hash:d,dataToBeSigned:h}=o;try{l=await fetch(`${e}${s}`,{method:"POST",headers:{Authorization:`Bearer ${t}`,Accept:"application/json","Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({dataToBeSigned:c.o4.fromUint8Array(h),hash:d,signatureType:i?.signingData?.signatureType||X.D.CAdES,signingToken:a.signingToken,cadesLevel:i?.signingData?.padesLevel||te.s.b_lt})})}catch(t){throw new r.uE(`The signing service failed to retrieve certificates: Failed to fetch from ${e}${s}`)}if(!l.ok)throw new r.uE(`The signing service failed to sign: ${await l.text()}`);const u=(await l.json())?.data||{};if(i?.signingData?.signatureContainer===ne.Y.pkcs7){const e={pkcs7:c.o4.toUint8Array(u.pkcs7).buffer};return u.ocspResponses&&(e.ocspResponses=u.ocspResponses.map(e=>({serialNumber:e.serialNumber,body:c.o4.toUint8Array(e.body).buffer}))),e}{const e={certificates:n,signedData:c.o4.toUint8Array(u.signedData).buffer,timestampResponse:c.o4.toUint8Array(u.timestampResponse).buffer};return u.ocspResponses&&(e.ocspResponses=u.ocspResponses.map(e=>({serialNumber:e.serialNumber,body:c.o4.toUint8Array(e.body).buffer}))),e}}}}var ae=n(38751),se=n(63050);class re extends(o.mS({baseUrl:null,baseCoreUrl:null,baseProcessorEngineUrl:null,licenseKey:null,document:null,backendPermissions:new ae.A,documentResponse:null,disableWebAssemblyStreaming:!1,enableAutomaticLinkExtraction:!1,overrideMemoryLimit:null,features:(0,o.B8)(),signatureFeatureAvailability:se.g.NONE,documentHandle:null,trustedCAsCallback:null,signaturesInfoPromise:null,customFonts:null,fontSubstitutions:null,forceLegacySignaturesFeature:!1,forceAnnotationsRender:!1,appName:null,lazyLoadedPages:null,productId:null,processorEngine:null,dynamicFonts:null,inlineWorkers:!0,allowLinearizedLoading:!1,enableCoreUnifiedComments:!1,enableCorePreservePDFAccessibility:!1,httpHeaders:null,canvasRendering:!1})){}const oe=n(64836).Fe,ce=new a.iy(oe);class le extends U.K{constructor(e){super(),(0,i.A)(this,"type","STANDALONE"),(0,i.A)(this,"standaloneDocumentSigner",new Z(this)),(0,i.A)(this,"signingServiceDocumentSigner",new ie(this)),(0,i.A)(this,"_XFDF",null),he(e);const{baseUrl:t,baseCoreUrl:n,baseProcessorEngineUrl:a,instantJSON:r,XFDF:o,enableAutomaticLinkExtraction:c,overrideMemoryLimit:l,trustedCAsCallback:h,electronAppName:u,appName:g,isSharePoint:f,isSalesforce:y,productId:b,processorEngine:A,dynamicFonts:S,inlineWorkers:v,formsConfiguration:w,allowLinearizedLoading:P,unifiedCommentsSupport:_,preservePDFAccessibility:F,canvasRendering:k}=e;"string"==typeof o&&(this._XFDF={source:o,keepCurrentAnnotations:!0===e.XFDFKeepCurrentAnnotations,ignorePageRotation:!0===e.XFDFIgnorePageRotation,richTextEnabled:!0===e.XFDFRichTextEnabled}),r&&r.annotations&&(r.annotations=r.annotations.map(e=>(e.id=e.id?.toString(),e))),this._instantJSON=r,this._formsConfiguration=w,"function"==typeof h&&(this._trustedCAsCallback=h);const{disableWebAssemblyStreaming:C,customFonts:D,fontSubstitutions:T}=e,{standaloneInstancesPoolSize:I}=e;void 0!==I&&(ce.size=I);const R=!!e.electronicSignatures&&Boolean(e.electronicSignatures.forceLegacySignaturesFeature);let E=b||null;!f&&!y||E||(E=f?p.v.SharePoint:p.v.Salesforce),this._state=new re(de({baseUrl:t,baseCoreUrl:n,baseProcessorEngineUrl:a,licenseKey:e.licenseKey,document:e.document,disableWebAssemblyStreaming:C,enableAutomaticLinkExtraction:c,overrideMemoryLimit:l,documentHandle:"0",customFonts:D,fontSubstitutions:T,forceLegacySignaturesFeature:R,appName:g||u,productId:E,processorEngine:A||m.j.fasterProcessing,dynamicFonts:S,inlineWorkers:v,allowLinearizedLoading:P,enableCoreUnifiedComments:_,enableCorePreservePDFAccessibility:F,httpHeaders:e.httpHeaders,canvasRendering:k??!1})),this._requestQueue=new s.L(d.z3);const{object:x,checkIn:O}=ce.checkOut();this.client=x,this.checkIn=O;const V=r?{annotations:r.annotations||[],formFields:r.formFields||[],formFieldValues:r.formFieldValues||[],skippedPdfObjectIds:r.skippedPdfObjectIds||[],skippedPdfFormFieldIds:r.skippedPdfFormFieldIds||[],attachments:r.attachments||{},bookmarks:r.bookmarks||[],skippedPdfBookmarkIds:r.skippedPdfBookmarkIds||[],comments:r.comments||void 0,skippedComments:r.skippedComments||void 0,format:r.format,...r.pdfId?{pdfId:r.pdfId}:null}:null;this.provider=new W(this.client,V)}isUsingInstantProvider(){return!1}hasClientsPresence(){return!1}async load(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this._isPDFJavaScriptEnabled=e.isPDFJavaScriptEnabled,{features:this._state.features,signatureFeatureAvailability:this._state.signatureFeatureAvailability,hasPassword:!!e.password,password:e.password,allowedTileScales:"all",clientInfo:null}}async afterDocumentLoaded(e){}destroy(){this.corePDFDocument.destroy(),this.provider&&this.provider.destroy(),this._requestQueue&&this._requestQueue.destroy(),this.checkIn()}async documentInfo(){return this._state.documentResponse}async lazyLoadPages(){if(!this._state.lazyLoadedPages){const e=await this.client.getAllPageInfos(this._state.documentResponse.pageCount);this._state=this._state.set("lazyLoadedPages",e)}return this._state.lazyLoadedPages}getDocumentHandle(){return this._state.documentHandle}getFormJSON(){return this.client.getFormJSON()}permissions(){return Promise.resolve(this._state.backendPermissions)}textForPageIndex(e){return this.corePDFDocument.getTextLines(e)}getContentTreeForPageIndex(e){return this.corePDFDocument.getContentTree(e)}getTextFromRects(e,t){return this.client.getTextFromRects(e,t.toJS())}getAvailableFontFaces(e){return this.client.getAvailableFontFaces(e)}async getSuggestedLineHeightFactor(e){return"number"!=typeof e.pdfObjectId?1:"number"!=typeof e.pageIndex?((0,r.R8)("Annotation must have a pageIndex."),1):(e.lineHeightFactor&&(0,r.R8)(`Annotation ${e.id} already has a line height factor.`),this.client.getSuggestedLineHeightFactor(e.pdfObjectId,e.pageIndex))}async getClosestSnapPoint(e){const t=await this.client.getClosestSnapPoint(e.x,e.y);return t&&"number"==typeof t[0]&&"number"==typeof t[1]?new w.bR({x:t[0],y:t[1]}):e}configureSnapper(e){return this.client.configureSnapper(e)}renderAnnotation(e,t,n,i,a,s,r){if(0===Math.floor(i)||0===Math.floor(a))return{promise:Promise.resolve(void 0),cancel:()=>{}};const o=(0,R.yl)();let c;if((0,_.cu)(e)){if(c=(0,_.sS)(e),this.isVisuallyIdenticalAnnotationCached({annotation:e,providedVisualAnnotationIndex:c,width:i,height:a}))return this.cachedRenderedAnnotationDiscardablePromise(c,o);this._addCachedRenderedAnnotation(c,{width:i,height:a,noZoom:e.noZoom,APStreamPromise:o.promise})}const l=e.id,d=new O(l,()=>this.client.renderAnnotation((0,L.eq)(e),n,i,a,(0,C.LG)(),s,r).then(e=>e?"string"==typeof e?(0,k.$3)(e):(0,k.vB)({buffer:e,width:i,height:a}):Promise.resolve(void 0)).then(t=>{(0,_.cu)(e)&&this._makeEnqueuedRelease(t??null,c);const n=t??void 0;return o.resolve(n),t??void 0}));return this._requestQueue.enqueue(d,!1)}async getMeasurementSnappingPoints(e){return this.client.getMeasurementSnappingPoints(e)}async getSecondaryMeasurementUnit(){return await this.client.getSecondaryMeasurementUnit()}async setSecondaryMeasurementUnit(e){return await this.client.setSecondaryMeasurementUnit(e)}async compareDocuments(e,t){const n={originalDocument:e.originalDocument,changedDocument:e.changedDocument,comparisonOperation:(0,f.c)(t)};return this.corePDFDocument.compareText(n).promise}async renderPageAnnotations(e,t,n){const i=this.provider,a=[],s=[],o=t.some(e=>e instanceof b.sb);o&&await i._setReadStateCallbacksPromise;const c=t.filter(e=>{const t=o?i._readStateCallbacks.getAnnotationWithFormField(e.id):null,n=t?.formField,r=(0,_.lG)(e,n);if(r&&n){a.find(e=>e.name===n.name)||(a.push((0,L.cA)((0,D.Af)(n))),s.push(n))}return r});function l(e,t){if((0,_.uM)(e)){const n=s.find(t=>t.name===e.formFieldName),i=t.find(t=>t.name===e.formFieldName);if(!(0,D.Ny)(n,i))return!1}return!0}const d=new Promise((t,a)=>{const o=c.filter(e=>0!==Math.floor(e.boundingBox.width*n)&&0!==Math.floor(e.boundingBox.height*n));this.client.renderPageAnnotations(e,o.map(e=>e.pdfObjectId).toArray(),o.map(e=>e.boundingBox.width*n).toArray(),o.map(e=>e.boundingBox.height*n).toArray(),(0,C.LG)()).then(e=>{const a=s.map(e=>i._readStateCallbacks?.getFormFieldByName(e.name)).filter(Boolean),c=e.map((e,t)=>{const i=o.get(t);return(0,r.V1)(i),l(i,a)&&i&&e?"string"==typeof e?(0,k.$3)(e):(0,k.vB)({buffer:e,width:i.boundingBox.width*n,height:i.boundingBox.height*n}):Promise.resolve(null)});Promise.all(c).then(e=>{const a=s.map(e=>i._readStateCallbacks?.getFormFieldByName(e.name)).filter(Boolean);e.forEach((e,t)=>{const i=o.get(t);if(i){const{formFieldValue:t}=this.getAnnotationFormFieldAndValue(i),s=this.getAnnotationAvailableVariants(i),r=this.annotationAPStreamPromises.get(i.id),o=l(i,a);if(r&&(this.annotationAPStreamPromises=this.annotationAPStreamPromises.delete(i.id),r(o?e:null)),s.length>1){const a={normal:e};e&&o&&this.cacheAPStream(a,i);const{promise:r}=this.renderAPStream(i,t,null,i.boundingBox.width*n,i.boundingBox.height*n,s);Promise.all(r.map(e=>e.promise)).then(e=>{e.some(Boolean)&&s.forEach((t,n)=>{"normal"!==t&&e[n]&&(a[t]=e[n])})})}else e&&o&&this.cacheAPStream(e,i)}}),t()})}).catch(a)});return this.pageAPStreamsPromises=this.pageAPStreamsPromises.set(e,d),d}renderDetachedAnnotation(e,t,n,i){if(e.id)throw new r.uE(`Detached annotations should not have an \`id\`: ${e.id}`);const a=(0,R.yl)();let s;if((0,_.cu)(e)){if(s=(0,_.sS)(e),this.isVisuallyIdenticalAnnotationCached({annotation:e,providedVisualAnnotationIndex:s,width:n,height:i}))return this.cachedRenderedAnnotationDiscardablePromise(s,a);this._addCachedRenderedAnnotation(s,{width:n,height:i,noZoom:e.noZoom,APStreamPromise:a.promise})}const o=(0,l.Z0)(),c=new O(o,()=>this.client.renderDetachedAnnotation((0,L.eq)(e),t,n,i,(0,C.LG)()).then(e=>e?(0,k.vB)({buffer:e,width:n,height:i}):Promise.resolve(null)).then(t=>((0,_.cu)(e)&&this._makeEnqueuedRelease(t,s),a.resolve(t),t)).catch(()=>{const e=this._cachedRenderedAnnotations.get(s);e&&e.timeout&&clearTimeout(e.timeout),this._cachedRenderedAnnotations.delete(s)})),{promise:d,cancel:h}=this._requestQueue.enqueue(c,!1);return{promise:d,cancel:h}}async getAttachment(e){const[t,n]=await this.client.getAttachment(e);return new Blob([t],{type:n})}async parseXFDF(e,t,n){const{errors:i,formFieldValues:a,annotations:s}=await this.client.parseXFDF(e,t,n);return{errors:i?.map(e=>({errorMessage:e.error_message,type:e.type})),formFieldValues:a?.reduce((e,t)=>(e[t.fqdn]=t.values,e),{}),annotations:(0,o.B8)(s?.map(e=>(0,L.h8)((0,_.K1)(),e))||[])}}async search(e,t,n,i){let a=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:g.n.TEXT;const r=await this.client.search(e,t,n,i,s);return(0,E.g)(r.filter(e=>a||!e.isAnnotation))}async searchAndRedact(e,t,n){const{totalPages:i}=n,a=await this.client.search(e,t.startPageIndex??0,t.pageRange??i,t.caseSensitive,t.searchType);return(0,o.B8)(a.filter(e=>t.searchInAnnotations||!e.isAnnotation).map(e=>{const i=e.isAnnotation?[e.annotationRect]:e.rectsOnPage,a=(0,o.B8)(i).map(e=>((0,r.V1)(e),(0,B.a)(e)));return new A.A({...(0,_.mN)(n),...t.annotationPreset,pageIndex:e.pageIndex,rects:a,boundingBox:P.A.union(a)})}))}async exportPDF(){let{flatten:e=!1,incremental:t,saveForPrinting:n=!1,format:i="pdf",excludeAnnotations:a=!1,preserveInstantJSONChanges:s=!0,permissions:o,outputFormat:c=!1,flattenElectronicSignatures:l=e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},d=arguments.length>1?arguments[1]:void 0;if(e&&!l)throw new r.uE("Cannot set `flattenElectronicSignatures` to `false` when `flatten` is set to `true`.");if(c&&"boolean"!=typeof c&&c.conformance&&(0,r.V1)(c.conformance&&Object.values(u.o).includes(c.conformance),"The supplied PDF/A Conformance type is not valid. Valid Conformance should be one of the following options NutrientViewer.Conformance."+Object.keys(u.o).join(", NutrientViewer.Conformance.")),void 0===t)if(this._state.features.includes(h.Y.DIGITAL_SIGNATURES)){const e=await this.getSignaturesInfo();t=!n&&Boolean("not_signed"!==e.status)}else t=!1;return this.client.exportFile(e,t,n,i,a,s,o,d).then(async e=>{let[t,n]=e;if(t.mimeType=n.mimeType,t.extension=n.extension,c){const e="boolean"!=typeof c&&c.conformance?c.conformance:u.o.PDFA_2B;let i;try{return i=await this._setupGdPictureClient(),await i.toPdf({document:t,contentType:n.mimeType,extension:n.extension,conformance:e})}finally{i?.destroy(),(0,x.Pm)(null)}}return t})}async exportOffice(e){let t,{format:n}=e;try{const[e]=await this.client.exportFile(!1,!1,!1,"pdf",!1,!0);return t=await this._setupGdPictureClient(),await t.toOffice(e,n)}catch(e){throw new r.uE(`Exporting to ${n} failed: ${e.message}.`)}finally{t?.destroy(),(0,x.Pm)(null)}}async _setupGdPictureClient(){let e=(0,x.jU)();return e||(e=(0,x.NY)({baseUrl:this._state.baseProcessorEngineUrl,mainThreadOrigin:this._state.appName||(0,I.D5)()||window.location.origin,licenseKey:this._state.licenseKey,processorEngine:this._state.processorEngine,customFonts:this._state.customFonts,dynamicFonts:this._state.dynamicFonts,fontSubstitutions:this._state.fontSubstitutions}),(0,x.Pm)(e)),e}exportXFDF(e){return this.client.exportXFDF(e)}exportInstantJSON(e){return this.client.exportInstantJSON(e)}getPDFURL(){let{includeComments:e=!0,saveForPrinting:t,excludeAnnotations:n}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.generatePDFObjectURL({includeComments:e,saveForPrinting:t,excludeAnnotations:n})}generatePDFObjectURL(){let e,{includeComments:t=!0,saveForPrinting:n,excludeAnnotations:i=!1}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},a=!1;return{promise:new Promise(s=>{this.exportPDF({flatten:!0,includeComments:t,saveForPrinting:n,excludeAnnotations:i}).then(t=>{if(a)return;const n=new Blob([t],{type:t.mimeType});e=window.URL.createObjectURL(n),s(e)})}),revoke:()=>{e&&window.URL.revokeObjectURL(e),a=!0}}}async getDocumentOutline(){const e=await this.client.getDocumentOutline();return(0,o.B8)(e.map(V.r))}async setDocumentOutline(e){return this.client.setDocumentOutline(e.map(V.U).toArray())}async getPageGlyphs(e){const t=await this.client.getPageGlyphs(e);return(0,L.Fj)(t)}async onKeystrokeEvent(e){return await this.client.onKeystrokeEvent(e)}async evalFormValuesActions(e){return this.client.evalFormValuesActions(e.map(L.cA).toJS())}async evalScript(e,t,n){return this.client.evalScript(e,t,n)}async setFormJSONUpdateBatchMode(e){return this.client.setFormJSONUpdateBatchMode(e)}async getMeasurementScales(){const e=await this.client.getMeasurementScales();return e?.measurementContentFormats}async addMeasurementScale(e){return await this.client.addMeasurementScale(e)}async removeMeasurementScale(e){return await this.client.removeMeasurementScale(e)}async getAnnotationsByScale(e){return await this.client.getAnnotationsByScale(e)}async applyOperationsAndReload(e){try{const{processedOperations:t,operationsDocuments:n}=await(0,F.t)(e);await this.client.applyOperations(t,n)}catch(e){throw new r.uE(`Applying operations failed: ${e}`)}return this.provider._state=this.provider._state.set("alreadyLoadedPages",(0,o.T5)()),this.reloadDocument()}async applyRedactionsAndReload(){try{await this.client.applyRedactions()}catch(e){throw new r.uE(`Applying redactions failed: ${e}`)}return this.reloadDocument()}async reloadDocument(){try{this.provider?.destroy(),this.provider=new W(this.client,null),this._state=this._state.set("lazyLoadedPages",null);const e=await this.client.reloadDocument();return this._state=this._state.set("documentResponse",e).set("documentHandle",(parseInt(this._state.documentHandle)+1).toString()).set("signaturesInfoPromise",null),this.clearRenderedAnnotationsCache(),{features:this._state.features,signatureFeatureAvailability:this._state.signatureFeatureAvailability,hasPassword:!1,password:void 0,allowedTileScales:"all",clientInfo:null}}catch(e){throw new r.uE(`Reloading failed: ${e}`)}}async getEmbeddedFiles(){const e=await this.client.getEmbeddedFilesList();return(0,o.B8)(e.map(e=>{let{id:t,...n}=e;return(0,y.r)(t,n,!0)}))}async exportPDFWithOperations(e){try{const{processedOperations:t,operationsDocuments:n}=await(0,F.t)(e);return this.client.exportPDFWithOperations(t,n)}catch(e){throw new r.uE(`Exporting PDF with operations failed: ${e}`)}}async setSignaturesLTV(e){try{const t=(e??[]).map(e=>e instanceof ArrayBuffer?c.o4.fromUint8Array(new Uint8Array(e)):c.o4.encode(e)),n=await this.getRevocationResponses(t),i=await this.client.setSignaturesLTV(n).then(e=>(0,L.N5)(e));if(i.signatures?.find(e=>e.certificateChainValidationStatus===Y.k.ok_but_could_not_check_revocation))throw"Could not set LTV for all signatures. Check that the OCSP response is valid.";return this._state=this._state.set("signaturesInfoPromise",null),this.getSignaturesInfo()}catch(e){throw new r.uE(`Setting signatures LTV failed: ${e}`)}}getSignaturesInfo(){try{if(this._state.signaturesInfoPromise)return this._state.signaturesInfoPromise;const e=this.client.getSignaturesInfo().then(e=>(0,L.N5)(e));return this._state=this._state.set("signaturesInfoPromise",e),e}catch(e){throw new r.uE(`Getting document signatures info: ${e}`)}}async refreshSignaturesInfo(){this._state=this._state.set("signaturesInfoPromise",null)}async loadCertificates(e){return this.client.loadCertificates(e)}async getRevocationResponses(e){const t=await this.client.getRevocationRequests(e);return await Promise.all(t.map(async e=>{let{method:t,url:n,content_type:i,request_data:a,token:s}=e;try{const e=await fetch(n,{method:t,headers:{"Content-Type":i??"application/ocsp-request"},body:c.o4.toUint8Array(a).buffer}),r=await e.arrayBuffer();return{response_code:e.status,body:c.o4.fromUint8Array(new Uint8Array(r)),token:s}}catch(e){return{response_code:0,body:"",token:s,error_message:e.message}}}))}async signDocumentAndReload(e,t){(0,r.V1)(void 0===t||"function"==typeof t||(0,S.k)(t),"On a Standalone deployment, `twoStepSignatureCallbackOrSigningServiceData` must be a function or `NutrientViewer.StandaloneSigningServiceData` if provided.");const n=(0,S.k)(t);return n?this.signingServiceDocumentSigner.signDocumentAndReload(e,n):this.standaloneDocumentSigner.signDocumentAndReload(e,t)}cancelRequests(){this._requestQueue.cancelAll()}async syncChanges(){}getDefaultGroup(){}isCollaborationPermissionsEnabled(){return!1}async clearAPStreamCache(){return this.client.clearAPStreamCache()}async setComparisonDocument(e,t){return this.client.setComparisonDocument(e,t)}async openComparisonDocument(e){return this._state=this._state.set("forceAnnotationsRender",!1),await this.client.closeDocument(),this._state=this._state.set("forceAnnotationsRender",!0),await this.client.openComparisonDocument(e)||this._state.documentResponse}async documentCompareAndOpen(e){return this.client.documentCompareAndOpen(e)}async persistOpenDocument(e){return this.client.persistOpenDocument(e)}async cleanupDocumentComparison(){return this.client.cleanupDocumentComparison()}async runPDFFormattingScripts(e,t){const n=[...new Set(e)];return this.client.runPDFFormattingScripts(n,t)}async runPDFFormattingScriptsFromWidgets(e,t,n){let i=[];if(this._isPDFJavaScriptEnabled){const{withAPStream:a,withoutAPStream:s}=e.reduce((e,i)=>{if(i instanceof b.sb){const a=t?.get(i.formFieldName);if(a instanceof b.Vw)return e;n?.(i)?e.withAPStream.push(i.formFieldName):e.withoutAPStream.push(i.formFieldName)}return e},{withAPStream:[],withoutAPStream:[]});let r=[];if(a.length&&!s.length)r=await this.runPDFFormattingScripts(a,!0);else if(!a.length&&s.length)r=await this.runPDFFormattingScripts(s,!1);else if(a.length&&s.length){const[e,t]=await Promise.all([this.runPDFFormattingScripts(a,!0),this.runPDFFormattingScripts(s,!1)]);r=e.concat(t)}i=(0,D.A5)(this._initialChanges,r)}return i}setFontSubstitutions(e){return this.client.setFontSubstitutions(e)}async contentEditorReload(){return(0,r.V1)(this.provider instanceof W,"Standalone can only use standalone annotation provider"),this.provider._state=this.provider._state.set("alreadyLoadedPages",(0,o.T5)()),this.reloadDocument()}getOCGs(){return this.client.getOCGs()}getOCGVisibilityState(){return this.client.getOCGVisibilityState()}setOCGVisibilityState(e){return this.client.setOCGVisibilityState(e)}updateButtonIcon(e,t,n){return this.client.updateButtonIcon((0,L.eq)(e),t,n)}async timestampData(e,t){const{url:n,username:i="",password:a=""}=t,s=c.o4.fromUint8Array(new Uint8Array(e));try{const e=await this.client.getTimestampRequest(s,{url:n,username:i,password:a}),t={method:e.method,headers:{"Content-Type":e.contentType||"application/timestamp-query"},body:c.o4.toUint8Array(e.requestData).buffer};(e.username||e.password)&&(t.headers.Authorization=`Basic ${btoa(`${e.username}:${e.password}`)}`);try{const n=await fetch(e.url,t),i=await n.arrayBuffer();return{response_code:n.status,body:c.o4.fromUint8Array(new Uint8Array(i)),token:e.token}}catch(t){return{response_code:400,body:"",token:e.token,error_message:t.message}}}catch(e){return{response_code:500,body:"",token:"",error_message:e.message}}}async waitUntilFullyLoaded(e){}}function de(e){return{baseUrl:e.baseUrl,baseCoreUrl:e.baseCoreUrl,baseProcessorEngineUrl:e.baseProcessorEngineUrl,licenseKey:e.licenseKey,document:e.document,disableWebAssemblyStreaming:!!e.disableWebAssemblyStreaming,enableAutomaticLinkExtraction:!!e.enableAutomaticLinkExtraction,overrideMemoryLimit:"number"==typeof e.overrideMemoryLimit?e.overrideMemoryLimit:null,documentHandle:"number"==typeof e.documentHandle?e.documentHandle:"0",trustedCAsCallback:"function"==typeof e.trustedCAsCallback?e.trustedCAsCallback:null,customFonts:Array.isArray(e.customFonts)?e.customFonts.filter(e=>e instanceof v.A):null,forceLegacySignaturesFeature:Boolean(e.forceLegacySignaturesFeature),appName:"string"==typeof e.appName?e.appName:null,productId:e.productId,processorEngine:e.processorEngine,dynamicFonts:e.dynamicFonts,fontSubstitutions:e.fontSubstitutions,inlineWorkers:e.inlineWorkers,allowLinearizedLoading:e.allowLinearizedLoading,enableCoreUnifiedComments:e.enableCoreUnifiedComments,enableCorePreservePDFAccessibility:e.enableCorePreservePDFAccessibility,httpHeaders:e.httpHeaders||null,canvasRendering:e.canvasRendering??!1}}function he(e){const{licenseKey:t,instantJSON:n,XFDF:i,disableWebAssemblyStreaming:a,disableIndexedDBCaching:s,enableAutomaticLinkExtraction:o,overrideMemoryLimit:c,standaloneInstancesPoolSize:l,trustedCAsCallback:d,baseUrl:h,baseCoreUrl:u,baseProcessorEngineUrl:m,customFonts:p,isSharePoint:g,isSalesforce:f,dynamicFonts:y,inlineWorkers:b,formsConfiguration:A,httpHeaders:S}=e;if((0,r.V1)("string"==typeof h,"`baseUrl` is mandatory and must be a valid URL, e.g. `https://example.com/"),(0,T.f4)(h),(0,r.V1)(!u||"string"==typeof u,"`baseCoreUrl` must be a valid URL if set, e.g. `https://example.com/"),u&&(0,T.Qo)(u),(0,r.V1)(!m||"string"==typeof m,"`baseProcessorEngineUrl` must be a valid URL if set, e.g. `https://example.com/"),m&&(0,T.hc)(m),(0,r.V1)(null==t||"string"==typeof t,"licenseKey must be a string value if provided. Please obtain yours from https://my.nutrient.io/."),"string"==typeof t&&(0,r.V1)(!t.startsWith("TRIAL-"),"You're using the npm key instead of the license key. This key is used to download the Nutrient Web SDK package via the node package manager.\n\nLeave out the license key to activate as a trial."),(0,r.V1)(void 0===i||"string"==typeof i,"XFDF must be a string"),n&&((0,r.yj)(n),(0,r.V1)(void 0===i,"Cannot import from both instantJSON and XFDF")),(0,r.V1)(void 0===a||"boolean"==typeof a,"disableWebAssemblyStreaming must be a boolean"),(0,r.V1)(void 0===o||"boolean"==typeof o,"enableAutomaticLinkExtraction must be a boolean"),(0,r.V1)(void 0===c||"number"==typeof c,"overrideMemoryLimit must be a number"),(0,r.V1)(void 0===l||"number"==typeof l&&l>=0,"standaloneInstancesPoolSize must be a non-negative number"),(0,r.V1)(void 0===d||"function"==typeof d,"trustedCAsCallback must be a function"),(0,r.V1)(void 0===p||Array.isArray(p)&&p.every(e=>e instanceof v.A),"customFonts must be an array of NutrientViewer.Font instances"),(0,r.V1)(void 0===p||p.every(e=>e.callback),"All NutrientViewer.Font instances specified on customFonts must have its callback property defined"),void 0!==s&&(0,r.t6)("disableIndexedDbCaching has been deprecated and it no longer has effect. It will be removed in a later version.\nBrowsers dropped IndexedDB serialization of Wasm modules in favor of regular HTTP caching."),(g||f)&&(0,r.t6)("isSharePoint and isSalesforce configuration properties are deprecated and will be removed in the next major release. Please use the new Configuration#productId property instead. For more information, please check the migration guide."),(0,r.V1)(!(g&&f),"You cannot enable both SharePoint and Salesforce integrations at the same time. Please set either isSharePoint or isSalesforce to true, but not both."),"string"==typeof y)try{new URL(y)}catch(e){throw new r.uE("dynamicFonts must be a valid URL to a JSON file containing the data for fonts to be dynamically loaded.")}if((0,r.V1)(void 0===b||"boolean"==typeof b,"inlineWorkers must be a boolean"),A&&(0,r.V1)(void 0===A.export?.disableComboBoxArrow||"boolean"==typeof A.export?.disableComboBoxArrow,"formsConfiguration.export.disableComboBoxArrow must be a boolean"),void 0!==S){(0,r.V1)(null!==S&&"object"==typeof S&&!Array.isArray(S),'httpHeaders must be an object with string key-value pairs, e.g. { "Authorization": "Bearer token" }'),Object.entries(S).forEach(e=>{let[t,n]=e;(0,r.V1)("string"==typeof t&&t.length>0,"httpHeaders keys must be non-empty strings representing valid HTTP header names"),(0,r.V1)("string"==typeof n,`httpHeaders value for key "${t}" must be a string. Received: ${typeof n}`)});const e=Object.keys(S).map(e=>e.toLowerCase());["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","date","dnt","expect","host","keep-alive","origin","permissions-policy","referer","te","trailer","transfer-encoding","upgrade","via"].forEach(t=>{(0,r.V1)(!e.includes(t),`httpHeaders cannot include the "${t}" header as it is controlled by the browser. For more information, see https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_request_header`)});const t=["proxy-","sec-"];e.forEach(e=>{t.forEach(t=>{(0,r.V1)(!e.startsWith(t),`httpHeaders cannot include headers starting with "${t}" (found: "${e}") as they are controlled by the browser. For more information, see https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_request_header`)})}),e.includes("range")&&console.warn('The "Range" header in httpHeaders will be overridden during progressive loading (allowLinearizedLoading: true) to manage document chunks. Your custom Range header will only be used for non-linearized document loading.')}}},26128:(e,t,n)=>{n.d(t,{L:()=>o});var i=n(57191),a=n(66080),s=n(26232);function r(){return!0}class o{constructor(e){this.queue=(0,i.uY)(),this.priorityQueue=(0,i.uY)(),this.inFlightRequests=(0,i.T5)(),this.inflightRequestLimit=e,this.isDestroyed=!1}enqueue(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(this.isDestroyed)return{promise:new Promise(()=>{}),cancel:()=>{}};let n,a;const s=new Promise((e,t)=>{n=e,a=t}),r=t?this.priorityQueue:this.queue,o=(0,i.hZ)(r,e,{promise:s,resolve:n,reject:a});return t?this.priorityQueue=o:this.queue=o,t?this.next():setTimeout(()=>this.next(),35),{promise:s,cancel:()=>this._cancel(e)}}_cancel(e){this.queue.has(e)&&(this.queue=this.queue.delete(e)),this.priorityQueue.has(e)&&(this.priorityQueue=this.priorityQueue.delete(e)),this.inFlightRequests.has(e)&&(this.inFlightRequests=this.inFlightRequests.delete(e))}cancelAll(){this.queue=(0,i.uY)(),this.priorityQueue=(0,i.uY)(),this.inFlightRequests=(0,i.T5)()}cancel(e){const t=(t,n)=>e(n);this.queue=this.queue.filter(t),this.priorityQueue=this.priorityQueue.filter(t),this.inFlightRequests=this.inFlightRequests.filter(t)}_requestFinished(e,t){if(this.isDestroyed)return;const n=this.inFlightRequests.get(e);n&&(n.resolve(t),this.inFlightRequests=this.inFlightRequests.delete(e)),this.next()}_requestFailed(e,t){if(this.isDestroyed)return;const n=this.inFlightRequests.get(e);n&&(n.reject(t),this.inFlightRequests=this.inFlightRequests.delete(e)),this.next()}next(){if(!(this.isDestroyed||this.inFlightRequests.size>=this.inflightRequestLimit)){if(this.priorityQueue.size>=1){let e,t,n,i=1/0;this.priorityQueue.forEach((a,r)=>{const o=r?.loadingStrategy?.queueOrder;if(o&&o!==s.wp.LIFO)if(o!==s.wp.FIFO||t){if(o===s.wp.Bidirectional){const e=r.loadingStrategy?.loadPriority??0;e<i&&(i=e,n=[r,a])}}else t=[r,a];else e=[r,a]});const r=e||t||n;(0,a.V1)(r);const[o,c]=r;return this.priorityQueue=this.priorityQueue.delete(o),this.inFlightRequests=this.inFlightRequests.set(o,c),void o.request().then(e=>this._requestFinished(o,e)).catch(e=>this._requestFailed(o,e))}if(this.queue.size>=1){const e=this.queue.findEntry(r);(0,a.V1)(e);const[t,n]=e;this.queue=this.queue.delete(t),this.inFlightRequests=this.inFlightRequests.set(t,n),t.request().then(e=>this._requestFinished(t,e)).catch(e=>this._requestFailed(t,e))}}}destroy(){this.isDestroyed=!0}}},38468:(e,t,n)=>{n.d(t,{g:()=>o});var i=n(57191),a=n(66080),s=n(34518),r=n(93143);function o(e){return(0,a.V1)(Array.isArray(e),"Wrong `json` field"),(0,i.B8)(e.map(e=>((0,a.V1)("number"==typeof e.pageIndex,"Wrong `pageIndex` field"),(0,a.V1)("string"==typeof e.previewText,"Wrong `previewText` field"),(0,a.V1)(Array.isArray(e.rangeInPreview),"Wrong `rangeInPreview` field"),(0,a.V1)(Array.isArray(e.rectsOnPage),"Wrong `rectsOnPage` field"),new r.A({pageIndex:e.pageIndex,previewText:e.previewText,locationInPreview:e.rangeInPreview[0],lengthInPreview:e.rangeInPreview[1],rectsOnPage:(0,i.B8)(e.rectsOnPage).map(e=>(0,s.a)(e)),isAnnotation:!!e.isAnnotation,annotationRect:e.annotationRect?(0,s.a)(e.annotationRect):null}))).filter(Boolean))}},48478:(e,t,n)=>{n.d(t,{O:()=>a,n:()=>i});let i=function(e){return e[e.EVALUATION=0]="EVALUATION",e[e.DEMO=1]="DEMO",e[e.DEVELOPMENT=2]="DEVELOPMENT",e[e.PRODUCTION=3]="PRODUCTION",e}({}),a=function(e){return e[e.WEB=59]="WEB",e[e.DOCUMENT_ENGINE=60]="DOCUMENT_ENGINE",e}({})},49105:(e,t,n)=>{n.d(t,{K:()=>m});var i=n(34724),a=n(57191),s=n(66080),r=n(30583);class o{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(0,i.A)(this,"cache",new Map),(0,i.A)(this,"hotQueue",new Set),(0,i.A)(this,"coldQueue",new Set),(0,i.A)(this,"pinnedTiles",new Set),(0,i.A)(this,"listeners",new Set),(0,i.A)(this,"currentBytes",0),(0,i.A)(this,"hits",0),(0,i.A)(this,"misses",0),(0,i.A)(this,"totalEvictedTiles",0),(0,i.A)(this,"totalEvictedBytes",0),(0,i.A)(this,"lastEvictedAt",null),(0,i.A)(this,"debugEvents",[]),(0,i.A)(this,"tileSizeCounts",new Map);const{maxMemoryMB:t,deviceType:n}=e,a="number"==typeof t?t:this.getAdaptiveCacheSize(n);this.maxBytes=1024*a*1024,this.registerDebugHandle()}getAdaptiveCacheSize(e){const t="mobile"===e||null==e&&/iPhone|iPad|iPod|Android|Mobile/i.test(navigator.userAgent),n="deviceMemory"in navigator&&"number"==typeof navigator.deviceMemory?navigator.deviceMemory:null;let i;return i=t?n&&n<=2?96:128:n&&n>=16?1024:n&&n>=8?768:512,i}generateKey(e,t,n,i){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,s=arguments.length>5?arguments[5]:void 0,r=!(arguments.length>6&&void 0!==arguments[6])||arguments[6];const o=Math.floor(n),c=Math.floor(i),l=Math.round(1e3*t)/1e3,d=Math.round(s),h=r?"":"/nt";return 0!==a?`${e}/mip${l}/x${o}y${c}/rot${a}/ts${d}${h}`:`${e}/mip${l}/x${o}y${c}/ts${d}${h}`}get(e,t,n,i){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,s=arguments.length>5?arguments[5]:void 0,r=!(arguments.length>6&&void 0!==arguments[6])||arguments[6];const o=this.generateKey(e,t,n,i,a,s,r),c=this.cache.get(o);return c?(this.hits++,c.lastAccessTime=Date.now(),c.accessCount++,this.coldQueue.has(o)&&c.accessCount>2&&(this.coldQueue.delete(o),this.hotQueue.add(o)),this.recordDebugEvent("hit",this.createDebugTilePayload(c)),c):(this.misses++,this.recordDebugEvent("miss",{key:o,pageIndex:e,mip:t,tileX:n,tileY:i,tileSize:s}),null)}has(e,t,n,i){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,s=arguments.length>5?arguments[5]:void 0,r=!(arguments.length>6&&void 0!==arguments[6])||arguments[6];const o=this.generateKey(e,t,n,i,a,s,r);return this.cache.has(o)}put(e,t,n,i,a){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:"bitmap",r=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0,o=arguments.length>7?arguments[7]:void 0,c=arguments.length>8?arguments[8]:void 0,l=arguments.length>9?arguments[9]:void 0,d=!(arguments.length>10&&void 0!==arguments[10])||arguments[10];const h=this.generateKey(e,t,n,i,r,o,d),u=this.calculateTileMemorySize(c,l,s);this.ensureMemoryBudget(u);const m={key:h,pageIndex:e,mip:t,tileX:n,tileY:i,tileSize:o,imageData:a,format:s,width:c,height:l,byteSize:u,lastAccessTime:Date.now(),createdTime:Date.now(),accessCount:1,isPinned:!1},p=this.cache.get(h);p&&(this.currentBytes-=p.byteSize,this.hotQueue.delete(h),this.coldQueue.delete(h),this.updateTileSizeCount(p.tileSize,-1)),this.cache.set(h,m),this.hotQueue.add(h),this.currentBytes+=u,this.updateTileSizeCount(m.tileSize,1),this.emitStats(),this.recordDebugEvent("put",this.createDebugTilePayload(m))}pin(e,t,n,i){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,s=arguments.length>5?arguments[5]:void 0,r=!(arguments.length>6&&void 0!==arguments[6])||arguments[6];const o=this.generateKey(e,t,n,i,a,s,r),c=this.cache.get(o);c&&(this.pinnedTiles.add(o),c.isPinned=!0,this.emitStats(),this.recordDebugEvent("pin",this.createDebugTilePayload(c)))}clearPage(e){const t=[];this.cache.forEach((n,i)=>{n.pageIndex!==e||n.isPinned||t.push(i)}),t.forEach(e=>{this.removeTile(e)}),t.length>0&&(this.emitStats(),this.recordDebugEvent("clear_page",{pageIndex:e,details:{removed:t.length}}))}clear(){const e=[];this.cache.forEach((t,n)=>{t.isPinned||e.push(n)}),e.forEach(e=>{this.removeTile(e)}),e.length>0&&(this.emitStats(),this.recordDebugEvent("clear_all",{details:{removed:e.length}}))}getStats(){const e=this.hits+this.misses>0?this.hits/(this.hits+this.misses):0,t={};return this.tileSizeCounts.forEach((e,n)=>{t[n]=e}),{totalTiles:this.cache.size,totalBytes:this.currentBytes,hotTiles:this.hotQueue.size,coldTiles:this.coldQueue.size,pinnedTiles:this.pinnedTiles.size,hitRate:e,maxBytes:this.maxBytes,evictions:this.totalEvictedTiles,evictedBytes:this.totalEvictedBytes,lastEvictedAt:this.lastEvictedAt,tileSizeHistogram:t}}subscribe(e){return this.listeners.add(e),e(this.getStats()),()=>{this.listeners.delete(e)}}emitStats(){if(0===this.listeners.size)return;const e=this.getStats();this.listeners.forEach(t=>{t(e)})}ensureMemoryBudget(e){if(this.currentBytes+e<=this.maxBytes)return;const t=this.currentBytes+e-this.maxBytes;let n=0;const i=Date.now(),a=Array.from(this.hotQueue);for(const e of a){const t=this.cache.get(e);t&&!t.isPinned&&i-t.lastAccessTime>5e3&&(this.hotQueue.delete(e),this.coldQueue.add(e))}n+=this.evictOldestFromQueue(this.coldQueue,t-n),n<t&&(n+=this.evictOldestFromQueue(this.hotQueue,t-n))}evictOldestFromQueue(e,t){if(t<=0)return 0;const n=[];let i=0;for(const a of e){const e=this.cache.get(a);if(!e||e.isPinned)continue;if(i<t){n.push({key:a,tile:e}),i+=e.byteSize;continue}let s=0,r=n[0]?.tile.lastAccessTime??0;for(let e=1;e<n.length;e++){const t=n[e].tile.lastAccessTime;t>r&&(r=t,s=e)}e.lastAccessTime<r&&(i-=n[s].tile.byteSize,n[s]={key:a,tile:e},i+=e.byteSize)}let a=0;for(const{key:e,tile:i}of n){if(a>=t)break;a+=i.byteSize,this.removeTile(e,!0)}return a}removeTile(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=this.cache.get(e);return n?(n.imageData.close(),this.cache.delete(e),this.hotQueue.delete(e),this.coldQueue.delete(e),this.pinnedTiles.delete(e),this.currentBytes-=n.byteSize,this.currentBytes=Math.max(this.currentBytes,0),this.updateTileSizeCount(n.tileSize,-1),t&&(this.totalEvictedTiles++,this.totalEvictedBytes+=n.byteSize,this.lastEvictedAt=Date.now(),this.recordDebugEvent("evict",this.createDebugTilePayload(n))),n):null}calculateTileMemorySize(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"bitmap",i=0;if("bitmap"===n)i=e*t*4;else{const a=e*t;i="jpeg"===n?Math.ceil(4*a*.15):Math.ceil(4*a*.4)}return i}getDebugTrace(){return[...this.debugEvents]}clearDebugTrace(){this.debugEvents=[]}createDebugTilePayload(e){return{key:e.key,pageIndex:e.pageIndex,mip:e.mip,tileX:e.tileX,tileY:e.tileY,tileSize:e.tileSize,bytes:e.byteSize}}recordDebugEvent(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!r.a)return;const n={timestamp:Date.now(),type:e,...t};this.debugEvents.push(n),this.debugEvents.length>2e3&&this.debugEvents.shift()}registerDebugHandle(){if(!r.a)return;if("undefined"==typeof window)return;const e={id:`tile-cache-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,getStats:()=>this.getStats(),getTrace:()=>this.getDebugTrace(),clearTrace:()=>this.clearDebugTrace()};window.__PSPDFKIT_TILE_CACHE_DEBUG__||(window.__PSPDFKIT_TILE_CACHE_DEBUG__=[]),window.__PSPDFKIT_TILE_CACHE_DEBUG__?.push(e)}updateTileSizeCount(e,t){if(!Number.isFinite(e))return;const n=(this.tileSizeCounts.get(e)||0)+t;n<=0?this.tileSizeCounts.delete(e):this.tileSizeCounts.set(e,n)}}var c=n(39826),l=n(35167),d=n(13069),h=n(10087),u=n(7210);class m{constructor(){(0,i.A)(this,"tileCache",new o({deviceType:c.LZ?"mobile":"desktop"})),(0,i.A)(this,"attachmentsCache",(0,a.T5)()),(0,i.A)(this,"cachedAPStreams",(0,a.T5)()),(0,i.A)(this,"pageAPStreamsPromises",(0,a.T5)()),(0,i.A)(this,"annotationAPStreamPromises",(0,a.T5)()),(0,i.A)(this,"_cachedRenderedAnnotations",(0,a.uY)()),(0,i.A)(this,"_objectURLs",{}),(0,i.A)(this,"_makeEnqueuedRelease",(e,t)=>{if("IMG"===e?.element?.tagName){const n=e.element.src;if(!n)return;"number"==typeof this._objectURLs[n]?this._objectURLs[n]++:this._objectURLs[n]=1;const i=e.release;e.release=()=>{this._objectURLs[n]--,this._objectURLs[n]<=0&&(i?.(),this._cachedRenderedAnnotations.has(t)&&(this._cachedRenderedAnnotations=this._cachedRenderedAnnotations.delete(t)),delete this._objectURLs[n])}}}),(0,i.A)(this,"_cacheableRenderedAnnotationSetExpire",e=>{const t=this._cachedRenderedAnnotations.get(e);(0,s.V1)(t),t.timeout&&clearTimeout(t.timeout);const n=setTimeout(()=>{this._cachedRenderedAnnotations.has(e)&&(this._cachedRenderedAnnotations=this._cachedRenderedAnnotations.delete(e))},3e4);this._cachedRenderedAnnotations=this._cachedRenderedAnnotations.update(e,e=>({...e,timeout:n}))}),(0,i.A)(this,"_addCachedRenderedAnnotation",(e,t)=>{let{width:n,height:i,noZoom:a,APStreamPromise:s}=t;if(this._cachedRenderedAnnotations.size>1e3){const e=this._cachedRenderedAnnotations.keySeq().first();e&&(this._cachedRenderedAnnotations=this._cachedRenderedAnnotations.delete(e))}this._cachedRenderedAnnotations=this._cachedRenderedAnnotations.set(e,{width:n,height:i,noZoom:a,APStreamPromise:s}),this._cacheableRenderedAnnotationSetExpire(e)})}getAnnotationFormFieldAndValue(e){const t=this.provider;(0,s.V1)(t instanceof t.constructor,"Backend can only use backend annotation provider");const n=e instanceof l.sb?t._readStateCallbacks?.getFormFieldByName(e.formFieldName):null;return{formField:n,formFieldValue:!n||n instanceof l.Vw?null:new l.E2({name:n.name,value:void 0!==n.formattedValue?n.formattedValue:"string"==typeof n.value?n.value:n.values})}}getAnnotationAvailableVariants(e){const t=this.provider;(0,s.V1)(t instanceof t.constructor,"Backend can only use backend annotation provider");return[...t._readStateCallbacks?.getAvailableVariants(e)||[],"normal"]}cachedRenderAnnotation(e,t,n,i,a,r){const o=this.provider;(0,s.V1)(o instanceof o.constructor,"Backend can only use backend annotation provider");const{formField:c,formFieldValue:l}=this.getAnnotationFormFieldAndValue(e);if(!(0,d.lG)(e,c))return this.renderAnnotation(e,l,t,n,i,a,r);const h=this.getAnnotationAvailableVariants(e);let u=!1,m=()=>{u=!0};return{promise:new Promise(async(s,o)=>{const c=t=>{const n=this.annotationAPStreamPromises.get(e.id);n&&(this.annotationAPStreamPromises=this.annotationAPStreamPromises.delete(e.id),n(t))},d=this.annotationAPStreamPromises.get(e.id);this.annotationAPStreamPromises=this.annotationAPStreamPromises.set(e.id,s),d&&d(null);try{const o=this.pageAPStreamsPromises.get(e.pageIndex);if(!o){const t=new Promise(t=>{this.annotationAPStreamPromises=this.annotationAPStreamPromises.set(e.id,t)});return void s(await t)}await o;const d=this.cachedAPStreams.get(e.pageIndex);if(d){const t=d?d.get(e.id):null;if(t)return void c(this.getAPStream(t,a))}const{promise:p,cancel:g}=this.renderAPStream(e,l,t,n,i,h,a,r);if(u)c(null);else if(m=g,h.length>1){const t=await Promise.all(p.map(e=>e.promise));c(t[h.indexOf(a||"normal")]),t.some(Boolean)&&this.cacheAPStream(h.reduce((e,n,i)=>t[i]?{...e,[n]:t[i]}:e,{}),e)}else{const t=await p,n=t?this.getAPStream(t,a):null;c(n),n&&this.cacheAPStream(t,e)}}catch(e){o(e)}}),cancel:m}}cacheAPStream(e,t){let n=this.cachedAPStreams.get(t.pageIndex);n||(this.cachedAPStreams=this.cachedAPStreams.set(t.pageIndex,(0,a.T5)()),n=this.cachedAPStreams.get(t.pageIndex)),this.cachedAPStreams=this.cachedAPStreams.setIn([t.pageIndex,t.id],e)}clearAllPageAPStreams(e){const t=this.cachedAPStreams.get(e);t&&(t.forEach(e=>{this.releaseAPStream(e)}),this.cachedAPStreams=this.cachedAPStreams.delete(e)),this.pageAPStreamsPromises=this.pageAPStreamsPromises.delete(e)}clearPageAPStreams(e,t){const n=this.cachedAPStreams.get(e);n&&(n.filter((e,n)=>t.has(n)).forEach(e=>{this.releaseAPStream(e)}),this.cachedAPStreams=this.cachedAPStreams.updateIn([e],(0,u.C$)(e=>e.filter((e,n)=>!t.has(n)))))}getAPStream(e,t){return e instanceof h.A?e:e?.[t||"normal"]||null}renderAPStream(e,t,n,i,a,s,r,o){if(s.length>1){const r=s.map(s=>this.renderAnnotation(e,t,n,i,a,"normal"!==s?s:void 0,o));return{promise:r,cancel:()=>{r.forEach(e=>{e.cancel()})}}}return this.renderAnnotation(e,t,n,i,a,r,o)}releaseAPStream(e){e instanceof h.A?e.release():Object.values(e).forEach(e=>{e.release()})}isVisuallyIdenticalAnnotationCached(e){let{annotation:t,providedVisualAnnotationIndex:n,width:i,height:a}=e;if(!(0,d.cu)(t))return!1;const r=n||(0,d.sS)(t);if(!this._cachedRenderedAnnotations.has(r))return!1;const o=this._cachedRenderedAnnotations.get(r);return(0,s.V1)(o),(0,d.Ab)({noZoom:o.noZoom&&t.noZoom,cachedRenderedAnnotationWidth:o.width,cachedRenderedAnnotationHeight:o.height,testAnnotationWidth:i,testAnnotationHeight:a})}cachedRenderedAnnotationDiscardablePromise(e,t){let{promise:n,resolve:i,reject:a}=t;const r=this._cachedRenderedAnnotations.get(e);return(0,s.V1)(r),r.APStreamPromise.then(t=>{let n;return t&&(n=new h.A(t.element.cloneNode(!0),t.release),this._makeEnqueuedRelease(n,e),this._cacheableRenderedAnnotationSetExpire(e)),i(n),n}).catch(a),{promise:n,cancel:()=>{}}}clearRenderedAnnotationsCache(){this._cachedRenderedAnnotations.forEach(e=>{let{APStreamPromise:t,timeout:n}=e;t.then(e=>{e?.release()}),n&&clearTimeout(n)}),this._cachedRenderedAnnotations=(0,a.T5)(),this._objectURLs={}}}},70191:(e,t,n)=>{n.d(t,{g:()=>a,t:()=>s});var i=n(66080);function a(e,t,n,i,a,s){let r;return e.has(n)?r=e.get(n):(r=a.toString(),t[r]=n,e.set(n,r)),{...i,[s]:r}}async function s(e){const t=new WeakMap,n={};return{processedOperations:await Promise.all(e.map(async(e,s)=>{if("importDocument"===e.type){const{document:r}=e;return(0,i.V1)(r instanceof File||r instanceof Blob,"Wrong `importDocument` operation `document` value: it must be a File or a Blob"),a(t,n,r,e,s,"document")}if("applyInstantJson"===e.type){const r=e.instantJson;(0,i.V1)("object"==typeof r&&null!==r,"Wrong `applyInstantJson` operation `instantJson` value: it must be an object");const o=JSON.stringify(r),c=new Blob([o],{type:"application/json"});return a(t,n,c,e,s,"dataFilePath")}if("applyXfdf"===e.type){const r=e.xfdf;(0,i.V1)("string"==typeof r,"Wrong `applyXfdf` operation `xfdf` value: it must be a string");const o=new Blob([r],{type:"application/vnd.adobe.xfdf"});return a(t,n,o,e,s,"dataFilePath")}return e})),operationsDocuments:n}}},80354:(e,t,n)=>{n.d(t,{r:()=>r});var i=n(57191);class a extends(i.mS({id:"",attachmentId:"",description:null,fileName:null,fileSize:null,updatedAt:null})){}var s=n(54807);function r(e,t){return function(e,t){return t}(0,arguments.length>2&&void 0!==arguments[2]&&arguments[2])?new a({id:(0,s.A)(),description:t.fileDescription,attachmentId:e,fileName:t.fileName||null,fileSize:t.fileSize||null,updatedAt:t.modificationDate?new Date(t.modificationDate):null}):new a({id:e,description:t.description,attachmentId:t.fileAttachmentId,fileName:t.fileName||null,fileSize:t.fileSize||null,updatedAt:new Date(t.updatedAt)||null})}},92042:(e,t,n)=>{n.d(t,{U:()=>c,r:()=>l});var i=n(66080),a=n(57191),s=n(22702),r=n(2689),o=n(35167);function c(e){return{type:"pspdfkit/outline-element",children:e.children&&e.children.map(e=>c(e)).toJS(),title:e.title,color:e.color&&(0,r.J)(e.color),isBold:e.isBold,isItalic:e.isItalic,isExpanded:e.isExpanded,action:e.action&&(0,s.Ix)(e.action)}}function l(e){let t,n;(0,i.V1)("pspdfkit/outline-element"===e.type,"invalid outline element type."),(0,i.V1)(null==e.children||Array.isArray(e.children),"children must be an Array<OutlineElement>."),(0,i.V1)("string"==typeof e.title,"title must be a string."),(0,i.V1)(null==e.isBold||"boolean"==typeof e.isBold,"isBold must be a boolean."),(0,i.V1)(null==e.isItalic||"boolean"==typeof e.isItalic,"isItalic must be a boolean."),(0,i.V1)(null==e.isExpanded||"boolean"==typeof e.isExpanded,"isExpanded must be a boolean.");try{t=e.action&&(0,s._8)(e.action)}catch(t){(0,i.R8)(`PDF Action not supported ${JSON.stringify(e.action)})`)}try{n=e.color&&(0,r.p)(e.color)}catch(t){(0,i.R8)(`Invalid color:\n\n${e.color}`)}const c={title:e.title,color:n,isBold:!0===e.isBold,isItalic:!0===e.isItalic,isExpanded:!0===e.isExpanded,action:t,children:e.children&&e.children.length>0?(0,a.B8)(e.children.map(l)):(0,a.B8)()};return new o.LC(c)}},92726:(e,t,n)=>{n.d(t,{N:()=>A});var i=n(25928),a=n(18465),s=n(61481),r=n(15447),o=n(66080),c=n(57191),l=n(13069),d=n(93617),h=n(94110),u=n(12446);function m(e,t,n){(function(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")})(e,t),t.set(e,n)}function p(e,t){return e.get(f(e,t))}function g(e,t,n){return e.set(f(e,t),n),n}function f(e,t,n){if("function"==typeof e?e===t:e.has(t))return arguments.length<3?t:n;throw new TypeError("Private element is not present on this object")}var y=new WeakMap,b=new WeakMap;class A{constructor(e,t){m(this,y,void 0),m(this,b,null),this.pdfLibrary=new i.T7.Qz(e),g(y,this,this.pdfLibrary.openDocument(t))}get rawDocument(){return p(y,this)}get linearizedDocument(){return(0,o.V1)(p(b,this),"Document is not linearized."),p(b,this)}async openLinearizedDocument(e){return g(b,this,await this.pdfLibrary.openLinarizedDocument(e)),g(y,this,p(b,this).document),p(b,this)}async normallyOpenLinearizedDocument(e,t){(0,o.V1)(p(b,this),"Document is not linearized."),p(b,this).destroy(),g(b,this,null),await e.client.openCreateFilePathDocument(t)}destroy(){this.rawDocument.destroyOffscreenCanvasRenderer?.(),(0,a.nl)(this.rawDocument.ctx)}parseAndEstimateComplexity(e){return this.rawDocument.renderer.parseAndEstimateComplexity(e)}renderTile(e,t,n,a,s,r,o,c){let d;r&&(d={annotations:r.annotations.filter(l.mH).map(u.eq).toJS().map(e=>({content:e})),formFieldValues:r.formFieldValues.map(u.cA).toJS(),formFields:r.formFields.map(u.T7).toJS(),signatures:r.signatures||[],attachments:r.attachments});const m=this.rawDocument.renderer.renderTile(e,t,n,{renderForPrinting:a,renderText:s,priority:t.width===n.width&&t.height===n.height?i.MX.bx.High:i.MX.bx.Normal,queueOrder:o,loadPriority:c},d).then(e=>(0,h.vB)({buffer:e.buffer.buffer,width:n.width,height:n.height,format:e.format}).then(e=>{if(null===e)throw new Error("Image handle is null");return e}));return{promise:m.promise,cancel:m.cancel}}renderTileRaw(e,t,n,a,s,r,o){let c,d;r&&(c={annotations:r.annotations.filter(l.mH).map(u.eq).toJS().map(e=>({content:e})),formFieldValues:r.formFieldValues.map(u.cA).toJS(),formFields:r.formFields.map(u.T7).toJS(),signatures:r.signatures||[],attachments:r.attachments}),d="high"===o?i.MX.bx.High:"normal"===o?i.MX.bx.Normal:t.width===n.width&&t.height===n.height?i.MX.bx.High:i.MX.bx.Normal;const h=this.rawDocument.renderer.renderTile(e,t,n,{renderForPrinting:a,renderText:s,priority:d},c);return{promise:h.promise.then(e=>({buffer:e.buffer.buffer,format:e.format})),cancel:h.cancel}}renderTileWithProgress(e,t,n,a,o){const c=this.rawDocument.ctx;if(c.wasmCtx){const l=c.wasmCtx.engine.corePDFAccess,d=new i.ql,h=(0,s.fu)(l,e,{width:t.width,height:t.height},{left:n.left,top:n.top,width:n.width,height:n.height},a,o);d.addCancelFn(h.cancel);const u=h.promise.catch(c=>{const l=c instanceof Error?c.message:"",h=l.includes("Unserializable return value")||l.includes("startProgressiveRender failed");if(!(c instanceof r.S||h))throw c;console.warn("[CorePDFDocument] Progressive render failed, falling back to direct render:",c);const u=this.rawDocument.renderer.renderTile(e,t,n,{renderForPrinting:!1,renderText:o.renderText,priority:i.MX.bx.High});return u.cancel&&d.addCancelFn(u.cancel),u.promise.then(e=>{a({status:s.yp.Done,buffer:e.buffer,format:e.format})})});return d.wrapPromise(u)}const l=new i.ql,d=this.rawDocument.renderer.renderTile(e,t,n,{renderForPrinting:!1,renderText:o.renderText,priority:i.MX.bx.High});d.cancel&&l.addCancelFn(d.cancel);const h=d.promise.then(e=>{a({status:s.yp.Done,buffer:e.buffer,format:e.format})});return l.wrapPromise(h)}getTextLines(e){return this.rawDocument.text.getTextLines(e).then(t=>(0,d.K0)({textLines:t},e))}getContentTree(e){return this.rawDocument.text.getContentTree(e).then(t=>{let n=[],i=0,a=0;return n=t.reduce((t,n)=>{let{nodes:s}=n;const r=(0,d.l1)(s,e,t.length,i,a);return i+=r.reduce((e,t)=>{let{content:n}=t;return e+(0,d.Y_)(n).size},0),a+=r.reduce((e,t)=>{let{content:n}=t;return e+(0,d.M3)(n).size},0),t.concat(r)},[]),(0,c.B8)(n)})}compareText(e){const t={data:e.originalDocument.arrayBuffer,password:e.originalDocument.password,pageIndexes:e.originalDocument.pageIndexes},n={data:e.changedDocument.arrayBuffer,password:e.changedDocument.password,pageIndexes:e.changedDocument.pageIndexes},a={numberOfContextWords:e.comparisonOperation.options?.numberOfContextWords,wordLevel:e.comparisonOperation.options?.wordLevel};return i.MX.fu.compareText(this.rawDocument.ctx,t,n,a).then(e=>e)}}}}]);