/*!
 * Nutrient Web SDK 1.10.0-18868f6 (https://www.nutrient.io/sdk/web)
 *
 * Copyright (c) 2016-2025 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/
 */
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.NutrientViewer=t():e.NutrientViewer=t()}(globalThis,(()=>(()=>{"use strict";function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e(t)}function t(t){var n=function(t,n){if("object"!=e(t)||!t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var s=r.call(t,n||"default");if("object"!=e(s))return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===n?String:Number)(t)}(t,"string");return"symbol"==e(n)?n:n+""}function n(e,n,r){return(n=t(n))in e?Object.defineProperty(e,n,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[n]=r,e}const r=Symbol("Comlink.proxy"),s=Symbol("Comlink.endpoint"),i=Symbol("Comlink.releaseProxy"),o=Symbol("Comlink.finalizer"),a=Symbol("Comlink.thrown"),c=e=>"object"==typeof e&&null!==e||"function"==typeof e,u=new Map([["proxy",{canHandle:e=>c(e)&&e[r],serialize(e){const{port1:t,port2:n}=new MessageChannel;return l(e,t),[n,[n]]},deserialize:e=>(e.start(),h(e))}],["throw",{canHandle:e=>c(e)&&a in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){if(e.isError)throw Object.assign(new Error(e.value.message),e.value);throw e.value}}]]);function l(e,t=globalThis,n=["*"]){t.addEventListener("message",(function s(i){if(!i||!i.data)return;if(!function(e,t){for(const n of e){if(t===n||"*"===n)return!0;if(n instanceof RegExp&&n.test(t))return!0}return!1}(n,i.origin))return void console.warn(`Invalid origin '${i.origin}' for comlink proxy`);const{id:c,type:u,path:h}=Object.assign({path:[]},i.data),f=(i.data.argumentList||[]).map(v);let p;try{const t=h.slice(0,-1).reduce(((e,t)=>e[t]),e),n=h.reduce(((e,t)=>e[t]),e);switch(u){case"GET":p=n;break;case"SET":t[h.slice(-1)[0]]=v(i.data.value),p=!0;break;case"APPLY":p=n.apply(t,f);break;case"CONSTRUCT":p=function(e){return Object.assign(e,{[r]:!0})}(new n(...f));break;case"ENDPOINT":{const{port1:t,port2:n}=new MessageChannel;l(e,n),p=function(e,t){return w.set(e,t),e}(t,[t])}break;case"RELEASE":p=void 0;break;default:return}}catch(e){p={value:e,[a]:0}}Promise.resolve(p).catch((e=>({value:e,[a]:0}))).then((n=>{const[r,i]=R(n);t.postMessage(Object.assign(Object.assign({},r),{id:c}),i),"RELEASE"===u&&(t.removeEventListener("message",s),d(t),o in e&&"function"==typeof e[o]&&e[o]())})).catch((e=>{const[n,r]=R({value:new TypeError("Unserializable return value"),[a]:0});t.postMessage(Object.assign(Object.assign({},n),{id:c}),r)}))})),t.start&&t.start()}function d(e){(function(e){return"MessagePort"===e.constructor.name})(e)&&e.close()}function h(e,t){const n=new Map;return e.addEventListener("message",(function(e){const{data:t}=e;if(!t||!t.id)return;const r=n.get(t.id);if(r)try{r(t)}finally{n.delete(t.id)}})),y(e,n,[],t)}function f(e){if(e)throw new Error("Proxy has been released and is not useable")}function p(e){return E(e,new Map,{type:"RELEASE"}).then((()=>{d(e)}))}const g=new WeakMap,m="FinalizationRegistry"in globalThis&&new FinalizationRegistry((e=>{const t=(g.get(e)||0)-1;g.set(e,t),0===t&&p(e)}));function y(e,t,n=[],r=function(){}){let o=!1;const a=new Proxy(r,{get(r,s){if(f(o),s===i)return()=>{!function(e){m&&m.unregister(e)}(a),p(e),t.clear(),o=!0};if("then"===s){if(0===n.length)return{then:()=>a};const r=E(e,t,{type:"GET",path:n.map((e=>e.toString()))}).then(v);return r.then.bind(r)}return y(e,t,[...n,s])},set(r,s,i){f(o);const[a,c]=R(i);return E(e,t,{type:"SET",path:[...n,s].map((e=>e.toString())),value:a},c).then(v)},apply(r,i,a){f(o);const c=n[n.length-1];if(c===s)return E(e,t,{type:"ENDPOINT"}).then(v);if("bind"===c)return y(e,t,n.slice(0,-1));const[u,l]=b(a);return E(e,t,{type:"APPLY",path:n.map((e=>e.toString())),argumentList:u},l).then(v)},construct(r,s){f(o);const[i,a]=b(s);return E(e,t,{type:"CONSTRUCT",path:n.map((e=>e.toString())),argumentList:i},a).then(v)}});return function(e,t){const n=(g.get(t)||0)+1;g.set(t,n),m&&m.register(e,t,e)}(a,e),a}function b(e){const t=e.map(R);return[t.map((e=>e[0])),(n=t.map((e=>e[1])),Array.prototype.concat.apply([],n))];var n}const w=new WeakMap;function R(e){for(const[t,n]of u)if(n.canHandle(e)){const[r,s]=n.serialize(e);return[{type:"HANDLER",name:t,value:r},s]}return[{type:"RAW",value:e},w.get(e)||[]]}function v(e){switch(e.type){case"HANDLER":return u.get(e.name).deserialize(e.value);case"RAW":return e.value}}function E(e,t,n,r){return new Promise((s=>{const i=new Array(4).fill(0).map((()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16))).join("-");t.set(i,s),e.start&&e.start(),e.postMessage(Object.assign({id:i},n),r)}))}class C{constructor(e,t){n(this,"queue",[]),n(this,"activeRequests",new Map),n(this,"isProcessing",!1),n(this,"renderCallbacks",new Map),n(this,"errorCallbacks",new Map),n(this,"maxConcurrentRequests",1),n(this,"activeRequestCount",0),this.renderChannel=e,this.maxConcurrentRequests=t}static async create(e){const t=await e.isServer();return new C(e,t?4:1)}setCallbacks(e,t,n){this.renderCallbacks.set(e,t),this.errorCallbacks.set(e,n)}enqueue(e,t){const n=Date.now();for(const r of t){if(this.activeRequests.has(r.id))continue;const t=this.queue.findIndex((e=>e.request.id===r.id));-1===t?this.queue.push({request:r,sessionId:e,priority:this.calculatePriority(r),timestamp:n,cancelled:!1}):this.queue[t].priority=this.calculatePriority(r)}this.sortQueue(),this.isProcessing||this.startProcessing()}cancel(e,t){const n=new Set(t);for(const t of this.queue)t.sessionId===e&&n.has(t.request.id)&&(t.cancelled=!0);for(const[t,r]of this.activeRequests)r.sessionId===e&&n.has(t)&&(r.cancelled=!0)}cancelSession(e){for(const t of this.queue)t.sessionId===e&&(t.cancelled=!0);for(const t of this.activeRequests.values())t.sessionId===e&&(t.cancelled=!0)}async startProcessing(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0||this.activeRequestCount>0;){for(;this.activeRequestCount<this.maxConcurrentRequests&&this.queue.length>0;){const e=this.getNextRequest();if(!e)break;this.activeRequestCount++,this.processRequest(e).finally((()=>{this.activeRequestCount--}))}await new Promise((e=>setTimeout(e,0)))}this.isProcessing=!1}}getNextRequest(){for(;this.queue.length>0;){const e=this.queue.shift();if(!e)break;if(!e.cancelled)return this.activeRequests.set(e.request.id,e),e}return null}async processRequest(e){const{request:t,sessionId:n}=e;try{if(e.cancelled)return;"undefined"!=typeof performance&&performance.mark&&performance.mark(`tile-render-start-${t.id}`);const r=await this.renderTile(t);if("undefined"!=typeof performance&&performance.mark&&(performance.mark(`tile-render-ready-${t.id}`),performance.measure))try{performance.measure(`tile-wasm-render-${t.id}`,`tile-render-start-${t.id}`,`tile-render-ready-${t.id}`)}catch(e){}if(e.cancelled)return;const s=this.renderCallbacks.get(n);s&&s(n,t.id,r)}catch(r){if(console.error("[SharedRenderQueue] Error processing request:",r),!e.cancelled){const e=this.errorCallbacks.get(n);e&&e(n,t.id,r)}}finally{this.activeRequests.delete(t.id)}}async renderTile(e){const{sourceInfo:t,options:n}=e,r=await this.renderChannel.render(t.pageIndex,t.pageSize,t.tileRect,{renderForPrinting:n.renderForPrinting,renderText:n.renderText,priority:n.priority||"high"});return{buffer:r,format:n.format||"bitmap",width:r.width,height:r.height}}calculatePriority(e){let t=0;"high"===e.options.priority&&(t-=1e3),e.targetInfo.isVisible&&(t-=500),t-=10*e.viewportRenderUpdateId;return t+=100*Math.abs(e.targetInfo.scale-e.targetInfo.targetScale),t}sortQueue(){this.queue.sort(((e,t)=>e.priority-t.priority))}}const q=function e(t){let n;return n=t instanceof Error?t:new Error(t),Object.setPrototypeOf(n,e.prototype),n};q.prototype=Object.create(Error.prototype,{name:{value:"PSPDFKitError",enumerable:!1}});const S=q;["a[href]","area[href]","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","button:not([disabled])","iframe","object","embed","[contenteditable]",'[tabindex]:not([tabindex^="-"])'].join(",");new WeakMap;return l(new class{constructor(){n(this,"sharedRenderQueue",null),n(this,"sessionCallbacks",new Map),n(this,"sessionErrors",new Map),n(this,"renderChannel",null),n(this,"sessionCounter",0)}async setupRenderMessageChannel(e){this.renderChannel=h(e)}async beginRenderer(e,t,n,r,s){!function(e,t){if(!e)throw new S(`Assertion failed: ${t||"Condition not met"}\n\nFor further assistance, please go to: https://www.nutrient.io/support/request`)}(this.renderChannel,"Setup render channel first"),this.sharedRenderQueue||(this.sharedRenderQueue=await C.create(this.renderChannel));const i=`page-${e}-${this.sessionCounter++}`;return this.sessionCallbacks.set(i,r),this.sessionErrors.set(i,s),this.sharedRenderQueue.setCallbacks(i,this.handleTileReady.bind(this),this.handleTileError.bind(this)),i}async requestTiles(e,t){if(!this.sharedRenderQueue)return void console.warn("SharedRenderQueue not initialized");const n=t.map((e=>({id:e.id,viewportRenderUpdateId:Date.now(),sourceInfo:{pageIndex:e.pageIndex,pageSize:e.pageSize,tileRect:e.tileRect},targetInfo:{scale:e.mip,targetScale:e.mip,isVisible:!0,canvasRect:{left:0,top:0,width:e.tileRect.width,height:e.tileRect.height}},options:{renderAnnotations:e.options.renderAnnotations,renderText:e.options.renderText,format:"bitmap",priority:e.options.priority}})));this.sharedRenderQueue.enqueue(e,n)}async cancelTiles(e,t){this.sharedRenderQueue&&this.sharedRenderQueue.cancel(e,t)}async endRenderer(e){this.sessionCallbacks.delete(e),this.sessionErrors.delete(e),this.sharedRenderQueue?.cancelSession(e)}handleTileReady(e,t,n){const r=this.sessionCallbacks.get(e);r&&r(e,t,n)}handleTileError(e,t,n){const r=this.sessionErrors.get(e);r&&r(e,t,n)}}),{}})()));