@nutrient-sdk/viewer
Version:
View and annotate PDF files in your web app. Full support for mobile and desktop. Runs in the browser using WASM.
13 lines • 76.8 kB
JavaScript
/*!
* Nutrient Web SDK 1.15.1 (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],{71530(e,t,n){n.d(t,{L:()=>o});var i=n(57191),a=n(89339),s=n(7871);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}}},82725(e,t,n){n.d(t,{N:()=>S});var i=n(64136),a=n(80069),s=n(9505),r=n(77872),o=n(89339),c=n(57191),l=n(45252),d=n(75378),h=n(90037),u=n(52041),m=n(75016);function p(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 g(e,t){return e.get(y(e,t))}function f(e,t,n){return e.set(y(e,t),n),n}function y(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 b=new WeakMap,A=new WeakMap;class S{constructor(e,t){p(this,b,void 0),p(this,A,null),this.pdfLibrary=new i.T7.Qz(e),f(b,this,this.pdfLibrary.openDocument(t))}get rawDocument(){return g(b,this)}get linearizedDocument(){return(0,o.V1)(g(A,this),"Document is not linearized."),g(A,this)}async openLinearizedDocument(e){return f(A,this,await this.pdfLibrary.openLinarizedDocument(e)),f(b,this,g(A,this).document),g(A,this)}async normallyOpenLinearizedDocument(e,t){(0,o.V1)(g(A,this),"Document is not linearized.");const n=g(A,this);let i;return n.isUsingOPFS?(i=await e.client.openDocumentWithOPFS(t),await n.destroyPreservingOPFSAsync()):(i=await e.client.openCreateFilePathDocument(t),await n.destroyAsync()),f(A,this,null),i}destroy(){this.cancelRequests(),i.MX.clearPreflightCache(this.rawDocument.ctx.documentKey),i.MX.clearFailedFontsCache(this.rawDocument.ctx.documentKey),this.rawDocument.destroyOffscreenCanvasRenderer?.(),(0,a.removeLinearizedInstanceAsync)(this.rawDocument.ctx)}cancelRequests(){this.rawDocument.ctx.requestQueue.cancelRequests(()=>!0)}parseAndEstimateComplexity(e){return this.rawDocument.renderer.parseAndEstimateComplexity(e)}isLinearizedLoading(){return(0,a.isLinearizedLoading)(this.rawDocument.ctx)}renderTileDirectlyWithProgress(e,t,n,a,r){let o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:new i.ql;const c=this.rawDocument.renderer.renderTile(e,t,n,{renderForPrinting:!1,renderText:a,priority:i.MX.Priority.High});c.cancel&&o.addCancelFn(c.cancel);const l=c.promise.then(e=>{r({status:s.ProgressiveStatus.Done,buffer:e.buffer,format:e.format})});return(0,i.ZO)(o.wrapPromise(l),{abortedMessage:"render request aborted"})}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.Priority.High:i.MX.Priority.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.Priority.High:"normal"===o?i.MX.Priority.Normal:t.width===n.width&&t.height===n.height?i.MX.Priority.High:i.MX.Priority.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}}renderAnnotationAtlas(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];const a="high"===(arguments.length>3&&void 0!==arguments[3]?arguments[3]:"normal")?i.MX.Priority.High:i.MX.Priority.Normal,s=this.rawDocument.renderer.renderAnnotationAtlas({pageIndex:e,pageSize:{width:t.width,height:t.height},annotationTypes:[...m.d],excludeAnnotationIds:n,priority:a});return{promise:s.promise,cancel:s.cancel}}renderTileWithProgress(e,t,n,o,c){const l=this.rawDocument.ctx,d=(0,a.isLinearizedLoading)(l);if(l.wasmCtx&&!d){const a=new i.ql,d=(0,s.renderTileProgressively)(l,e,{width:t.width,height:t.height},{left:n.left,top:n.top,width:n.width,height:n.height},o,c);a.addCancelFn(d.cancel);const h=d.promise.catch(i=>{const s=i instanceof Error?i.message:"",l=s.includes("Unserializable return value")||s.includes("startProgressiveRender failed");if(!(i instanceof r.S||l))throw i;return console.warn("[CorePDFDocument] Progressive render failed, falling back to direct render:",i),this.renderTileDirectlyWithProgress(e,t,n,c.renderText,o,a).promise});return(0,i.ZO)(a.wrapPromise(h),{abortedMessage:"render request aborted"})}return this.renderTileDirectlyWithProgress(e,t,n,c.renderText,o)}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.TextComparison.compareText(this.rawDocument.ctx,t,n,a).then(e=>e)}}},5386(e,t,n){n.d(t,{K:()=>p});var i=n(34724),a=n(57191),s=n(89339),r=n(99114);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=window,t={id:`tile-cache-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,getStats:()=>this.getStats(),getTrace:()=>this.getDebugTrace(),clearTrace:()=>this.clearDebugTrace()};e.__PSPDFKIT_TILE_CACHE_DEBUG__||(e.__PSPDFKIT_TILE_CACHE_DEBUG__=[]),e.__PSPDFKIT_TILE_CACHE_DEBUG__?.push(t)}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(4689),l=n(97947),d=n(45252),h=n(63620),u=n(76037),m=n(98046);class p{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})}}getAnnotationFormFieldRevision(e){const t=this.provider;if((0,s.V1)(t instanceof t.constructor,"Backend can only use backend annotation provider"),!(e instanceof l.sb))return null;const n=t._readStateCallbacks?.getFormFieldRevision?.(e.formFieldName);return"number"==typeof n?n:0}getAnnotationWidgetAppearanceSignature(e){const{formField:t}=this.getAnnotationFormFieldAndValue(e);return(0,m.bH)(e,t)}isWidgetPageRenderFresh(e,t,n){const i=e instanceof l.sb?t.find(t=>t.name===e.formFieldName):null;return this.isWidgetRenderFreshAtCompletion(e,i,null!=i?n.get(i.name)??0:null)}isWidgetRenderFreshAtCompletion(e,t,n){if(!(e instanceof l.sb))return!0;const i=this.provider;(0,s.V1)(i instanceof i.constructor,"Backend can only use backend annotation provider");const a=i._readStateCallbacks?.getAnnotationWithFormField?.(e.id),r=a?.annotation,o=a?.formField||i._readStateCallbacks?.getFormFieldByName(e.formFieldName);if(i._readStateCallbacks?.getAnnotationWithFormField&&!(r instanceof l.sb))return!1;if((0,m.bH)(e,t)!==(0,m.bH)(r||e,o))return!1;if(t&&null!=n){const e=i._readStateCallbacks?.getFormFieldRevision?.(t.name);if("number"==typeof e&&e!==n)return!1}return!0}isCachedAPStreamEntryValid(e,t){return null==e.formFieldRevision||e.formFieldRevision===this.getAnnotationFormFieldRevision(t)&&e.widgetAppearanceSignature===this.getAnnotationWidgetAppearanceSignature(t)}getValidCachedAPStream(e){const t=this.cachedAPStreams.get(e.pageIndex),n=t?.get(e.id);return n?this.isCachedAPStreamEntryValid(n,e)?n.APStream:(this.releaseAPStream(n.APStream),this.cachedAPStreams=this.cachedAPStreams.updateIn([e.pageIndex],(0,u.C$)(t=>t.delete(e.id))),null):null}resolvePendingAnnotationAPStreams(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;for(const n of e){const e=this.annotationAPStreamPromises.get(n);e&&(this.annotationAPStreamPromises=this.annotationAPStreamPromises.delete(n),e(t))}}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)=>{try{const o=this.pageAPStreamsPromises.get(e.pageIndex);if(!o){const t=this.annotationAPStreamPromises.get(e.id);this.annotationAPStreamPromises=this.annotationAPStreamPromises.set(e.id,s),t&&t(void 0);const n=new Promise(t=>{this.annotationAPStreamPromises=this.annotationAPStreamPromises.set(e.id,t)});return void s(await n)}await o;const c=this.getValidCachedAPStream(e);if(c)return void s(this.getAPStream(c,a));const{formField:l,formFieldValue:d}=this.getAnnotationFormFieldAndValue(e),p=this.getAnnotationFormFieldRevision(e),{promise:g,cancel:f}=this.renderAPStream(e,d,t,n,i,h,a,r);if(u)s(void 0);else if(m=f,h.length>1){const t=await Promise.all(g.map(e=>e.promise));if(!this.isWidgetRenderFreshAtCompletion(e,l,p))return t.forEach(e=>{e?.release()}),void s(void 0);s(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 g,n=t?this.getAPStream(t,a):null;if(!this.isWidgetRenderFreshAtCompletion(e,l,p))return n?.release(),void s(void 0);s(n),n&&this.cacheAPStream(t,e)}}catch(e){o(e)}}),cancel:m}}cacheAPStream(e,t){let n=this.cachedAPStreams.get(t.pageIndex),i=null,s=null;if(t instanceof l.sb){const{formField:e}=this.getAnnotationFormFieldAndValue(t);(0,d.lG)(t,e)&&(i=this.getAnnotationFormFieldRevision(t),s=(0,m.bH)(t,e))}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],{APStream:e,formFieldRevision:i,widgetAppearanceSignature:s})}clearAllPageAPStreams(e){const t=this.cachedAPStreams.get(e);t&&(t.forEach(e=>{this.releaseAPStream(e.APStream)}),this.cachedAPStreams=this.cachedAPStreams.delete(e)),this.pageAPStreamsPromises=this.pageAPStreamsPromises.delete(e)}clearPageAPStreamsPromise(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.APStream)}),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={}}}},74129(e,t,n){n.d(t,{mG:()=>de,Ay:()=>pe,DO:()=>ge,mn:()=>fe});var i=n(34724),a=n(86177),s=n(64136),r=n(22568),o=n(71530),c=n(89339),l=n(57191),d=n(13803),h=n(84008),u=n(53379),m=n(99819),p=n(600),g=n(68592),f=n(33704),y=n(67880),b=n(5366),A=n(77112),S=n(97947),v=n(32591),F=n(20053),_=n(4357),P=n(49963),w=n(64893),C=n(45252),k=n(2090),D=n(90037),T=n(92182),R=n(98046),I=n(41417),O=n(64662),E=n(19896),x=n(62389),V=n(58825);class L{constructor(e,t){this.identifier=e,this.callback=t}request(){return this.callback()}}var B=n(22019),U=n(29655),N=n(52041),z=n(5386),M=n(25668),q=n(23485),j=n(1024),W=n(23529),$=n(51670);class H extends((0,l.mS)({alreadyLoadedPages:(0,l.T5)(),isLoaded:!1,isDestroyed:!1})){}const K={skippedPdfObjectIds:[],skippedPdfBookmarkIds:[],annotations:[],bookmarks:[],formFieldValues:[],formFields:[],attachments:{}};class Q{constructor(e,t){(0,i.A)(this,"_state",new H),(0,i.A)(this,"_formFieldsLoadedPromise",null),(0,i.A)(this,"_objectCreationPromises",(0,l.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,l.NZ)()),this._core=e,this._json=t?(0,c.$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,c.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,j.lj)(atob(e.binary),e.contentType),(0,c.V1)(this._annotationCallbacks),this._annotationCallbacks.createAttachment(a.imageAttachmentId,i)}catch(e){(0,c.pq)(`Skipped attachment with id ${a.imageAttachmentId} from payload because an error occurred while converting the binary image to blob.`),(0,c.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=>J(e,n)).toArray())}updateComment(e,t,n){return this._core.applyComments(t.map(e=>J(e,n)).toArray())}deleteComment(e,t,n){return this._core.applyComments(t.map(e=>J(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,l.B8)(e.map(e=>{let t;return t=e.pdfObjectId?e.id||e.pdfObjectId?.toString():(0,C.K1)(),(0,N.XL)(t,e)}));await Promise.all(t.map(e=>"number"==typeof e.pageIndex&&this.loadAnnotationsForPageIndex(e.pageIndex)).filter(Boolean).toArray()),this._commentCallbacks?.createComments(t,$.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,l.NZ)(),this._isDestroyed())return;const t=await Promise.all(e.map(e=>this._core.getTabOrder(e)));this._isDestroyed()||((0,c.V1)(this._annotationCallbacks),(0,M.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,c.V1)("imageAttachmentId"in e,"Annotation must have imageAttachmentId."),n===e.imageAttachmentId)),i=await this._core.createAnnotation((0,N.eq)(e),n?n.data:null),a="multiline"in e&&!!e.multiline&&"imageAttachmentId"in e&&!!e.imageAttachmentId;"number"!=typeof i||"number"!=typeof e.pdfObjectId&&!a||e.pdfObjectId===i||this._isDestroyed()||((0,c.V1)(this._annotationCallbacks),this._annotationCallbacks.updateAnnotations((0,l.B8)([e.set("pdfObjectId",i)]))),await this.updateTabOrder(e.pageIndex)}async updateAnnotation(e){this._verifyLoaded(),await this._core.updateAnnotation((0,N.eq)(e)),await this.updateTabOrder(e.pageIndex)}deleteAnnotation(e){return this._verifyLoaded(),this._core.deleteAnnotation((0,N.eq)(e))}createBookmark(e){return this._verifyLoaded(),this._core.createBookmark((0,q.U)(e))}updateBookmark(e){return this._verifyLoaded(),this._core.updateBookmark((0,q.U)(e))}deleteBookmark(e){return this._verifyLoaded(),this._core.deleteBookmark(e)}createFormField(e){this._verifyLoaded(),(0,c.V1)(this._readStateCallbacks);const t=this._readStateCallbacks.getFormFieldWidgets(e);return this._core.createFormField((0,N.T7)(e),t.map(e=>(0,N.eq)(e)).toArray()).then(async e=>{(0,M.vA)(()=>{e.forEach((e,n)=>{const i=t.get(n);(0,c.V1)(i),(0,c.V1)(this._annotationCallbacks),"number"!=typeof e||"number"!=typeof i.pdfObjectId||i.pdfObjectId===e||this._isDestroyed()||this._annotationCallbacks.updateAnnotations((0,l.B8)([i.set("pdfObjectId",e)]))})})})}updateFormField(e){this._verifyLoaded(),(0,c.V1)(this._readStateCallbacks);const t=this._readStateCallbacks.getFormFieldWidgets(e);return this._core.updateFormField((0,N.T7)(e),t.map(e=>(0,N.eq)(e)).toArray())}deleteFormField(e){return this._verifyLoaded(),this._core.deleteFormField((0,N.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,l.B8)(),n=(0,l.B8)().withMutations(n=>{e.forEach(e=>{const{formField:i,widgets:a,value:s}=e;try{let e;e=i.pdfObjectId?i.pdfObjectId.toString():(0,C.K1)();const r=(0,N.mh)(e,i);(0,c.V1)(this._readStateCallbacks),this._readStateCallbacks.isFormFieldInState(r.name)||n.push(r.set("value",s)),a.forEach(e=>{if(e.formFieldName!==r.name)return;let n;n=e.pdfObjectId?e.id||e.pdfObjectId.toString():(0,C.K1)(),(0,c.V1)(this._readStateCallbacks),t=t.push((0,N.h8)(n,e))})}catch(e){(0,c.pq)(`Skipped creating form field #${i.pdfObjectId} from payload because an error occurred while deserializing.`),(0,c.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,C.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,c.V1)(i);const a=t.filter(t=>t.formFieldName===e).toArray().map(e=>(0,N.eq)(e));this._core.updateFormField((0,N.T7)(i),a)}),n.size>0&&!this._isDestroyed()&&((0,c.V1)(this._formFieldCallbacks),this._formFieldCallbacks.createFormFields(n,$.n)),await this._loadFormFieldValues(),t.size>0&&!this._isDestroyed()&&((0,c.V1)(this._annotationCallbacks),this._annotationCallbacks.createAnnotations(t,(0,l.T5)(),$.n)),this._formFieldsLoadedPromise=Promise.resolve()}createFormFieldValue(e){return this._verifyLoaded(),this.setFormFieldValue(e)}setFormFieldValue(e){return this._verifyLoaded(),this._core.setFormFieldValue((0,N.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 r=(0,l.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,C.K1)():t.id||t.pdfObjectId.toString(),(e.some(e=>e.id===n)||this._readStateCallbacks?.isAnnotationInState(n))&&(n=(0,C.K1)(),t.id=n,this._core.updateAnnotation(t));const i=(0,N.h8)(n,t);e.push(i)}catch(e){(0,c.pq)(`Skipped creating annotation #${t.pdfObjectId} from payload because an error occurred while deserializing.`),(0,c.pq)(e)}})});(0,M.vA)(()=>{(0,c.V1)(this._annotationCallbacks),r.size>0&&this._annotationCallbacks.createAnnotations(r,(0,l.T5)(),$.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,l.B8)().withMutations(t=>{e.forEach(e=>{try{t.push((0,N.R5)(e))}catch(t){(0,c.pq)(`Skipped creating form field value #${e.pdfObjectId} from payload because an error occurred while deserializing.`),(0,c.pq)(t)}})});t.size>0&&!this._isDestroyed()&&((0,c.V1)(this._formFieldValueCallbacks),this._formFieldValueCallbacks.setFormFieldValues(t))}async loadBookmarks(){this._verifyLoaded();const e=await this._core.getBookmarks();if(this._isDestroyed())return;const t=(0,l.B8)().withMutations(t=>{for(const n of e){let e;e=n.id?n.id:n.pdfBookmarkId?n.pdfBookmarkId:(0,W.z)();try{t.push((0,q.r)(e,n))}catch(t){(0,c.pq)(`Skipped creating bookmark #${e} from payload because an error occurred while deserializing.`),(0,c.pq)(t)}}});t.size>0&&!this._isDestroyed()&&((0,c.V1)(this._bookmarkCallbacks),this._bookmarkCallbacks.createBookmarks(t,$.n))}_verifyLoaded(){(0,c.V1)(this._state.isLoaded,"StandaloneProvider not properly initialized.")}_isDestroyed(){return this._state.isDestroyed}async syncChanges(){}}function J(e,t){(0,c.V1)(e.rootId,"A new comment must have `rootId` present");const n=t.get(e.rootId);return(0,c.V1)(n,"An annotation must be present linked to the comment to create"),(0,N.wG)(e,n.pdfObjectId?.toString()===n.id?parseInt(e.rootId):e.rootId)}function X(e){return"string"==typeof e?.serialNumber&&e.body instanceof ArrayBuffer}function G(e){return e?.pkcs7 instanceof ArrayBuffer&&(!("ocspResponses"in e)||Array.isArray(e.ocspResponses)&&e.ocspResponses.every(e=>X(e)))}function Y(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=>X(e)))return!1}return!0}var Z=n(37052),ee=n(70081);class te{constructor(e){this.backend=e}async signDocumentAndReload(e,t){const n=e?.signingData,i=n?.certificates;(0,c.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,c.V1)(!n?.timestamp||"string"==typeof n?.timestamp?.url,"The `url` property of `signingData.timestamp` must be a string."),(0,c.V1)(!n?.timestamp||!n?.timestamp?.password||"string"==typeof n?.timestamp?.password,"The `password` property of `signingData.timestamp` must be a string."),(0,c.V1)(!n?.timestamp||!n?.timestamp?.username||"string"==typeof n?.timestamp?.username,"The `username` property of `signingData.timestamp` must be a string."),(0,c.V1)(void 0===n?.ltv||"boolean"==typeof n?.ltv,"The `ltv` property of `signingData` must be a boolean if set."),(0,c.V1)(void 0===n?.ltv||"boolean"==typeof n?.ltv,"The `ltv` property of `signingData` must be a boolean if set."),(0,c.V1)(!n||!n.signatureType||n.signatureType===Z.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?Z.D.CAdES:Z.D.CMS),...i&&{certificates:i.map(e=>e instanceof ArrayBuffer?d.o4.fromUint8Array(new Uint8Array(e)):d.o4.encode(e))},...e?.placeholderSize?{estimatedSize:e.placeholderSize}:null};try{const{hash:i,signatureFormFieldName:s,file:r,fileContents:o,dataToBeSigned:l}=await this.backend.client.prepareSign((0,N.Y6)(a),e?.signatureMetadata?(0,N.sZ)(e.signatureMetadata):null,Boolean(e?.flatten),e?.formFieldName,(0,N.qN)(e?.position),await(0,N.z8)(e?.appearance),this.backend._state.certificateCheckTime),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}(l);let u,m,p;if(t){try{u=await t({hash:i,fileContents:o,dataToBeSigned:h})}catch(e){throw new c.uE(`\`twoStepSignatureCallback\` threw an error: ${e}`)}if(!(u instanceof ArrayBuffer||G(u)||Y(u)))throw new c.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 c.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 d.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=d.o4.fromUint8Array(new Uint8Array(p))||"";else if(G(p)){const e=p;g=d.o4.fromUint8Array(new Uint8Array(e.pkcs7))||""}else if(Y(p)){const e=p;g=d.o4.fromUint8Array(new Uint8Array(e.signedData))||"",f=e.certificates.map(e=>e instanceof ArrayBuffer?d.o4.fromUint8Array(new Uint8Array(e)):d.o4.encode(e))}let y=null,b=[];if(n?.ltv&&(p instanceof ArrayBuffer?b=await this.backend.getRevocationResponses(f):(G(p)||Y(p))&&((0,c.V1)(null==p.ocspResponses||Array.isArray(p.ocspResponses)&&p.ocspResponses.every(e=>X(e)),"The `ocspResponses` property of `signatureData` must be a array of `OCSPResponses`."),b=p.ocspResponses?.map(e=>({response_code:200,body:d.o4.fromUint8Array(new Uint8Array(e.body)),token:e.serialNumber}))??[],b.length||((0,c.R8)("The `TwoStepSignatureCallback` didn't return certificate revocation responses; trying to fetch them online."),b=await this.backend.getRevocationResponses(f)))),Y(p)){const e=p;(0,c.V1)(null==e.timestampResponse||e.timestampResponse instanceof ArrayBuffer,"The `timestampResponse` property of `signatureData` must be an `ArrayBuffer`."),e.timestampResponse&&(y={response_code:200,body:d.o4.fromUint8Array(new Uint8Array(e.timestampResponse)),token:"1234"})}if(!y&&n?.timestamp&&p instanceof ArrayBuffer){const e=d.o4.toUint8Array(g).buffer;y=await this.backend.timestampData(e,n.timestamp)}const A=await this.backend.client.sign(r,s,i,N.xz[a.signatureType],g,f,G(p)?"pkcs7":Y(p)?"raw":n?.signatureContainer?n.signatureContainer:null,y,b);return n?.ltv&&A.signature.certificateChainValidationStatus===ee.k.ok_but_could_not_check_revocation&&(0,c.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(this.backend._state.certificateCheckTime),e}}}var ne=n(62700),ie=n(87737),ae=n(89353);class se extends te{constructor(e){super(e)}async signDocumentAndReload(e,t){t=(0,F.k)(t),(0,c.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),r=await this.getCertificates(s,n,`${a}get_certificates`,i);e?.signingData?.certificates&&(0,c.R8)("`signingData.certificates` is ignored when signing with `NutrientViewer.StandaloneSigningServiceData`; the signing service provides the signing certificate chain. Use `trustedCAsCallback` to configure trust anchors for standalone validation.");const o=this.signatureCallbackFactory(s,n,r,e,t,`${a}sign_hash`);return await super.signDocumentAndReload({...e,signingData:{...e?.signingData,signatureType:e?.signingData?.signatureType||Z.D.CAdES,certificates:r}},o)}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 c.uE(`The signing service failed to retrieve certificates: Failed to fetch from ${s}`)}if(!a.ok)throw new c.uE(`The signing service failed to retrieve certificates: ${await a.json()}`);const r=(await a.json())?.data||{};return r.certificates.concat(r.ca_certificates).map(e=>d.o4.fromBase64(e))}resolveApiBasePath(e){return(0,ne.i)(e.jwt).api_base_path||"/api/"}resolveServerUrl(e){const t=e.serverUrl||(0,ne.i)(e.jwt).server_url;return(0,c.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 r=>{let o,{hash:l,dataToBeSigned:h}=r;try{o=await fetch(`${e}${s}`,{method:"POST",headers:{Authorization:`Bearer ${t}`,Accept:"application/json","Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({dataToBeSigned:d.o4.fromUint8Array(h),hash:l,signatureType:i?.signingData?.signatureType||Z.D.CAdES,signingToken:a.signingToken,cadesLevel:i?.signingData?.padesLevel||ie.s.b_lt})})}catch(t){throw new c.uE(`The signing service failed to retrieve certificates: Failed to fetch from ${e}${s}`)}if(!o.ok)throw new c.uE(`The signing service failed to sign: ${await o.text()}`);const u=(await o.json())?.data||{};if(i?.signingData?.signatureContainer===ae.Y.pkcs7){const e={pkcs7:d.o4.toUint8Array(u.pkcs7).buffer};return u.ocspResponses&&(e.ocspResponses=u.ocspResponses.map(e=>({serialNumber:e.serialNumber,body:d.o4.toUint8Array(e.body).buffer}))),e}{const e={certificates:n,signedData:d.o4.toUint8Array(u.signedData).buffer,timestampResponse:d.o4.toUint8Array(u.timestampResponse).buffer};return u.ocspResponses&&(e.ocspResponses=u.ocspResponses.map(e=>({serialNumber:e.serialNumber,body:d.o4.toUint8Array(e.body).buffer}))),e}}}}var re=n(53276),oe=n(9855);class ce extends(l.mS({baseUrl:null,baseCoreUrl:null,baseProcessorEngineUrl:null,licenseKey:null,document:null,backendPermissions:new re.A,documentResponse:null,disableWebAssemblyStreaming:!1,enableAutomaticLinkExtraction:!1,overrideMemoryLimit:null,features:(0,l.B8)(),signatureFeatureAvailability:oe.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:!0,enableCoreUnifiedComments:!1,enableCorePreservePDFAccessibility:!1,httpHeaders:null,canvasRendering:!1,certificateCheckTime:"signing_time",storage:{mode:"opfs",minFileSize:52428800,isAuto:!0}})){}const le=n(86177).Fe,de=new a.iy(le);let he=0;const ue=52428800;function me(e){return e&&"object"==typeof e&&"isAuto"in e||e&&"object"==typeof e&&"memory"===e.mode?e:"memory"===e?{mode:"memory"}:"auto"===e?{mode:"opfs",minFileSize:ue,isAuto:!0}:"opfs"===e?{mode:"opfs",minFileSize:null,isAuto:!1}:e&&"object"==typeof e&&"opfs"===e.mode?{mode:"opfs",minFileSize:"number"==typeof e.minFileSize?e.minFileSize:null,isAuto:!1}:(null!=e&&(0,c.R8)(`tempStorage: unrecognized value ${JSON.stringify(e)}. Valid values are "memory", "auto", "opfs", or { mode: "opfs", minFileSize?: number }. Defaulting to "auto".`),{mode:"opfs",minFileSize:ue,isAuto:!0})}class pe extends z.K{constructor(e){super(),(0,i.A)(this,"type","STANDALONE"),(0,i.A)(this,"_didDestroyResources",!1),(0,i.A)(this,"_isDestroyed",!1),(0,i.A)(this,"standaloneDocumentSigner",new te(this)),(0,i.A)(this,"signingServiceDocumentSigner",new se(this)),(0,i.A)(this,"_XFDF",null),fe(e);const{baseUrl:t,baseCoreUrl:n,baseProcessorEngineUrl:a,instantJSON:s,XFDF:r,enableAutomaticLinkExtraction:c,overrideMemoryLimit:l,trustedCAsCallback:d,electronAppName:h,appName:m,isSharePoint:p,isSalesforce:y,productId:b,processorEngine:A,dynamicFonts:S,inlineWorkers:v,formsConfiguration:F,allowLinearizedLoading:_,unifiedCommentsSupport:P,preservePDFAccessibility:w,canvasRendering:C}=e;"string"==typeof r&&(this._XFDF={source:r,keepCurrentAnnotations:!0===e.XFDFKeepCurrentAnnotations,ignorePageRotation:!0===e.XFDFIgnorePageRotation,richTextEnabled:!0===e.XFDFRichTextEnabled}),s&&s.annotations&&(s.annotations=s.annotations.map(e=>(e.id=e.id?.toString(),e))),this._instantJSON=s,this._formsConfiguration=F,"function"==typeof d&&(this._trustedCAsCallback=d);const{disableWebAssemblyStreaming:k,customFonts:D,fontSubstitutions:T}=e,{standaloneInstancesPoolSize:R}=e;void 0!==R&&(de.size=R);const I=!!e.electronicSignatures&&Boolean(e.electronicSignatures.forceLegacySignaturesFeature);let O=b||null;!p&&!y||O||(O=p?f.v.SharePoint:f.v.Salesforce),this._state=new ce(ge({baseUrl:t,baseCoreUrl:n,baseProcessorEngineUrl:a,licenseKey:e.licenseKey,document:e.document,disableWebAssemblyStreaming:k,enableAutomaticLinkExtraction:c,overrideMemoryLimit:l,documentHandle:"0",customFonts:D,fontSubstitutions:T,forceLegacySignaturesFeature:I,appName:m||h,productId:O,processorEngine:A||g.j.fasterProcessing,dynamicFonts:S,inlineWorkers:v,allowLinearizedLoading:_,enableCoreUnifiedComments:P,enableCorePreservePDFAccessibility:w,httpHeaders:e.httpHeaders,canvasRendering:C??!1,certificateCheckTime:e.certificateCheckTime,tempStorage:me(e.tempStorage)})),this._requestQueue=new o.L(u.z3);const{object:E,checkIn:x}=de.checkOut();this.client=E,this.checkIn=x;const V=s?{annotations:s.annotations||[],formFields:s.formFields||[],formFieldValues:s.formFieldValues||[],skippedPdfObjectIds:s.skippedPdfObjectIds||[],skippedPdfFormFieldIds:s.skippedPdfFormFieldIds||[],attachments:s.attachments||{},bookmarks:s.bookmarks||[],skippedPdfBookmarkIds:s.skippedPdfBookmarkIds||[],comments:s.comments||void 0,skippedComments:s.skippedComments||void 0,format:s.format,...s.pdfId?{pdfId:s.pdfId}:null}:null;this.provider=new Q(this.client,V),he+=1}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){}destroyResources(){this._didDestroyResources||(this._didDestroyResources=!0,this.corePDFDocument?.destroy(),this.provider?.destroy(),this._requestQueue?.destroy(),he=Math.max(0,he-1),0===he&&(0,r.J4)())}destroy(){this._isDestroyed||(this._isDestroyed=!0,this.destroyResources(),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)}renderAnnotationAtlas(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"normal";return this.corePDFDocument.renderAnnotationAtlas(e,t,n,i)}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,c.R8)("Annotation must have a pageIndex."),1):(e.lineHeightFactor&&(0,c.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)