/*!
 * Nutrient Web SDK 1.16.0-2012f75 (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([[362],{46847(e,t,s){s.r(t),s.d(t,{corePool:()=>u.mG,customFontsPromiseRef:()=>N,default:()=>z,loadModule:()=>x,normalizeCoreOptions:()=>u.DO,validateStandaloneConfiguration:()=>u.mn});var n=s(34724),a=s(57191),i=s(89339),o=s(86177),r=s(64662),l=s(80695),c=s(23264),u=s(74129),d=s(39515),h=s(9855),f=s(28805),m=s(33704),p=s(76464),y=s(96584),g=s(51974),w=s(73844);function A(e){return null!==e&&(0,w.uA)(e)&&!(0,w.C5)(e)}function _(e){return"opfs"!==e.mode?"memory":e.isAuto?"auto":"opfs"}function b(e,t){const s={credentials:"same-origin"};if(e&&Object.keys(e).length>0){const t=new Headers;Object.entries(e).forEach(e=>{let[s,n]=e;t.append(s,n)}),s.headers=t}return t&&(s.signal=t),s}function S(e,t){"opfs"===e.mode&&(e.isAuto?(0,i.R8)(`OPFS storage: ${t}. Falling back to memory.`):(0,i.R8)(`OPFS storage was explicitly requested, but ${t}. Falling back to memory.`))}async function F(e){try{await e.closeOPFSStorage()}catch{}}async function D(e,t,s,n,a,o,r,l,c){const u=b(a,c);let d;r?(d=r,o?.()):d=await fetch(e,u).finally(()=>{o?.()});const h=(f=d.headers?.get("Content-Type"),f?.toLowerCase().split(";")[0].trim()||null);var f;h&&l?.(h);const m=d.headers?.get("Content-Length"),p=m?parseInt(m,10):null,y=Number.isFinite(p)?p:null,D=_(n),P=function(e,t,s){return"opfs"===e.mode&&!A(t)&&(null===e.minFileSize||null!==s&&s>=e.minFileSize)}(n,h,y);let v;if("opfs"===n.mode&&(A(h)?v="unsupported-content-type":null!==n.minFileSize&&null===y?v="file-size-unknown":null!==n.minFileSize&&null!==y&&y<n.minFileSize&&(v="below-min-file-size")),P){const a=await async function(e,t,s,n){const a=e.headers?.get("Content-Length");if(!a)return S(n,"the Content-Length header is missing"),{document:null,canReuseResponse:!0,fallbackReason:"content-length-missing"};const o=parseInt(a,10);if(isNaN(o)||o<=0)return S(n,"the Content-Length header is invalid"),{document:null,canReuseResponse:!0,fallbackReason:"content-length-invalid"};if(!await t.initOPFSStorage(o))return{document:null,canReuseResponse:!0,fallbackReason:"init-failed"};const r=1048576,l=e.body?.getReader();if(!l)return(0,i.R8)("OPFS storage: ReadableStream not available. Falling back to memory."),await F(t),{document:null,canReuseResponse:!0,fallbackReason:"readable-stream-unavailable"};let c=0,u=null;try{let e=new Uint8Array(r),s=0;for(;;){const{done:n,value:a}=await l.read();if(n){if(s>0){const n=e.subarray(0,s);await t.writeOPFSChunk(n,c-s)}break}null===u&&(u=a.slice(0,Math.min(a.byteLength,16384)));let i=0;for(;i<a.byteLength;){const n=r-s,o=Math.min(n,a.byteLength-i);e.set(a.subarray(i,i+o),s),s+=o,i+=o,c+=o,s===r&&(await t.writeOPFSChunk(e,c-s),e=new Uint8Array(r),s=0)}}}catch(e){return(0,i.R8)(`OPFS storage: error during streaming write: ${e}. Falling back to memory.`),await F(t),{document:null,canReuseResponse:!1,fallbackReason:"streaming-write-error"}}if(c!==o)return(0,i.R8)(`OPFS storage: short response (${c} of ${o} bytes). Falling back to memory.`),await F(t),{document:null,canReuseResponse:!1,fallbackReason:"short-response"};try{const a=Math.min(o,16384),i=null!==u&&u.byteLength>=a?u.slice(0,a):await t.readOPFSBytes(0,a),r=i.slice(0,Math.min(i.byteLength,8192)),l=await(0,w.oj)(r.buffer,s,e.headers?.get("Content-Type"));return{document:{type:"opfs",isFullyAvailable:!0,fullDocument:null,opfsActive:!0,documentHeadBuffer:i.buffer,contentType:l,storageAnalytics:{storageRequested:_(n),storageActual:"opfs"}},canReuseResponse:!1}}catch(e){return(0,i.R8)(`OPFS storage: error during finalization: ${e}. Falling back to memory.`),await F(t),{document:null,canReuseResponse:!1,fallbackReason:"finalization-error"}}}(d,t,s,n);if(a.document)return a.document;v=a.fallbackReason??v,(0,g.q)("DocumentLoader: OPFS load failed; falling back to in-memory document load",{canReuseResponse:a.canReuseResponse,fallbackReason:v}),a.canReuseResponse||(d=await fetch(e,u))}const R=await d.arrayBuffer();return{type:"memory",isFullyAvailable:!0,fullDocument:R,contentType:await(0,w.oj)(R,s,d.headers?.get("Content-Type")),storageAnalytics:{storageRequested:D,storageActual:"memory",...v?{storageFallbackReason:v}:{}}}}async function P(e,t,s,n){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{mode:"memory"},r=arguments.length>5?arguments[5]:void 0,l=arguments.length>6?arguments[6]:void 0,c=arguments.length>7?arguments[7]:void 0,u=arguments.length>8?arguments[8]:void 0;if(e instanceof ArrayBuffer){const t=await(0,w.oj)(e,s),n=_(a);return c?.(t),{type:"memory",isFullyAvailable:!0,fullDocument:e,contentType:t,storageAnalytics:{storageRequested:n,storageActual:"memory",..."memory"!==n?{storageFallbackReason:"arraybuffer-input"}:{}}}}(0,i.V1)("string"==typeof e,"Document is not a string");let d=!1;const{linearizedDocument:h,serverSupportsRangeRequests:f,fallbackResponse:m}=await(async()=>{if(n&&function(e){if(e.startsWith("/"))return!0;try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch(e){return!1}}(e)){const t=await s.openLinearizedDocument(o.EA);(0,i.V1)(t,"Linearized document is not available"),t.contentType&&c&&c(t.contentType);const n=await t.initialize(e,r,u);return n.supportsRanges?{linearizedDocument:t,serverSupportsRangeRequests:!0,fallbackResponse:void 0}:{linearizedDocument:null,serverSupportsRangeRequests:!1,fallbackResponse:n.fullResponse}}return{linearizedDocument:null,serverSupportsRangeRequests:!1,fallbackResponse:void 0}})();try{if(!f)return d=!0,D(e,t,s,a,r,l,m,c,u);(0,i.V1)(h,"Linearized document is not available"),h.startDownload();if(!await h.waitUntilIsLinearizedIsKnown(u))return await h.destroyAsync(),d=!0,D(e,t,s,a,r,l,void 0,c,u);l?.();const n=await h.waitUntilDocumentInfoAvailable(u);return n?("undefined"!=typeof performance&&"function"==typeof performance.mark&&performance.mark("linearized-first-page-ready"),l?.(),{type:"linearized",isFullyAvailable:!1,documentResponse:n,contentType:"application/pdf",storageAnalytics:{storageRequested:_(a),storageActual:h.isUsingOPFS?"opfs":"memory",...h.opfsFallbackReason?{storageFallbackReason:h.opfsFallbackReason}:{}}}):(await h.destroyAsync(),d=!0,D(e,t,s,a,r,l,void 0,c,u))}catch(n){if(await(h?.destroyAsync()),n instanceof DOMException&&"AbortError"===n.name)throw n;if(d)throw n;return D(e,t,s,a,r,l,void 0,c,u)}}var v=s(80874),R=s(61469),C=s(82725),L=s(41417),E=s(62700);function k(e,t,s){const n=new i.uE(e);return n.status=t,n.body=s,n}function T(e){try{const t=(0,E.i)(e);if("number"!=typeof t.exp||!Number.isFinite(t.exp))throw new Error("Missing JWT exp.");return 1e3*t.exp}catch{throw new i.uE("DWS standalone authorization failed: returned wasmAuthToken is missing a decodable exp claim.")}}async function I(e,t,s){let n;try{n=await fetch(function(e){const t=e??"https://api.pspdfkit.com/";return(0,L.Me)(t),`${t}viewer/standalone/auth`}(t),{method:"POST",headers:{Accept:"application/json",Authorization:`Bearer ${e}`,"Content-Type":"application/json","PSPDFKit-Platform":"web","PSPDFKit-Version":"cloud-protocol=1, server-protocol=5, client=1.16.0-2012f75, client-git=2012f75290"},body:JSON.stringify({}),signal:s??void 0})}catch(e){if("undefined"!=typeof DOMException&&e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&"AbortError"===e.name)throw e;const t=e instanceof Error?e.message:String(e);throw new i.uE(`DWS standalone authorization failed while connecting to the authorization endpoint: ${t}`)}if(!n.ok){const e=await n.text();throw function(e,t){return 401===e.status?k("DWS standalone authorization failed: the session is invalid, expired, or missing.",e.status,t):403===e.status?k("DWS standalone authorization failed: the session scope, origin, standalone entitlement, or policy was rejected.",e.status,t):k("DWS standalone authorization failed while connecting to the authorization endpoint.",e.status,t)}(n,e)}const a=await n.json();if("string"!=typeof a.wasmAuthToken||0===a.wasmAuthToken.length)throw new i.uE("DWS standalone authorization failed: response is missing wasmAuthToken.");return{wasmAuthToken:a.wasmAuthToken,expiresAt:T(a.wasmAuthToken)}}class O{constructor(e){(0,n.A)(this,"_expiresAt",null),(0,n.A)(this,"_started",!1),(0,n.A)(this,"_destroyed",!1),(0,n.A)(this,"_refreshTimerId",null),(0,n.A)(this,"_pendingRefresh",null),(0,n.A)(this,"_hardRefreshState",null),(0,n.A)(this,"_authorizationAbortController",null),(0,n.A)(this,"_retryAttempt",0),(0,n.A)(this,"_setSessionVersion",0),this._session=e.session,this._hostedBaseUrl=e.hostedBaseUrl,this._onAuthFailed=e.onAuthFailed,this._replaceAuthToken=e.replaceAuthToken}async authorizeInitial(e){const t=await this.authorize(e);return this._expiresAt=t.expiresAt,this._retryAttempt=0,t.wasmAuthToken}start(){this._started=!0,this.scheduleRefresh()}setSession(e){this._session=e,this._setSessionVersion+=1;const t=this._setSessionVersion;if(this._authorizationAbortController?.abort(),this._hardRefreshState){const e=this._hardRefreshState;return this._hardRefreshState=null,clearTimeout(e.timeoutId),void this.replaceWithCurrentSession(t).then(e.resolve).catch(e.reject)}this._started&&this.refreshAfterSessionUpdate(t)}refresh(){return this._pendingRefresh||(this._pendingRefresh=this.refreshInternal().finally(()=>{this._pendingRefresh=null})),this._pendingRefresh}destroy(){if(this._destroyed=!0,this._authorizationAbortController?.abort(),this._authorizationAbortController=null,this.clearRefreshTimer(),this._hardRefreshState){const e=this._hardRefreshState;this._hardRefreshState=null,clearTimeout(e.timeoutId),e.reject(new i.uE("DWS standalone auth module was destroyed."))}}async refreshInternal(){this.clearRefreshTimer();try{await this.replaceWithCurrentSession(this._setSessionVersion)}catch(e){if(this._destroyed||e instanceof Error&&"AbortError"===e.name)return;if(function(e){return"object"==typeof e&&null!==e&&401===e.status}(e))return void await this.waitForSessionFromAuthFailedCallback();if(function(e){const t="object"==typeof e&&null!==e?e.status:void 0;return"number"!=typeof t||t>=500}(e)&&this.scheduleRetry())return;await this.waitForSessionFromAuthFailedCallback()}}async replaceWithCurrentSession(e){const t=await this.authorize();this._destroyed||e!==this._setSessionVersion||(await this._replaceAuthToken(t.wasmAuthToken),this._expiresAt=t.expiresAt,this._retryAttempt=0,this.scheduleRefresh())}async authorize(e){if(this._destroyed)throw new i.uE("DWS standalone auth module was destroyed.");const t=new AbortController,s=()=>t.abort();this._authorizationAbortController=t,e?.aborted?s():e?.addEventListener("abort",s,{once:!0});try{return await I(this._session,this._hostedBaseUrl,t.signal)}finally{e?.removeEventListener("abort",s),this._authorizationAbortController===t&&(this._authorizationAbortController=null)}}scheduleRefresh(){if(!this._started||this._destroyed||null===this._expiresAt)return;this.clearRefreshTimer();const e=Math.max(0,this._expiresAt-Date.now()-6e4);this.setRefreshTimer(e)}scheduleRetry(){if(!this._started||this._destroyed||null===this._expiresAt)return!1;const e=this._expiresAt-Date.now();if(e<=0)return!1;const t=Math.min(1e3*2**this._retryAttempt,3e4,e);return!(t<=0||Date.now()+t>=this._expiresAt)&&(this._retryAttempt+=1,this.clearRefreshTimer(),this.setRefreshTimer(t),!0)}setRefreshTimer(e){this._refreshTimerId=setTimeout(()=>{this.refresh().catch(e=>{(0,i.R8)(`DWS standalone authorization refresh failed: ${e.message}`)})},e)}refreshAfterSessionUpdate(e){const t=()=>{this._destroyed||e!==this._setSessionVersion||this.refresh().catch(e=>{(0,i.R8)(`DWS standalone authorization refresh failed after setSession: ${e.message}`)})};this._pendingRefresh?this._pendingRefresh.catch(()=>{}).then(t):t()}clearRefreshTimer(){null!==this._refreshTimerId&&(clearTimeout(this._refreshTimerId),this._refreshTimerId=null)}waitForSessionFromAuthFailedCallback(){if(!this._onAuthFailed)throw new i.uE("DWS standalone authorization failed. Provide onAuthFailed and call setSession(newSession) to recover.");return new Promise((e,t)=>{const s=setTimeout(()=>{this._hardRefreshState=null,t(new i.uE("DWS standalone auth refresh timed out: setSession was not called within 30 seconds."))},3e4);this._hardRefreshState={resolve:e,reject:t,timeoutId:s},Promise.resolve().then(()=>this._onAuthFailed?.()).catch(e=>{this._hardRefreshState&&(this._hardRefreshState=null,clearTimeout(s)),t(e)})})}}let U;class B extends Error{}class z extends u.Ay{waitForAbandonedLoad(){return new Promise(()=>{})}retainGdPictureLoad(){this._retainedGdPictureLoad||(this._retainedGdPictureLoad=!0,(0,p.qR)())}async releaseGdPictureLoad(){this._retainedGdPictureLoad&&(this._retainedGdPictureLoad=!1,await(0,p.M7)())}async abandonLoadAfterCleanup(){throw await this.releaseGdPictureLoad(),new B}async openDocumentOrAbandon(e,t){try{const s=await this.client.openDocument(e,t);return this.destroyed&&await this.abandonLoadAfterCleanup(),s}catch(e){throw this.destroyed&&await this.abandonLoadAfterCleanup(),e}}async openDocumentWithOPFSOrAbandon(e){try{const t=await this.client.openDocumentWithOPFS(e);return this.destroyed&&await this.abandonLoadAfterCleanup(),t}catch(e){throw this.destroyed&&await this.abandonLoadAfterCleanup(),e}}stashDocumentHeadBuffer(e){const t=Math.min(e.byteLength,16384);this._documentHeadBuffer=e.slice(0,t)}constructor(e){const t=e.baseUrl||(0,c.$_)(window.document),s=e.baseCoreUrl||t,a=e.baseProcessorEngineUrl||t,o={...e,baseUrl:t,baseCoreUrl:s,baseProcessorEngineUrl:a};if("string"!=typeof o.baseUrl)throw new i.uE("`baseUrl` is mandatory and must be a valid URL, e.g. `https://example.com/`");if("string"!=typeof o.document&&!(o.document instanceof ArrayBuffer))throw new i.uE("document must be either an URL to a supported document type (PDF and images), e.g. `https://example.com/document.pdf`, or an `ArrayBuffer`");const r="string"==typeof o.session;if(!r&&U&&U!==o.licenseKey)throw new i.uE("Trying to re-use instance with a different licenseKey.\nUnfortunately we only allow one licenseKey per instance.\nPlease contact support for further assistance.");if("string"==typeof o.licenseKey&&o.licenseKey.startsWith("TRIAL-"))throw new i.uE("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.");super(o),(0,n.A)(this,"_resolvedPdfBuffer",null),(0,n.A)(this,"_documentHeadBuffer",null),(0,n.A)(this,"_loadInProgress",!1),(0,n.A)(this,"_retainedGdPictureLoad",!1),(0,n.A)(this,"_opfsActive",!1),(0,n.A)(this,"_documentStorageAnalytics",null),(0,n.A)(this,"_dwsStandaloneAuthModule",null),(0,n.A)(this,"corePDFAccess",null),(0,n.A)(this,"_pageHideListener",e=>{e.persisted||this.destroyed||"opfs"!==this._state.storage.mode||this.cleanupOPFSStorage("pagehide",!1)}),this.destroyed=!1,this.activeConfiguration=e,this._usesDWSStandaloneAuth=r,r&&(this.client.destroy(),this._dwsStandaloneAuthModule=new O({session:o.session,hostedBaseUrl:o.hostedBaseUrl,onAuthFailed:o.onAuthFailed,replaceAuthToken:e=>this.client.replaceAuthToken(e)})),window.addEventListener("pagehide",this._pageHideListener)}cleanupOPFSStorage(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const s=this.corePDFAccess,n="opfs"===this._state.storage.mode&&s&&(!t||this._opfsActive);this._opfsActive=!1,n&&s.closeOPFSStorage().catch(t=>{(0,i.R8)(`OPFS storage cleanup error (${e}): ${t}`)})}async load(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._resolvedPdfBuffer=null,this._documentHeadBuffer=null,this._opfsActive=!1,this._documentStorageAnalytics=null,this._loadInProgress=!0;try{const t=()=>{try{this.retainGdPictureLoad();let t=(0,p.jU)();t||(t=(0,p.NY)({baseUrl:this._state.baseProcessorEngineUrl,mainThreadOrigin:this._state.appName||(0,r.D5)()||window.location.origin,licenseKey:this._state.licenseKey||void 0,customFonts:this._state.customFonts||void 0,dynamicFonts:this._state.dynamicFonts||void 0,fontSubstitutions:this._state.fontSubstitutions,processorEngine:this._state.processorEngine}),(0,p.Pm)(t)),e.onGdPictureReady&&t.then(e.onGdPictureReady).catch(()=>{})}catch(e){console.error("Error initializing GdPicture client:",e)}};let s,n=.2;e.progressCallback&&e.progressCallback("loading",n),this._isPDFJavaScriptEnabled=e.isPDFJavaScriptEnabled,"string"==typeof this._state.document&&(0,w.XC)(this._state.baseUrl,this._state.document,this._state.productId),this._state.document instanceof ArrayBuffer&&(0,w.uA)(await(0,w.oj)(this._state.document))&&t();try{s=await(this._dwsStandaloneAuthModule?.authorizeInitial(e.signal))}catch(e){throw this.destroyed&&await this.abandonLoadAfterCleanup(),e}this.destroyed&&await this.abandonLoadAfterCleanup();const o=await x(this.client,this._state,s).finally(()=>{n+=.3,e.progressCallback&&e.progressCallback("loading",n)});(0,l.lp)(),e.onWasmReady?.(),this.destroyed&&await this.abandonLoadAfterCleanup(),this._dwsStandaloneAuthModule?.start();const c=this.client.corePDFAccess;this.corePDFAccess=c,"opfs"===this._state.storage.mode&&c.cleanupOPFSOrphans().catch(e=>{(0,i.R8)(`OPFS orphan cleanup failed: ${e}`)});const u="string"==typeof this._state.dynamicFonts?this._state.dynamicFonts.split("/").slice(0,-1).join("/"):void 0;this.corePDFDocument=new C.N({corePDFAccess:c,canvasRendering:this._state.canvasRendering,dynamicFontsBaseURL:u,storage:this._state.storage},{type:"alreadyLoadedDocument"});const d=P(this._state.document,c,this.corePDFDocument,this._state.allowLinearizedLoading,this._state.storage,this._state.httpHeaders||void 0,()=>{n+=.3,e.progressCallback&&e.progressCallback("loading",n)},e=>{(0,w.uA)(e)&&t()},e.signal);(0,i.V1)(o);const{features:y,signatureFeatureAvailability:g,capabilities:A,licenseData:_}=o;if(this._state.productId===m.v.SharePoint&&"string"==typeof this._state.document&&Array.isArray(o.afu)){const e=new URL(this._state.document,this._state.baseUrl);if(!o.afu.some(t=>e.hostname.match(t)))throw new i.uE(`The document origin ${e.hostname} is not authorized.`)}const b=g===h.g.ELECTRONIC_SIGNATURES&&(0,f.UX)(y)&&this._state.forceLegacySignaturesFeature?h.g.LEGACY_SIGNATURES:g;this._state=this._state.set("features",(0,a.B8)(y)).set("signatureFeatureAvailability",b),this._dwsStandaloneAuthModule||(U=this._state.licenseKey);const S=await d;this._documentStorageAnalytics=S.storageAnalytics??null;let F=null;const D={password:e.password,initialPageIndex:"number"==typeof e.initialPageIndex?e.initialPageIndex:0,formsConfiguration:this._formsConfiguration};if("memory"===S.type){let t=null;const s=(0,w.C5)(S.contentType),n=A.includes("GdPictureWASM"),a=s||!n;if(a)try{this.destroyed?F=await this.abandonLoadAfterCleanup():((this.activeConfiguration.isTextComparison||this.activeConfiguration.aiAssistant)&&(this._resolvedPdfBuffer=S.fullDocument.slice(0)),this.stashDocumentHeadBuffer(S.fullDocument),F=await this.openDocumentOrAbandon(S.fullDocument,D))}catch(e){const s=e;if("INVALID_PASSWORD"===s.message){const e=Array.isArray(s.callArgs)?s.callArgs[0]:null;this._state.document instanceof ArrayBuffer&&e instanceof ArrayBuffer&&(this._state=this._state.set("document",e))}else"IMAGE_DOCUMENTS_NOT_LICENSED"===s.message?s.message="The image documents feature is not enabled for your license key. Please contact support or sales to purchase the UI module for your product.":A.includes("GdPictureWASM")||(s.message="File not in PDF format or corrupted.");t=s}const o=t?.message,c=t instanceof i.uE&&"string"==typeof o&&o.includes("File not in PDF format or corrupted.");if(!n||!c&&s){if(t)throw t}else{this.retainGdPictureLoad();let s=null;const n=t?.callArgs,o=Array.isArray(n)?n[0]:null;if(o instanceof ArrayBuffer?s=o:a?"string"==typeof this._state.document&&(s=await this.fetchDocumentBytesWithCurrentHeaders(this._state.document)):s=S.fullDocument,!(s instanceof ArrayBuffer)){if(t)throw t;throw new i.uE("Document bytes are not available")}let c=this.destroyed;const u=S.contentType;try{if(!c){(0,l.HN)();const t=await(0,p.fL)(s,u,{baseUrl:this._state.baseProcessorEngineUrl,mainThreadOrigin:this._state.appName||(0,r.D5)()||window.location.origin,licenseKey:this._state.licenseKey||void 0,processorEngine:this._state.processorEngine,customFonts:this._state.customFonts||void 0,dynamicFonts:this._state.dynamicFonts||void 0,fontSubstitutions:this._state.fontSubstitutions},e.officeConversionSettings,!0,e.signal);(0,l.yq)(),(this.activeConfiguration.isTextComparison||this.activeConfiguration.aiAssistant)&&(this._resolvedPdfBuffer=t.slice(0)),this.stashDocumentHeadBuffer(t),c=this.destroyed,c||(F=await this.openDocumentOrAbandon(t,D))}}catch(e){if(!this.destroyed){const t=e;if("INVALID_PASSWORD"===t.message&&this._state.document instanceof ArrayBuffer){const e=Array.isArray(t.callArgs)?t.callArgs[0]:null;e instanceof ArrayBuffer&&(this._state=this._state.set("document",e))}throw"IMAGE_DOCUMENTS_NOT_LICENSED"===t.message&&(t.message="The image documents feature is not enabled for your license key. Please contact support or sales to purchase the UI module for your product."),t}c=!0}c&&(F=await this.abandonLoadAfterCleanup())}(0,i.V1)(F),await this.afterDocumentLoaded(F)}else if("opfs"===S.type)if(this.destroyed)F=await this.abandonLoadAfterCleanup();else{this._opfsActive=!0,this._documentHeadBuffer=S.documentHeadBuffer;try{F=await this.openDocumentWithOPFSOrAbandon(D)}catch(t){const s=t,n=A.includes("GdPictureWASM"),a=s instanceof i.uE&&"string"==typeof s.message&&s.message.includes("File not in PDF format or corrupted.");this._opfsActive=!1,this._documentStorageAnalytics&&(this._documentStorageAnalytics={...this._documentStorageAnalytics,storageActual:"memory",storageFallbackReason:"open-document-failed"});try{await(this.corePDFAccess?.closeOPFSStorage())}catch{}if(!n||!a||"string"!=typeof this._state.document)throw s;{this.retainGdPictureLoad();let t=this.destroyed;const s=S.contentType;try{if(!t){(0,l.HN)();const n=await(0,p.fL)(await this.fetchDocumentBytesWithCurrentHeaders(this._state.document),s,{baseUrl:this._state.baseProcessorEngineUrl,mainThreadOrigin:this._state.appName||(0,r.D5)()||window.location.origin,licenseKey:this._state.licenseKey||void 0,processorEngine:this._state.processorEngine,customFonts:this._state.customFonts||void 0,dynamicFonts:this._state.dynamicFonts||void 0,fontSubstitutions:this._state.fontSubstitutions},e.officeConversionSettings,!0,e.signal);(0,l.yq)(),this.activeConfiguration.isTextComparison&&(this._resolvedPdfBuffer=n.slice(0)),this.stashDocumentHeadBuffer(n),t=this.destroyed,t||(F=await this.openDocumentOrAbandon(n,D))}}catch(e){if(!this.destroyed){const t=e;if("INVALID_PASSWORD"===t.message){const e=Array.isArray(t.callArgs)?t.callArgs[0]:null;e instanceof ArrayBuffer&&(this._state=this._state.set("document",e))}throw"IMAGE_DOCUMENTS_NOT_LICENSED"===t.message&&(t.message="The image documents feature is not enabled for your license key. Please contact support or sales to purchase the UI module for your product."),t}t=!0}t&&(F=await this.abandonLoadAfterCleanup())}}(0,i.V1)(F),await this.afterDocumentLoaded(F)}else F=S.documentResponse;this._state=this._state.set("documentResponse",F);const v=this.mapLicenseDataToClientInfo(_);return{features:this._state.features,signatureFeatureAvailability:this._state.signatureFeatureAvailability,hasPassword:!!e.password,password:e.password,allowedTileScales:"all",evaluation:o.evaluation,linearizedLoading:!S.isFullyAvailable,documentResponse:F,clientInfo:v}}catch(e){if(e instanceof B)return this.waitForAbandonedLoad();throw e}finally{this._loadInProgress=!1,await this.releaseGdPictureLoad()}}mapLicenseDataToClientInfo(e){const t="1.16.0-2012f75",s=(0,v.o)(this._state.productId);if(null===s)return null;if(!e)return{environment:R.n.EVALUATION,productId:s,productVersion:t,licenseId:void 0,demoKeyId:void 0};let n=R.n.DEVELOPMENT;return"p"===e.type?n=R.n.PRODUCTION:"d"===e.type?n=R.n.DEMO:"b"===e.type?n=R.n.DEVELOPMENT:"t"===e.type&&(n=R.n.EVALUATION),{environment:n,productId:s,productVersion:t,licenseId:e.li,demoKeyId:"d"===e.type?e.i:void 0}}takeResolvedPdfBuffer(){const e=this._resolvedPdfBuffer;return this._resolvedPdfBuffer=null,e}takeDocumentHeadBuffer(){const e=this._documentHeadBuffer;return this._documentHeadBuffer=null,e}getDocumentStorageAnalytics(){return this._documentStorageAnalytics}prepareClientForCheckIn(){this._usesDWSStandaloneAuth&&this.client.destroy()}destroy(){if(!this.destroyed){if(this.destroyed=!0,this._dwsStandaloneAuthModule?.destroy(),this._dwsStandaloneAuthModule=null,this._resolvedPdfBuffer=null,this._documentHeadBuffer=null,this._documentStorageAnalytics=null,window.removeEventListener("pagehide",this._pageHideListener),this._loadInProgress)return this.releaseGdPictureLoad(),this.destroyResources(),this.client.destroy(),this._opfsActive=!1,void(this.corePDFAccess=null);this.cleanupOPFSStorage("destroy"),this.corePDFAccess=null,super.destroy()}}setSession(e){this._dwsStandaloneAuthModule?this._dwsStandaloneAuthModule.setSession(e):(0,i.R8)("`setSession` is only supported in server-backed mode or DWS standalone mode. Use NutrientViewer.load with documentId and authPayload for server-backed token refresh, or document and session for DWS standalone token refresh.")}getCustomFontsPromise(){return N}async afterDocumentLoaded(e){if(this._isPDFJavaScriptEnabled&&(this._initialChanges=await this.client.enablePDFJavaScriptSupport()),this._XFDF&&await this.client.importXFDF(this._XFDF.source,this._XFDF.keepCurrentAnnotations,this._XFDF.ignorePageRotation,this._XFDF.richTextEnabled),this._instantJSON&&this._instantJSON.pdfId&&e.ID.permanent){const t=this._instantJSON.pdfId,s=e.ID,n=s.changing??s.update;if(t.permanent!==s.permanent)throw new i.uE("Could not instantiate from Instant JSON: Permanent PDF ID mismatch.\nPlease use the same PDF document that was used to create this Instant JSON.\nFor more information, please visit: https://www.nutrient.io/guides/web/importing-exporting/instant-json/");if(t.changing!==n)throw new i.uE("Could not instantiate from Instant JSON: Changing PDF ID mismatch.\nPlease use the same revision of this PDF document that was used to create this Instant JSON.\nFor more information, please visit: https://www.nutrient.io/guides/web/importing-exporting/instant-json/")}if(this._trustedCAsCallback)try{const e=await this._trustedCAsCallback();if(!Array.isArray(e))throw new i.uE("Certificates response must be an array");if(e.some(e=>!(e instanceof ArrayBuffer)&&"string"!=typeof e))throw new i.uE("All certificates must be passed as ArrayBuffer (DER) or string (PEM)");await this.client.loadCertificates(e.map(d.PI))}catch(e){throw new i.uE(`Could not retrieve certificates for digital signatures validation: ${e.message}.`)}}async waitUntilFullyLoaded(e){return this.corePDFDocument.linearizedDocument.waitUntilDownloaded().then(async()=>{const t=this.corePDFDocument.linearizedDocument.isUsingOPFS,s=await this.corePDFDocument.normallyOpenLinearizedDocument(this,{password:e,initialPageIndex:0,formsConfiguration:this._formsConfiguration});this.destroyed&&(t&&(await(this.corePDFAccess?.closeOPFSStorage().catch(e=>{(0,i.R8)(`OPFS storage cleanup error: ${e}`)})),this._opfsActive=!1),await this.waitForAbandonedLoad()),t&&(this._opfsActive=!0),this._state=this._state.set("documentResponse",s),await this.afterDocumentLoaded(s)})}async getDocumentBytes(){if(this._state.document instanceof ArrayBuffer)return this._state.document;if("string"==typeof this._state.document){const e=await fetch(this._state.document);if(!e.ok)throw new i.uE(`Failed to fetch document: ${e.statusText}`);return e.arrayBuffer()}throw new i.uE("Document bytes are not available")}async fetchDocumentBytesWithCurrentHeaders(e){return(await fetch(e,b(this._state.httpHeaders||void 0))).arrayBuffer()}}const N={current:void 0};async function x(e,t,s){N.current=N.current||(t.customFonts?(0,y.eY)(t.customFonts):void 0);const n=(0,c.f)(t.appName);return e.loadNativeModule(t.baseCoreUrl,{mainThreadOrigin:n,disableWebAssemblyStreaming:t.disableWebAssemblyStreaming,enableAutomaticLinkExtraction:t.enableAutomaticLinkExtraction,overrideMemoryLimit:t.overrideMemoryLimit,workerSpawnerFn:()=>(0,o.pj)(t.inlineWorkers)}).then(async()=>e.load(t.baseCoreUrl,s??t.licenseKey,{mainThreadOrigin:n,...N.current?{customFonts:await N.current}:null,dynamicFonts:t.dynamicFonts,productId:t.productId,featureFlags:(()=>{const e=[];return t.enableCoreUnifiedComments&&e.push("UnifiedComments"),t.enableCorePreservePDFAccessibility&&e.push("PreservePDFAccessibility"),e.length>0?e:void 0})()}))}}}]);