@d-i-t-a/reader 2.3.12 → 2.3.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.js +5 -2
- package/dist/esm/index.js.map +2 -2
- package/dist/reader.css +1 -1
- package/dist/reader.css.map +1 -1
- package/dist/reader.js +3 -3
- package/dist/reader.js.map +2 -2
- package/package.json +4 -4
package/dist/reader.js
CHANGED
|
@@ -67,7 +67,7 @@ function print() { __p += __j.call(arguments, '') }
|
|
|
67
67
|
`?"\\n":Q==="\r"?"\\r":`\\${Q}`)}function we(pe){return/^[\x00-\x7F]*$/.test(pe)}function Ae(pe){let Q=["\xFE\xFF"];for(let ce=0,Ue=pe.length;ce<Ue;ce++){let ct=pe.charCodeAt(ce);Q.push(String.fromCharCode(ct>>8&255),String.fromCharCode(ct&255))}return Q.join("")}function Oe(pe){return decodeURIComponent(escape(pe))}function Be(pe){return unescape(encodeURIComponent(pe))}function ot(pe){return typeof pe=="object"&&pe!==null&&pe.byteLength!==void 0}function ze(pe,Q){if(pe.length!==Q.length)return!1;for(let ce=0,Ue=pe.length;ce<Ue;ce++)if(pe[ce]!==Q[ce])return!1;return!0}function Je(pe=new Date){return[pe.getUTCFullYear().toString(),(pe.getUTCMonth()+1).toString().padStart(2,"0"),pe.getUTCDate().toString().padStart(2,"0"),pe.getUTCHours().toString().padStart(2,"0"),pe.getUTCMinutes().toString().padStart(2,"0"),pe.getUTCSeconds().toString().padStart(2,"0")].join("")}function Ge(){let pe=Object.create(null),Q=!1;return Object.defineProperty(pe,"settled",{get(){return Q}}),pe.promise=new Promise(function(ce,Ue){pe.resolve=function(ct){Q=!0,ce(ct)},pe.reject=function(ct){Q=!0,Ue(ct)}}),pe}},(r,t,n)=>{var i=n(3)},(r,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isNodeJS=void 0;let n=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser");t.isNodeJS=n},(__unused_webpack_module,exports,__w_pdfjs_require__)=>{var r,n,i,o,a,l,u,d,ax,y;Object.defineProperty(exports,"__esModule",{value:!0}),exports.build=exports.RenderTask=exports.PDFWorkerUtil=exports.PDFWorker=exports.PDFPageProxy=exports.PDFDocumentProxy=exports.PDFDocumentLoadingTask=exports.PDFDataRangeTransport=exports.LoopbackPort=exports.DefaultStandardFontDataFactory=exports.DefaultCanvasFactory=exports.DefaultCMapReaderFactory=void 0,exports.getDocument=getDocument,exports.setPDFNetworkStreamFactory=setPDFNetworkStreamFactory,exports.version=void 0;var _util=__w_pdfjs_require__(1),_display_utils=__w_pdfjs_require__(5),_font_loader=__w_pdfjs_require__(7),_annotation_storage=__w_pdfjs_require__(8),_canvas=__w_pdfjs_require__(10),_worker_options=__w_pdfjs_require__(13),_is_node=__w_pdfjs_require__(3),_message_handler=__w_pdfjs_require__(14),_metadata=__w_pdfjs_require__(15),_optional_content_config=__w_pdfjs_require__(16),_transport_stream=__w_pdfjs_require__(17),_xfa_text=__w_pdfjs_require__(18);let DEFAULT_RANGE_CHUNK_SIZE=65536,RENDERING_CANCELLED_TIMEOUT=100,DefaultCanvasFactory=_display_utils.DOMCanvasFactory;exports.DefaultCanvasFactory=DefaultCanvasFactory;let DefaultCMapReaderFactory=_display_utils.DOMCMapReaderFactory;exports.DefaultCMapReaderFactory=DefaultCMapReaderFactory;let DefaultStandardFontDataFactory=_display_utils.DOMStandardFontDataFactory;if(exports.DefaultStandardFontDataFactory=DefaultStandardFontDataFactory,_is_node.isNodeJS){let{NodeCanvasFactory:w,NodeCMapReaderFactory:p,NodeStandardFontDataFactory:m}=__w_pdfjs_require__(19);exports.DefaultCanvasFactory=DefaultCanvasFactory=w,exports.DefaultCMapReaderFactory=DefaultCMapReaderFactory=p,exports.DefaultStandardFontDataFactory=DefaultStandardFontDataFactory=m}let createPDFNetworkStream;function setPDFNetworkStreamFactory(w){createPDFNetworkStream=w}function getDocument(w){let p=new PDFDocumentLoadingTask,m;if(typeof w=="string"||w instanceof URL)m={url:w};else if((0,_util.isArrayBuffer)(w))m={data:w};else if(w instanceof PDFDataRangeTransport)m={range:w};else{if(typeof w!="object")throw new Error("Invalid parameter in getDocument, need either string, URL, Uint8Array, or parameter object.");if(!w.url&&!w.data&&!w.range)throw new Error("Invalid parameter object: need either .data, .range or .url");m=w}let f=Object.create(null),g=null,v=null;for(let C in m){let O=m[C];switch(C){case"url":if(typeof window!="undefined")try{f[C]=new URL(O,window.location).href;continue}catch(E){(0,_util.warn)(`Cannot create valid URL: "${E}".`)}else if(typeof O=="string"||O instanceof URL){f[C]=O.toString();continue}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.");case"range":g=O;continue;case"worker":v=O;continue;case"data":if(_is_node.isNodeJS&&typeof Buffer!="undefined"&&O instanceof Buffer)f[C]=new Uint8Array(O);else{if(O instanceof Uint8Array)break;if(typeof O=="string")f[C]=(0,_util.stringToBytes)(O);else if(typeof O=="object"&&O!==null&&!isNaN(O.length))f[C]=new Uint8Array(O);else if((0,_util.isArrayBuffer)(O))f[C]=new Uint8Array(O);else throw new Error("Invalid PDF binary data: either typed array, string, or array-like object is expected in the data property.")}continue}f[C]=O}if(f.CMapReaderFactory=f.CMapReaderFactory||DefaultCMapReaderFactory,f.StandardFontDataFactory=f.StandardFontDataFactory||DefaultStandardFontDataFactory,f.ignoreErrors=f.stopAtErrors!==!0,f.fontExtraProperties=f.fontExtraProperties===!0,f.pdfBug=f.pdfBug===!0,f.enableXfa=f.enableXfa===!0,(!Number.isInteger(f.rangeChunkSize)||f.rangeChunkSize<1)&&(f.rangeChunkSize=DEFAULT_RANGE_CHUNK_SIZE),(typeof f.docBaseUrl!="string"||(0,_display_utils.isDataScheme)(f.docBaseUrl))&&(f.docBaseUrl=null),(!Number.isInteger(f.maxImageSize)||f.maxImageSize<-1)&&(f.maxImageSize=-1),typeof f.cMapUrl!="string"&&(f.cMapUrl=null),typeof f.standardFontDataUrl!="string"&&(f.standardFontDataUrl=null),typeof f.useWorkerFetch!="boolean"&&(f.useWorkerFetch=f.CMapReaderFactory===_display_utils.DOMCMapReaderFactory&&f.StandardFontDataFactory===_display_utils.DOMStandardFontDataFactory),typeof f.isEvalSupported!="boolean"&&(f.isEvalSupported=!0),typeof f.disableFontFace!="boolean"&&(f.disableFontFace=_is_node.isNodeJS),typeof f.useSystemFonts!="boolean"&&(f.useSystemFonts=!_is_node.isNodeJS&&!f.disableFontFace),(typeof f.ownerDocument!="object"||f.ownerDocument===null)&&(f.ownerDocument=globalThis.document),typeof f.disableRange!="boolean"&&(f.disableRange=!1),typeof f.disableStream!="boolean"&&(f.disableStream=!1),typeof f.disableAutoFetch!="boolean"&&(f.disableAutoFetch=!1),(0,_util.setVerbosityLevel)(f.verbosity),!v){let C={verbosity:f.verbosity,port:_worker_options.GlobalWorkerOptions.workerPort};v=C.port?PDFWorker.fromPort(C):new PDFWorker(C),p._worker=v}let A=p.docId;return v.promise.then(function(){if(p.destroyed)throw new Error("Loading aborted");let C=_fetchDocument(v,f,g,A),O=new Promise(function(E){let T;g?T=new _transport_stream.PDFDataTransportStream({length:f.length,initialData:f.initialData,progressiveDone:f.progressiveDone,contentDispositionFilename:f.contentDispositionFilename,disableRange:f.disableRange,disableStream:f.disableStream},g):f.data||(T=createPDFNetworkStream({url:f.url,length:f.length,httpHeaders:f.httpHeaders,withCredentials:f.withCredentials,rangeChunkSize:f.rangeChunkSize,disableRange:f.disableRange,disableStream:f.disableStream})),E(T)});return Promise.all([C,O]).then(function([E,T]){if(p.destroyed)throw new Error("Loading aborted");let I=new _message_handler.MessageHandler(A,E,v.port),M=new WorkerTransport(I,p,T,f);p._transport=M,I.send("Ready",null)})}).catch(p._capability.reject),p}async function _fetchDocument(w,p,m,f){if(w.destroyed)throw new Error("Worker was destroyed");m&&(p.length=m.length,p.initialData=m.initialData,p.progressiveDone=m.progressiveDone,p.contentDispositionFilename=m.contentDispositionFilename);let g=await w.messageHandler.sendWithPromise("GetDocRequest",{docId:f,apiVersion:"2.14.305",source:{data:p.data,url:p.url,password:p.password,disableAutoFetch:p.disableAutoFetch,rangeChunkSize:p.rangeChunkSize,length:p.length},maxImageSize:p.maxImageSize,disableFontFace:p.disableFontFace,docBaseUrl:p.docBaseUrl,ignoreErrors:p.ignoreErrors,isEvalSupported:p.isEvalSupported,fontExtraProperties:p.fontExtraProperties,enableXfa:p.enableXfa,useSystemFonts:p.useSystemFonts,cMapUrl:p.useWorkerFetch?p.cMapUrl:null,standardFontDataUrl:p.useWorkerFetch?p.standardFontDataUrl:null});if(w.destroyed)throw new Error("Worker was destroyed");return g}let t=class{constructor(){var p;this._capability=(0,_util.createPromiseCapability)(),this._transport=null,this._worker=null,this.docId=`d${Nr(t,r,(p=+It(t,r))+1),p}`,this.destroyed=!1,this.onPassword=null,this.onProgress=null,this.onUnsupportedFeature=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0,await this._transport?.destroy(),this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}},PDFDocumentLoadingTask=t;r=new WeakMap,_n(PDFDocumentLoadingTask,r,0),exports.PDFDocumentLoadingTask=PDFDocumentLoadingTask;class PDFDataRangeTransport{constructor(p,m,f=!1,g=null){this.length=p,this.initialData=m,this.progressiveDone=f,this.contentDispositionFilename=g,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=(0,_util.createPromiseCapability)()}addRangeListener(p){this._rangeListeners.push(p)}addProgressListener(p){this._progressListeners.push(p)}addProgressiveReadListener(p){this._progressiveReadListeners.push(p)}addProgressiveDoneListener(p){this._progressiveDoneListeners.push(p)}onDataRange(p,m){for(let f of this._rangeListeners)f(p,m)}onDataProgress(p,m){this._readyCapability.promise.then(()=>{for(let f of this._progressListeners)f(p,m)})}onDataProgressiveRead(p){this._readyCapability.promise.then(()=>{for(let m of this._progressiveReadListeners)m(p)})}onDataProgressiveDone(){this._readyCapability.promise.then(()=>{for(let p of this._progressiveDoneListeners)p()})}transportReady(){this._readyCapability.resolve()}requestDataRange(p,m){(0,_util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}exports.PDFDataRangeTransport=PDFDataRangeTransport;class PDFDocumentProxy{constructor(p,m){this._pdfInfo=p,this._transport=m,Object.defineProperty(this,"fingerprint",{get(){return(0,_display_utils.deprecated)("`PDFDocumentProxy.fingerprint`, please use `PDFDocumentProxy.fingerprints` instead."),this.fingerprints[0]}}),Object.defineProperty(this,"getStats",{value:async()=>((0,_display_utils.deprecated)("`PDFDocumentProxy.getStats`, please use the `PDFDocumentProxy.stats`-getter instead."),this.stats||{streamTypes:{},fontTypes:{}})})}get annotationStorage(){return this._transport.annotationStorage}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get stats(){return this._transport.stats}get isPureXfa(){return!!this._transport._htmlForXfa}get allXfaHtml(){return this._transport._htmlForXfa}getPage(p){return this._transport.getPage(p)}getPageIndex(p){return this._transport.getPageIndex(p)}getDestinations(){return this._transport.getDestinations()}getDestination(p){return this._transport.getDestination(p)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJavaScript(){return this._transport.getJavaScript()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig(){return this._transport.getOptionalContentConfig()}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(p=!1){return this._transport.startCleanup(p||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}saveDocument(){return this._transport.annotationStorage.size<=0&&(0,_display_utils.deprecated)("saveDocument called while `annotationStorage` is empty, please use the getData-method instead."),this._transport.saveDocument()}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}exports.PDFDocumentProxy=PDFDocumentProxy;class PDFPageProxy{constructor(p,m,f,g,v=!1){this._pageIndex=p,this._pageInfo=m,this._ownerDocument=g,this._transport=f,this._stats=v?new _display_utils.StatTimer:null,this._pdfBug=v,this.commonObjs=f.commonObjs,this.objs=new PDFObjects,this._bitmaps=new Set,this.cleanupAfterRender=!1,this.pendingCleanup=!1,this._intentStates=new Map,this._annotationPromises=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:p,rotation:m=this.rotate,offsetX:f=0,offsetY:g=0,dontFlip:v=!1}={}){return new _display_utils.PageViewport({viewBox:this.view,scale:p,rotation:m,offsetX:f,offsetY:g,dontFlip:v})}getAnnotations({intent:p="display"}={}){let m=this._transport.getRenderingIntent(p),f=this._annotationPromises.get(m.cacheKey);return f||(f=this._transport.getAnnotations(this._pageIndex,m.renderingIntent),this._annotationPromises.set(m.cacheKey,f),f=f.then(g=>{for(let v of g)v.titleObj!==void 0&&Object.defineProperty(v,"title",{get(){return(0,_display_utils.deprecated)("`title`-property on annotation, please use `titleObj` instead."),v.titleObj.str}}),v.contentsObj!==void 0&&Object.defineProperty(v,"contents",{get(){return(0,_display_utils.deprecated)("`contents`-property on annotation, please use `contentsObj` instead."),v.contentsObj.str}});return g})),f}getJSActions(){return this._jsActionsPromise||=this._transport.getPageJSActions(this._pageIndex)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:p,viewport:m,intent:f="display",annotationMode:g=_util.AnnotationMode.ENABLE,transform:v=null,imageLayer:A=null,canvasFactory:C=null,background:O=null,optionalContentConfigPromise:E=null,annotationCanvasMap:T=null,pageColors:I=null}){arguments[0]?.renderInteractiveForms!==void 0&&((0,_display_utils.deprecated)("render no longer accepts the `renderInteractiveForms`-option, please use the `annotationMode`-option instead."),arguments[0].renderInteractiveForms===!0&&g===_util.AnnotationMode.ENABLE&&(g=_util.AnnotationMode.ENABLE_FORMS)),arguments[0]?.includeAnnotationStorage!==void 0&&((0,_display_utils.deprecated)("render no longer accepts the `includeAnnotationStorage`-option, please use the `annotationMode`-option instead."),arguments[0].includeAnnotationStorage===!0&&g===_util.AnnotationMode.ENABLE&&(g=_util.AnnotationMode.ENABLE_STORAGE)),this._stats&&this._stats.time("Overall");let M=this._transport.getRenderingIntent(f,g);this.pendingCleanup=!1,E||(E=this._transport.getOptionalContentConfig());let j=this._intentStates.get(M.cacheKey);j||(j=Object.create(null),this._intentStates.set(M.cacheKey,j)),j.streamReaderCancelTimeout&&(clearTimeout(j.streamReaderCancelTimeout),j.streamReaderCancelTimeout=null);let U=C||new DefaultCanvasFactory({ownerDocument:this._ownerDocument}),B=!!(M.renderingIntent&_util.RenderingIntentFlag.PRINT);j.displayReadyCapability||(j.displayReadyCapability=(0,_util.createPromiseCapability)(),j.operatorList={fnArray:[],argsArray:[],lastChunk:!1},this._stats&&this._stats.time("Page Request"),this._pumpOperatorList(M));let N=ne=>{j.renderTasks.delete(q),(this.cleanupAfterRender||B)&&(this.pendingCleanup=!0),this._tryCleanup(),ne?(q.capability.reject(ne),this._abortOperatorList({intentState:j,reason:ne instanceof Error?ne:new Error(ne)})):q.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"))},q=new InternalRenderTask({callback:N,params:{canvasContext:p,viewport:m,transform:v,imageLayer:A,background:O},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:T,operatorList:j.operatorList,pageIndex:this._pageIndex,canvasFactory:U,useRequestAnimationFrame:!B,pdfBug:this._pdfBug,pageColors:I});(j.renderTasks||=new Set).add(q);let z=q.task;return Promise.all([j.displayReadyCapability.promise,E]).then(([ne,oe])=>{if(this.pendingCleanup){N();return}this._stats&&this._stats.time("Rendering"),q.initializeGraphics({transparency:ne,optionalContentConfig:oe}),q.operatorListChanged()}).catch(N),z}getOperatorList({intent:p="display",annotationMode:m=_util.AnnotationMode.ENABLE}={}){function f(){v.operatorList.lastChunk&&(v.opListReadCapability.resolve(v.operatorList),v.renderTasks.delete(A))}let g=this._transport.getRenderingIntent(p,m,!0),v=this._intentStates.get(g.cacheKey);v||(v=Object.create(null),this._intentStates.set(g.cacheKey,v));let A;return v.opListReadCapability||(A=Object.create(null),A.operatorListChanged=f,v.opListReadCapability=(0,_util.createPromiseCapability)(),(v.renderTasks||=new Set).add(A),v.operatorList={fnArray:[],argsArray:[],lastChunk:!1},this._stats&&this._stats.time("Page Request"),this._pumpOperatorList(g)),v.opListReadCapability.promise}streamTextContent({disableCombineTextItems:p=!1,includeMarkedContent:m=!1}={}){let f=100;return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,combineTextItems:p!==!0,includeMarkedContent:m===!0},{highWaterMark:f,size(g){return g.items.length}})}getTextContent(p={}){if(this._transport._htmlForXfa)return this.getXfa().then(f=>_xfa_text.XfaText.textContent(f));let m=this.streamTextContent(p);return new Promise(function(f,g){function v(){A.read().then(function({value:O,done:E}){if(E){f(C);return}Object.assign(C.styles,O.styles),C.items.push(...O.items),v()},g)}let A=m.getReader(),C={items:[],styles:Object.create(null)};v()})}getStructTree(){return this._structTreePromise||=this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;let p=[];for(let m of this._intentStates.values())if(this._abortOperatorList({intentState:m,reason:new Error("Page was destroyed."),force:!0}),!m.opListReadCapability)for(let f of m.renderTasks)p.push(f.completed),f.cancel();this.objs.clear();for(let m of this._bitmaps)m.close();return this._bitmaps.clear(),this._annotationPromises.clear(),this._jsActionsPromise=null,this._structTreePromise=null,this.pendingCleanup=!1,Promise.all(p)}cleanup(p=!1){return this.pendingCleanup=!0,this._tryCleanup(p)}_tryCleanup(p=!1){if(!this.pendingCleanup)return!1;for(let{renderTasks:m,operatorList:f}of this._intentStates.values())if(m.size>0||!f.lastChunk)return!1;this._intentStates.clear(),this.objs.clear(),this._annotationPromises.clear(),this._jsActionsPromise=null,this._structTreePromise=null,p&&this._stats&&(this._stats=new _display_utils.StatTimer);for(let m of this._bitmaps)m.close();return this._bitmaps.clear(),this.pendingCleanup=!1,!0}_startRenderPage(p,m){let f=this._intentStates.get(m);!f||(this._stats&&this._stats.timeEnd("Page Request"),f.displayReadyCapability&&f.displayReadyCapability.resolve(p))}_renderPageChunk(p,m){for(let f=0,g=p.length;f<g;f++)m.operatorList.fnArray.push(p.fnArray[f]),m.operatorList.argsArray.push(p.argsArray[f]);m.operatorList.lastChunk=p.lastChunk;for(let f of m.renderTasks)f.operatorListChanged();p.lastChunk&&this._tryCleanup()}_pumpOperatorList({renderingIntent:p,cacheKey:m}){let g=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:p,cacheKey:m,annotationStorage:p&_util.RenderingIntentFlag.ANNOTATIONS_STORAGE?this._transport.annotationStorage.serializable:null}).getReader(),v=this._intentStates.get(m);v.streamReader=g;let A=()=>{g.read().then(({value:C,done:O})=>{if(O){v.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(C,v),A())},C=>{if(v.streamReader=null,!this._transport.destroyed){if(v.operatorList){v.operatorList.lastChunk=!0;for(let O of v.renderTasks)O.operatorListChanged();this._tryCleanup()}if(v.displayReadyCapability)v.displayReadyCapability.reject(C);else if(v.opListReadCapability)v.opListReadCapability.reject(C);else throw C}})};A()}_abortOperatorList({intentState:p,reason:m,force:f=!1}){if(!!p.streamReader){if(!f){if(p.renderTasks.size>0)return;if(m instanceof _display_utils.RenderingCancelledException){p.streamReaderCancelTimeout=setTimeout(()=>{this._abortOperatorList({intentState:p,reason:m,force:!0}),p.streamReaderCancelTimeout=null},RENDERING_CANCELLED_TIMEOUT);return}}if(p.streamReader.cancel(new _util.AbortException(m.message)).catch(()=>{}),p.streamReader=null,!this._transport.destroyed){for(let[g,v]of this._intentStates)if(v===p){this._intentStates.delete(g);break}this.cleanup()}}}get stats(){return this._stats}}exports.PDFPageProxy=PDFPageProxy;class LoopbackPort{constructor(){this._listeners=[],this._deferred=Promise.resolve()}postMessage(p,m){let f={data:structuredClone(p,m)};this._deferred.then(()=>{for(let g of this._listeners)g.call(this,f)})}addEventListener(p,m){this._listeners.push(m)}removeEventListener(p,m){let f=this._listeners.indexOf(m);this._listeners.splice(f,1)}terminate(){this._listeners.length=0}}exports.LoopbackPort=LoopbackPort;let PDFWorkerUtil={isWorkerDisabled:!1,fallbackWorkerSrc:null,fakeWorkerId:0};exports.PDFWorkerUtil=PDFWorkerUtil;{if(_is_node.isNodeJS&&typeof Ha=="function")PDFWorkerUtil.isWorkerDisabled=!0,PDFWorkerUtil.fallbackWorkerSrc="./pdf.worker.js";else if(typeof document=="object"){let w=document?.currentScript?.src;w&&(PDFWorkerUtil.fallbackWorkerSrc=w.replace(/(\.(?:min\.)?js)(\?.*)?$/i,".worker$1$2"))}PDFWorkerUtil.isSameOrigin=function(w,p){let m;try{if(m=new URL(w),!m.origin||m.origin==="null")return!1}catch(g){return!1}let f=new URL(p,m);return m.origin===f.origin},PDFWorkerUtil.createCDNWrapper=function(w){let p=`importScripts("${w}");`;return URL.createObjectURL(new Blob([p]))}}let _PDFWorker=class{constructor({name:w=null,port:p=null,verbosity:m=(0,_util.getVerbosityLevel)()}={}){if(p&&It(_PDFWorker,n).has(p))throw new Error("Cannot use more than one PDFWorker per port.");if(this.name=w,this.destroyed=!1,this.verbosity=m,this._readyCapability=(0,_util.createPromiseCapability)(),this._port=null,this._webWorker=null,this._messageHandler=null,p){It(_PDFWorker,n).set(p,this),this._initializeFromPort(p);return}this._initialize()}get promise(){return this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(w){this._port=w,this._messageHandler=new _message_handler.MessageHandler("main","worker",w),this._messageHandler.on("ready",function(){}),this._readyCapability.resolve()}_initialize(){if(typeof Worker!="undefined"&&!PDFWorkerUtil.isWorkerDisabled&&!_PDFWorker._mainThreadWorkerMessageHandler){let w=_PDFWorker.workerSrc;try{PDFWorkerUtil.isSameOrigin(window.location.href,w)||(w=PDFWorkerUtil.createCDNWrapper(new URL(w,window.location).href));let p=new Worker(w),m=new _message_handler.MessageHandler("main","worker",p),f=()=>{p.removeEventListener("error",g),m.destroy(),p.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},g=()=>{this._webWorker||f()};p.addEventListener("error",g),m.on("test",A=>{if(p.removeEventListener("error",g),this.destroyed){f();return}A?(this._messageHandler=m,this._port=p,this._webWorker=p,this._readyCapability.resolve(),m.send("configure",{verbosity:this.verbosity})):(this._setupFakeWorker(),m.destroy(),p.terminate())}),m.on("ready",A=>{if(p.removeEventListener("error",g),this.destroyed){f();return}try{v()}catch(C){this._setupFakeWorker()}});let v=()=>{let A=new Uint8Array;m.send("test",A,[A.buffer])};v();return}catch(p){(0,_util.info)("The worker has been disabled.")}}this._setupFakeWorker()}_setupFakeWorker(){PDFWorkerUtil.isWorkerDisabled||((0,_util.warn)("Setting up fake worker."),PDFWorkerUtil.isWorkerDisabled=!0),_PDFWorker._setupFakeWorkerGlobal.then(w=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}let p=new LoopbackPort;this._port=p;let m=`fake${PDFWorkerUtil.fakeWorkerId++}`,f=new _message_handler.MessageHandler(m+"_worker",m,p);w.setup(f,p);let g=new _message_handler.MessageHandler(m,m+"_worker",p);this._messageHandler=g,this._readyCapability.resolve(),g.send("configure",{verbosity:this.verbosity})}).catch(w=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${w.message}".`))})}destroy(){this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),It(_PDFWorker,n).delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(w){if(!w?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");return It(this,n).has(w.port)?It(this,n).get(w.port):new _PDFWorker(w)}static get workerSrc(){if(_worker_options.GlobalWorkerOptions.workerSrc)return _worker_options.GlobalWorkerOptions.workerSrc;if(PDFWorkerUtil.fallbackWorkerSrc!==null)return _is_node.isNodeJS||(0,_display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.'),PDFWorkerUtil.fallbackWorkerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _mainThreadWorkerMessageHandler(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch(w){return null}}static get _setupFakeWorkerGlobal(){let loader=async()=>{let mainWorkerMessageHandler=this._mainThreadWorkerMessageHandler;if(mainWorkerMessageHandler)return mainWorkerMessageHandler;if(_is_node.isNodeJS&&typeof Ha=="function"){let worker=eval("require")(this.workerSrc);return worker.WorkerMessageHandler}return await(0,_display_utils.loadScript)(this.workerSrc),window.pdfjsWorker.WorkerMessageHandler};return(0,_util.shadow)(this,"_setupFakeWorkerGlobal",loader())}},PDFWorker=_PDFWorker;n=new WeakMap,_n(PDFWorker,n,new WeakMap),exports.PDFWorker=PDFWorker,PDFWorker.getWorkerSrc=function(){return(0,_display_utils.deprecated)("`PDFWorker.getWorkerSrc()`, please use `PDFWorker.workerSrc` instead."),this.workerSrc};class WorkerTransport{constructor(p,m,f,g){_n(this,i,null);_n(this,o,new Map);_n(this,a,new Map);_n(this,l,null);this.messageHandler=p,this.loadingTask=m,this.commonObjs=new PDFObjects,this.fontLoader=new _font_loader.FontLoader({docId:m.docId,onUnsupportedFeature:this._onUnsupportedFeature.bind(this),ownerDocument:g.ownerDocument,styleElement:g.styleElement}),this._params=g,g.useWorkerFetch||(this.CMapReaderFactory=new g.CMapReaderFactory({baseUrl:g.cMapUrl,isCompressed:g.cMapPacked}),this.StandardFontDataFactory=new g.StandardFontDataFactory({baseUrl:g.standardFontDataUrl})),this.destroyed=!1,this.destroyCapability=null,this._passwordCapability=null,this._networkStream=f,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=(0,_util.createPromiseCapability)(),this.setupMessageHandler()}get annotationStorage(){return(0,_util.shadow)(this,"annotationStorage",new _annotation_storage.AnnotationStorage)}get stats(){return It(this,i)}getRenderingIntent(p,m=_util.AnnotationMode.ENABLE,f=!1){let g=_util.RenderingIntentFlag.DISPLAY,v="";switch(p){case"any":g=_util.RenderingIntentFlag.ANY;break;case"display":break;case"print":g=_util.RenderingIntentFlag.PRINT;break;default:(0,_util.warn)(`getRenderingIntent - invalid intent: ${p}`)}switch(m){case _util.AnnotationMode.DISABLE:g+=_util.RenderingIntentFlag.ANNOTATIONS_DISABLE;break;case _util.AnnotationMode.ENABLE:break;case _util.AnnotationMode.ENABLE_FORMS:g+=_util.RenderingIntentFlag.ANNOTATIONS_FORMS;break;case _util.AnnotationMode.ENABLE_STORAGE:g+=_util.RenderingIntentFlag.ANNOTATIONS_STORAGE,v=this.annotationStorage.hash;break;default:(0,_util.warn)(`getRenderingIntent - invalid annotationMode: ${m}`)}return f&&(g+=_util.RenderingIntentFlag.OPLIST),{renderingIntent:g,cacheKey:`${g}_${v}`}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=(0,_util.createPromiseCapability)(),this._passwordCapability&&this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));let p=[];for(let f of It(this,o).values())p.push(f._destroy());It(this,o).clear(),It(this,a).clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();let m=this.messageHandler.sendWithPromise("Terminate",null);return p.push(m),Promise.all(p).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),Nr(this,l,null),this._getFieldObjectsPromise=null,this._hasJSActionsPromise=null,this._networkStream&&this._networkStream.cancelAllRequests(new _util.AbortException("Worker was terminated.")),this.messageHandler&&(this.messageHandler.destroy(),this.messageHandler=null),this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){let{messageHandler:p,loadingTask:m}=this;p.on("GetReader",(f,g)=>{(0,_util.assert)(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=v=>{this._lastProgress={loaded:v.loaded,total:v.total}},g.onPull=()=>{this._fullReader.read().then(function({value:v,done:A}){if(A){g.close();return}(0,_util.assert)((0,_util.isArrayBuffer)(v),"GetReader - expected an ArrayBuffer."),g.enqueue(new Uint8Array(v),1,[v])}).catch(v=>{g.error(v)})},g.onCancel=v=>{this._fullReader.cancel(v),g.ready.catch(A=>{if(!this.destroyed)throw A})}}),p.on("ReaderHeadersReady",f=>{let g=(0,_util.createPromiseCapability)(),v=this._fullReader;return v.headersReady.then(()=>{(!v.isStreamingSupported||!v.isRangeSupported)&&(this._lastProgress&&m.onProgress?.(this._lastProgress),v.onProgress=A=>{m.onProgress?.({loaded:A.loaded,total:A.total})}),g.resolve({isStreamingSupported:v.isStreamingSupported,isRangeSupported:v.isRangeSupported,contentLength:v.contentLength})},g.reject),g.promise}),p.on("GetRangeReader",(f,g)=>{(0,_util.assert)(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");let v=this._networkStream.getRangeReader(f.begin,f.end);if(!v){g.close();return}g.onPull=()=>{v.read().then(function({value:A,done:C}){if(C){g.close();return}(0,_util.assert)((0,_util.isArrayBuffer)(A),"GetRangeReader - expected an ArrayBuffer."),g.enqueue(new Uint8Array(A),1,[A])}).catch(A=>{g.error(A)})},g.onCancel=A=>{v.cancel(A),g.ready.catch(C=>{if(!this.destroyed)throw C})}}),p.on("GetDoc",({pdfInfo:f})=>{this._numPages=f.numPages,this._htmlForXfa=f.htmlForXfa,delete f.htmlForXfa,m._capability.resolve(new PDFDocumentProxy(f,this))}),p.on("DocException",function(f){let g;switch(f.name){case"PasswordException":g=new _util.PasswordException(f.message,f.code);break;case"InvalidPDFException":g=new _util.InvalidPDFException(f.message);break;case"MissingPDFException":g=new _util.MissingPDFException(f.message);break;case"UnexpectedResponseException":g=new _util.UnexpectedResponseException(f.message,f.status);break;case"UnknownErrorException":g=new _util.UnknownErrorException(f.message,f.details);break;default:(0,_util.unreachable)("DocException - expected a valid Error.")}m._capability.reject(g)}),p.on("PasswordRequest",f=>{if(this._passwordCapability=(0,_util.createPromiseCapability)(),m.onPassword){let g=v=>{v instanceof Error?this._passwordCapability.reject(v):this._passwordCapability.resolve({password:v})};try{m.onPassword(g,f.code)}catch(v){this._passwordCapability.reject(v)}}else this._passwordCapability.reject(new _util.PasswordException(f.message,f.code));return this._passwordCapability.promise}),p.on("DataLoaded",f=>{m.onProgress?.({loaded:f.length,total:f.length}),this.downloadInfoCapability.resolve(f)}),p.on("StartRenderPage",f=>{if(this.destroyed)return;It(this,o).get(f.pageIndex)._startRenderPage(f.transparency,f.cacheKey)}),p.on("commonobj",([f,g,v])=>{if(!this.destroyed&&!this.commonObjs.has(f))switch(g){case"Font":let A=this._params;if("error"in v){let E=v.error;(0,_util.warn)(`Error during font loading: ${E}`),this.commonObjs.resolve(f,E);break}let C=null;A.pdfBug&&globalThis.FontInspector?.enabled&&(C={registerFont(E,T){globalThis.FontInspector.fontAdded(E,T)}});let O=new _font_loader.FontFaceObject(v,{isEvalSupported:A.isEvalSupported,disableFontFace:A.disableFontFace,ignoreErrors:A.ignoreErrors,onUnsupportedFeature:this._onUnsupportedFeature.bind(this),fontRegistry:C});this.fontLoader.bind(O).catch(E=>p.sendWithPromise("FontFallback",{id:f})).finally(()=>{!A.fontExtraProperties&&O.data&&(O.data=null),this.commonObjs.resolve(f,O)});break;case"FontPath":case"Image":this.commonObjs.resolve(f,v);break;default:throw new Error(`Got unknown common object type ${g}`)}}),p.on("obj",([f,g,v,A])=>{if(this.destroyed)return;let C=It(this,o).get(g);if(!C.objs.has(f))switch(v){case"Image":C.objs.resolve(f,A);let O=8e6;if(A){let E;if(A.bitmap){let{bitmap:T,width:I,height:M}=A;E=I*M*4,C._bitmaps.add(T)}else E=A.data?.length||0;E>O&&(C.cleanupAfterRender=!0)}break;case"Pattern":C.objs.resolve(f,A);break;default:throw new Error(`Got unknown object type ${v}`)}}),p.on("DocProgress",f=>{this.destroyed||m.onProgress?.({loaded:f.loaded,total:f.total})}),p.on("DocStats",f=>{this.destroyed||Nr(this,i,Object.freeze({streamTypes:Object.freeze(f.streamTypes),fontTypes:Object.freeze(f.fontTypes)}))}),p.on("UnsupportedFeature",this._onUnsupportedFeature.bind(this)),p.on("FetchBuiltInCMap",f=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.CMapReaderFactory?this.CMapReaderFactory.fetch(f):Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."))),p.on("FetchStandardFontData",f=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.StandardFontDataFactory?this.StandardFontDataFactory.fetch(f):Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.")))}_onUnsupportedFeature({featureId:p}){this.destroyed||this.loadingTask.onUnsupportedFeature?.(p)}getData(){return this.messageHandler.sendWithPromise("GetData",null)}getPage(p){if(!Number.isInteger(p)||p<=0||p>this._numPages)return Promise.reject(new Error("Invalid page request."));let m=p-1,f=It(this,a).get(m);if(f)return f;let g=this.messageHandler.sendWithPromise("GetPage",{pageIndex:m}).then(v=>{if(this.destroyed)throw new Error("Transport destroyed");let A=new PDFPageProxy(m,v,this,this._params.ownerDocument,this._params.pdfBug);return It(this,o).set(m,A),A});return It(this,a).set(m,g),g}getPageIndex(p){return typeof p!="object"||p===null||!Number.isInteger(p.num)||p.num<0||!Number.isInteger(p.gen)||p.gen<0?Promise.reject(new Error("Invalid pageIndex request.")):this.messageHandler.sendWithPromise("GetPageIndex",{num:p.num,gen:p.gen})}getAnnotations(p,m){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:p,intent:m})}saveDocument(){return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:this.annotationStorage.serializable,filename:this._fullReader?.filename??null}).finally(()=>{this.annotationStorage.resetModified()})}getFieldObjects(){return this._getFieldObjectsPromise||=this.messageHandler.sendWithPromise("GetFieldObjects",null)}hasJSActions(){return this._hasJSActionsPromise||=this.messageHandler.sendWithPromise("HasJSActions",null)}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(p){return typeof p!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:p})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getJavaScript(){return this.messageHandler.sendWithPromise("GetJavaScript",null)}getDocJSActions(){return this.messageHandler.sendWithPromise("GetDocJSActions",null)}getPageJSActions(p){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:p})}getStructTree(p){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:p})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(){return this.messageHandler.sendWithPromise("GetOptionalContentConfig",null).then(p=>new _optional_content_config.OptionalContentConfig(p))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){return It(this,l)||Nr(this,l,this.messageHandler.sendWithPromise("GetMetadata",null).then(p=>({info:p[0],metadata:p[1]?new _metadata.Metadata(p[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})))}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(p=!1){if(await this.messageHandler.sendWithPromise("Cleanup",null),!this.destroyed){for(let m of It(this,o).values())if(!m.cleanup())throw new Error(`startCleanup: Page ${m.pageNumber} is currently rendering.`);this.commonObjs.clear(),p||this.fontLoader.clear(),Nr(this,l,null),this._getFieldObjectsPromise=null,this._hasJSActionsPromise=null}}get loadingParams(){let p=this._params;return(0,_util.shadow)(this,"loadingParams",{disableAutoFetch:p.disableAutoFetch,enableXfa:p.enableXfa})}}i=new WeakMap,o=new WeakMap,a=new WeakMap,l=new WeakMap;class PDFObjects{constructor(){_n(this,d);_n(this,u,Object.create(null))}get(p,m=null){if(m){let g=Dr(this,d,ax).call(this,p);return g.capability.promise.then(()=>m(g.data)),null}let f=It(this,u)[p];if(!f?.capability.settled)throw new Error(`Requesting object that isn't resolved yet ${p}.`);return f.data}has(p){return It(this,u)[p]?.capability.settled||!1}resolve(p,m=null){let f=Dr(this,d,ax).call(this,p);f.data=m,f.capability.resolve()}clear(){Nr(this,u,Object.create(null))}}u=new WeakMap,d=new WeakSet,ax=function(p){let m=It(this,u)[p];return m||(It(this,u)[p]={capability:(0,_util.createPromiseCapability)(),data:null})};class RenderTask{constructor(p){this._internalRenderTask=p,this.onContinue=null}get promise(){return this._internalRenderTask.capability.promise}cancel(){this._internalRenderTask.cancel()}}exports.RenderTask=RenderTask;let b=class{constructor({callback:p,params:m,objs:f,commonObjs:g,annotationCanvasMap:v,operatorList:A,pageIndex:C,canvasFactory:O,useRequestAnimationFrame:E=!1,pdfBug:T=!1,pageColors:I=null}){this.callback=p,this.params=m,this.objs=f,this.commonObjs=g,this.annotationCanvasMap=v,this.operatorListIdx=null,this.operatorList=A,this._pageIndex=C,this.canvasFactory=O,this._pdfBug=T,this.pageColors=I,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=E===!0&&typeof window!="undefined",this.cancelled=!1,this.capability=(0,_util.createPromiseCapability)(),this.task=new RenderTask(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=m.canvasContext.canvas}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:p=!1,optionalContentConfig:m}){if(this.cancelled)return;if(this._canvas){if(It(b,y).has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");It(b,y).add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());let{canvasContext:f,viewport:g,transform:v,imageLayer:A,background:C}=this.params;this.gfx=new _canvas.CanvasGraphics(f,this.commonObjs,this.objs,this.canvasFactory,A,m,this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:v,viewport:g,transparency:p,background:C}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback&&this.graphicsReadyCallback()}cancel(p=null){this.running=!1,this.cancelled=!0,this.gfx&&this.gfx.endDrawing(),this._canvas&&It(b,y).delete(this._canvas),this.callback(p||new _display_utils.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,"canvas"))}operatorListChanged(){if(!this.graphicsReady){this.graphicsReadyCallback||(this.graphicsReadyCallback=this._continueBound);return}this.stepper&&this.stepper.updateOperatorList(this.operatorList),!this.running&&this._continue()}_continue(){this.running=!0,!this.cancelled&&(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?window.requestAnimationFrame(()=>{this._nextBound().catch(this._cancelBound)}):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),this._canvas&&It(b,y).delete(this._canvas),this.callback())))}},InternalRenderTask=b;y=new WeakMap,_n(InternalRenderTask,y,new WeakSet);let version="2.14.305";exports.version=version;let build="eaaa8b4ad";exports.build=build},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StatTimer=t.RenderingCancelledException=t.PixelsPerInch=t.PageViewport=t.PDFDateString=t.DOMStandardFontDataFactory=t.DOMSVGFactory=t.DOMCanvasFactory=t.DOMCMapReaderFactory=void 0,t.deprecated=E,t.getFilenameFromUrl=g,t.getPdfFilenameFromUrl=v,t.getXfaPageViewport=M,t.isDataScheme=m,t.isPdfFile=f,t.isValidFetchUrl=C,t.loadScript=O;var i=n(6),o=n(1);let a="http://www.w3.org/2000/svg",j=class{},l=j;Ic(l,"CSS",96),Ic(l,"PDF",72),Ic(l,"PDF_TO_CSS_UNITS",j.CSS/j.PDF),t.PixelsPerInch=l;class u extends i.BaseCanvasFactory{constructor({ownerDocument:B=globalThis.document}={}){super();this._document=B}_createCanvas(B,N){let q=this._document.createElement("canvas");return q.width=B,q.height=N,q}}t.DOMCanvasFactory=u;async function d(U,B=!1){if(C(U,document.baseURI)){let N=await fetch(U);if(!N.ok)throw new Error(N.statusText);return B?new Uint8Array(await N.arrayBuffer()):(0,o.stringToBytes)(await N.text())}return new Promise((N,q)=>{let z=new XMLHttpRequest;z.open("GET",U,!0),B&&(z.responseType="arraybuffer"),z.onreadystatechange=()=>{if(z.readyState===XMLHttpRequest.DONE){if(z.status===200||z.status===0){let ne;if(B&&z.response?ne=new Uint8Array(z.response):!B&&z.responseText&&(ne=(0,o.stringToBytes)(z.responseText)),ne){N(ne);return}}q(new Error(z.statusText))}},z.send(null)})}class h extends i.BaseCMapReaderFactory{_fetchData(B,N){return d(B,this.isCompressed).then(q=>({cMapData:q,compressionType:N}))}}t.DOMCMapReaderFactory=h;class y extends i.BaseStandardFontDataFactory{_fetchData(B){return d(B,!0)}}t.DOMStandardFontDataFactory=y;class b extends i.BaseSVGFactory{_createSVG(B){return document.createElementNS(a,B)}}t.DOMSVGFactory=b;class w{constructor({viewBox:B,scale:N,rotation:q,offsetX:z=0,offsetY:ne=0,dontFlip:oe=!1}){this.viewBox=B,this.scale=N,this.rotation=q,this.offsetX=z,this.offsetY=ne;let ae=(B[2]+B[0])/2,te=(B[3]+B[1])/2,le,xe,fe,J;switch(q%=360,q<0&&(q+=360),q){case 180:le=-1,xe=0,fe=0,J=1;break;case 90:le=0,xe=1,fe=1,J=0;break;case 270:le=0,xe=-1,fe=-1,J=0;break;case 0:le=1,xe=0,fe=0,J=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}oe&&(fe=-fe,J=-J);let D,k,x,R;le===0?(D=Math.abs(te-B[1])*N+z,k=Math.abs(ae-B[0])*N+ne,x=Math.abs(B[3]-B[1])*N,R=Math.abs(B[2]-B[0])*N):(D=Math.abs(ae-B[0])*N+z,k=Math.abs(te-B[1])*N+ne,x=Math.abs(B[2]-B[0])*N,R=Math.abs(B[3]-B[1])*N),this.transform=[le*N,xe*N,fe*N,J*N,D-le*N*ae-fe*N*te,k-xe*N*ae-J*N*te],this.width=x,this.height=R}clone({scale:B=this.scale,rotation:N=this.rotation,offsetX:q=this.offsetX,offsetY:z=this.offsetY,dontFlip:ne=!1}={}){return new w({viewBox:this.viewBox.slice(),scale:B,rotation:N,offsetX:q,offsetY:z,dontFlip:ne})}convertToViewportPoint(B,N){return o.Util.applyTransform([B,N],this.transform)}convertToViewportRectangle(B){let N=o.Util.applyTransform([B[0],B[1]],this.transform),q=o.Util.applyTransform([B[2],B[3]],this.transform);return[N[0],N[1],q[0],q[1]]}convertToPdfPoint(B,N){return o.Util.applyInverseTransform([B,N],this.transform)}}t.PageViewport=w;class p extends o.BaseException{constructor(B,N){super(B,"RenderingCancelledException");this.type=N}}t.RenderingCancelledException=p;function m(U){let B=U.length,N=0;for(;N<B&&U[N].trim()==="";)N++;return U.substring(N,N+5).toLowerCase()==="data:"}function f(U){return typeof U=="string"&&/\.pdf$/i.test(U)}function g(U){let B=U.indexOf("#"),N=U.indexOf("?"),q=Math.min(B>0?B:U.length,N>0?N:U.length);return U.substring(U.lastIndexOf("/",q)+1,q)}function v(U,B="document.pdf"){if(typeof U!="string")return B;if(m(U))return(0,o.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),B;let N=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/,q=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,z=N.exec(U),ne=q.exec(z[1])||q.exec(z[2])||q.exec(z[3]);if(ne&&(ne=ne[0],ne.includes("%")))try{ne=q.exec(decodeURIComponent(ne))[0]}catch(oe){}return ne||B}class A{constructor(){this.started=Object.create(null),this.times=[]}time(B){B in this.started&&(0,o.warn)(`Timer is already running for ${B}`),this.started[B]=Date.now()}timeEnd(B){B in this.started||(0,o.warn)(`Timer has not been started for ${B}`),this.times.push({name:B,start:this.started[B],end:Date.now()}),delete this.started[B]}toString(){let B=[],N=0;for(let q of this.times){let z=q.name;z.length>N&&(N=z.length)}for(let q of this.times){let z=q.end-q.start;B.push(`${q.name.padEnd(N)} ${z}ms
|
|
68
68
|
`)}return B.join("")}}t.StatTimer=A;function C(U,B){try{let{protocol:N}=B?new URL(U,B):new URL(U);return N==="http:"||N==="https:"}catch(N){return!1}}function O(U,B=!1){return new Promise((N,q)=>{let z=document.createElement("script");z.src=U,z.onload=function(ne){B&&z.remove(),N(ne)},z.onerror=function(){q(new Error(`Cannot load script at: ${z.src}`))},(document.head||document.documentElement).appendChild(z)})}function E(U){console.log("Deprecated API usage: "+U)}let T;class I{static toDateObject(B){if(!B||typeof B!="string")return null;T||(T=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?"));let N=T.exec(B);if(!N)return null;let q=parseInt(N[1],10),z=parseInt(N[2],10);z=z>=1&&z<=12?z-1:0;let ne=parseInt(N[3],10);ne=ne>=1&&ne<=31?ne:1;let oe=parseInt(N[4],10);oe=oe>=0&&oe<=23?oe:0;let ae=parseInt(N[5],10);ae=ae>=0&&ae<=59?ae:0;let te=parseInt(N[6],10);te=te>=0&&te<=59?te:0;let le=N[7]||"Z",xe=parseInt(N[8],10);xe=xe>=0&&xe<=23?xe:0;let fe=parseInt(N[9],10)||0;return fe=fe>=0&&fe<=59?fe:0,le==="-"?(oe+=xe,ae+=fe):le==="+"&&(oe-=xe,ae-=fe),new Date(Date.UTC(q,z,ne,oe,ae,te))}}t.PDFDateString=I;function M(U,{scale:B=1,rotation:N=0}){let{width:q,height:z}=U.attributes.style,ne=[0,0,parseInt(q),parseInt(z)];return new w({viewBox:ne,scale:B,rotation:N})}},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BaseStandardFontDataFactory=t.BaseSVGFactory=t.BaseCanvasFactory=t.BaseCMapReaderFactory=void 0;var i=n(1);class o{constructor(){this.constructor===o&&(0,i.unreachable)("Cannot initialize BaseCanvasFactory.")}create(h,y){if(h<=0||y<=0)throw new Error("Invalid canvas size");let b=this._createCanvas(h,y);return{canvas:b,context:b.getContext("2d")}}reset(h,y,b){if(!h.canvas)throw new Error("Canvas is not specified");if(y<=0||b<=0)throw new Error("Invalid canvas size");h.canvas.width=y,h.canvas.height=b}destroy(h){if(!h.canvas)throw new Error("Canvas is not specified");h.canvas.width=0,h.canvas.height=0,h.canvas=null,h.context=null}_createCanvas(h,y){(0,i.unreachable)("Abstract method `_createCanvas` called.")}}t.BaseCanvasFactory=o;class a{constructor({baseUrl:h=null,isCompressed:y=!1}){this.constructor===a&&(0,i.unreachable)("Cannot initialize BaseCMapReaderFactory."),this.baseUrl=h,this.isCompressed=y}async fetch({name:h}){if(!this.baseUrl)throw new Error('The CMap "baseUrl" parameter must be specified, ensure that the "cMapUrl" and "cMapPacked" API parameters are provided.');if(!h)throw new Error("CMap name must be specified.");let y=this.baseUrl+h+(this.isCompressed?".bcmap":""),b=this.isCompressed?i.CMapCompressionType.BINARY:i.CMapCompressionType.NONE;return this._fetchData(y,b).catch(w=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${y}`)})}_fetchData(h,y){(0,i.unreachable)("Abstract method `_fetchData` called.")}}t.BaseCMapReaderFactory=a;class l{constructor({baseUrl:h=null}){this.constructor===l&&(0,i.unreachable)("Cannot initialize BaseStandardFontDataFactory."),this.baseUrl=h}async fetch({filename:h}){if(!this.baseUrl)throw new Error('The standard font "baseUrl" parameter must be specified, ensure that the "standardFontDataUrl" API parameter is provided.');if(!h)throw new Error("Font filename must be specified.");let y=`${this.baseUrl}${h}`;return this._fetchData(y).catch(b=>{throw new Error(`Unable to load font data at: ${y}`)})}_fetchData(h){(0,i.unreachable)("Abstract method `_fetchData` called.")}}t.BaseStandardFontDataFactory=l;class u{constructor(){this.constructor===u&&(0,i.unreachable)("Cannot initialize BaseSVGFactory.")}create(h,y){if(h<=0||y<=0)throw new Error("Invalid SVG dimensions");let b=this._createSVG("svg:svg");return b.setAttribute("version","1.1"),b.setAttribute("width",`${h}px`),b.setAttribute("height",`${y}px`),b.setAttribute("preserveAspectRatio","none"),b.setAttribute("viewBox",`0 0 ${h} ${y}`),b}createElement(h){if(typeof h!="string")throw new Error("Invalid SVG element type");return this._createSVG(h)}_createSVG(h){(0,i.unreachable)("Abstract method `_createSVG` called.")}}t.BaseSVGFactory=u},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FontLoader=t.FontFaceObject=void 0;var i=n(1);class o{constructor({docId:d,onUnsupportedFeature:h,ownerDocument:y=globalThis.document,styleElement:b=null}){this.constructor===o&&(0,i.unreachable)("Cannot initialize BaseFontLoader."),this.docId=d,this._onUnsupportedFeature=h,this._document=y,this.nativeFontFaces=[],this.styleElement=null}addNativeFontFace(d){this.nativeFontFaces.push(d),this._document.fonts.add(d)}insertRule(d){let h=this.styleElement;h||(h=this.styleElement=this._document.createElement("style"),h.id=`PDFJS_FONT_STYLE_TAG_${this.docId}`,this._document.documentElement.getElementsByTagName("head")[0].appendChild(h));let y=h.sheet;y.insertRule(d,y.cssRules.length)}clear(){for(let d of this.nativeFontFaces)this._document.fonts.delete(d);this.nativeFontFaces.length=0,this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async bind(d){if(d.attached||d.missingFile)return;if(d.attached=!0,this.isFontLoadingAPISupported){let y=d.createNativeFontFace();if(y){this.addNativeFontFace(y);try{await y.loaded}catch(b){throw this._onUnsupportedFeature({featureId:i.UNSUPPORTED_FEATURES.errorFontLoadNative}),(0,i.warn)(`Failed to load font '${y.family}': '${b}'.`),d.disableFontFace=!0,b}}return}let h=d.createFontFaceRule();if(h){if(this.insertRule(h),this.isSyncFontLoadingSupported)return;await new Promise(y=>{let b=this._queueLoadingCallback(y);this._prepareFontLoadEvent([h],[d],b)})}}_queueLoadingCallback(d){(0,i.unreachable)("Abstract method `_queueLoadingCallback`.")}get isFontLoadingAPISupported(){let d=!!this._document?.fonts;return(0,i.shadow)(this,"isFontLoadingAPISupported",d)}get isSyncFontLoadingSupported(){(0,i.unreachable)("Abstract method `isSyncFontLoadingSupported`.")}get _loadTestFont(){(0,i.unreachable)("Abstract method `_loadTestFont`.")}_prepareFontLoadEvent(d,h,y){(0,i.unreachable)("Abstract method `_prepareFontLoadEvent`.")}}let a;t.FontLoader=a,t.FontLoader=a=class extends o{constructor(d){super(d);this.loadingContext={requests:[],nextRequestId:0},this.loadTestFontId=0}get isSyncFontLoadingSupported(){let d=!1;return(typeof navigator=="undefined"||/Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent)?.[1]>=14)&&(d=!0),(0,i.shadow)(this,"isSyncFontLoadingSupported",d)}_queueLoadingCallback(d){function h(){for((0,i.assert)(!b.done,"completeRequest() cannot be called twice."),b.done=!0;y.requests.length>0&&y.requests[0].done;){let w=y.requests.shift();setTimeout(w.callback,0)}}let y=this.loadingContext,b={id:`pdfjs-font-loading-${y.nextRequestId++}`,done:!1,complete:h,callback:d};return y.requests.push(b),b}get _loadTestFont(){let d=function(){return atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==")};return(0,i.shadow)(this,"_loadTestFont",d())}_prepareFontLoadEvent(d,h,y){function b(q,z){return q.charCodeAt(z)<<24|q.charCodeAt(z+1)<<16|q.charCodeAt(z+2)<<8|q.charCodeAt(z+3)&255}function w(q,z,ne,oe){let ae=q.substring(0,z),te=q.substring(z+ne);return ae+oe+te}let p,m,f=this._document.createElement("canvas");f.width=1,f.height=1;let g=f.getContext("2d"),v=0;function A(q,z){if(v++,v>30){(0,i.warn)("Load test font never loaded."),z();return}if(g.font="30px "+q,g.fillText(".",0,20),g.getImageData(0,0,1,1).data[3]>0){z();return}setTimeout(A.bind(null,q,z))}let C=`lt${Date.now()}${this.loadTestFontId++}`,O=this._loadTestFont;O=w(O,976,C.length,C);let T=16,I=1482184792,M=b(O,T);for(p=0,m=C.length-3;p<m;p+=4)M=M-I+b(C,p)|0;p<C.length&&(M=M-I+b(C+"XXX",p)|0),O=w(O,T,4,(0,i.string32)(M));let j=`url(data:font/opentype;base64,${btoa(O)});`,U=`@font-face {font-family:"${C}";src:${j}}`;this.insertRule(U);let B=[];for(let q of h)B.push(q.loadedName);B.push(C);let N=this._document.createElement("div");N.style.visibility="hidden",N.style.width=N.style.height="10px",N.style.position="absolute",N.style.top=N.style.left="0px";for(let q of B){let z=this._document.createElement("span");z.textContent="Hi",z.style.fontFamily=q,N.appendChild(z)}this._document.body.appendChild(N),A(C,()=>{N.remove(),y.complete()})}};class l{constructor(d,{isEvalSupported:h=!0,disableFontFace:y=!1,ignoreErrors:b=!1,onUnsupportedFeature:w,fontRegistry:p=null}){this.compiledGlyphs=Object.create(null);for(let m in d)this[m]=d[m];this.isEvalSupported=h!==!1,this.disableFontFace=y===!0,this.ignoreErrors=b===!0,this._onUnsupportedFeature=w,this.fontRegistry=p}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let d;if(!this.cssFontInfo)d=new FontFace(this.loadedName,this.data,{});else{let h={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(h.style=`oblique ${this.cssFontInfo.italicAngle}deg`),d=new FontFace(this.cssFontInfo.fontFamily,this.data,h)}return this.fontRegistry&&this.fontRegistry.registerFont(this),d}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;let d=(0,i.bytesToString)(this.data),h=`url(data:${this.mimetype};base64,${btoa(d)});`,y;if(!this.cssFontInfo)y=`@font-face {font-family:"${this.loadedName}";src:${h}}`;else{let b=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(b+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),y=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${b}src:${h}}`}return this.fontRegistry&&this.fontRegistry.registerFont(this,h),y}getPathGenerator(d,h){if(this.compiledGlyphs[h]!==void 0)return this.compiledGlyphs[h];let y;try{y=d.get(this.loadedName+"_path_"+h)}catch(b){if(!this.ignoreErrors)throw b;return this._onUnsupportedFeature({featureId:i.UNSUPPORTED_FEATURES.errorFontGetPath}),(0,i.warn)(`getPathGenerator - ignoring character: "${b}".`),this.compiledGlyphs[h]=function(w,p){}}if(this.isEvalSupported&&i.FeatureTest.isEvalSupported){let b=[];for(let w of y){let p=w.args!==void 0?w.args.join(","):"";b.push("c.",w.cmd,"(",p,`);
|
|
69
69
|
`)}return this.compiledGlyphs[h]=new Function("c","size",b.join(""))}return this.compiledGlyphs[h]=function(b,w){for(let p of y)p.cmd==="scale"&&(p.args=[w,-w]),b[p.cmd].apply(b,p.args)}}}t.FontFaceObject=l},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AnnotationStorage=void 0;var i=n(9),o=n(1);class a{constructor(){this._storage=new Map,this._modified=!1,this.onSetModified=null,this.onResetModified=null}getValue(u,d){let h=this._storage.get(u);return h===void 0?d:Object.assign(d,h)}getRawValue(u){return this._storage.get(u)}setValue(u,d){let h=this._storage.get(u),y=!1;if(h!==void 0)for(let[b,w]of Object.entries(d))h[b]!==w&&(y=!0,h[b]=w);else y=!0,this._storage.set(u,d);y&&this._setModified()}getAll(){return this._storage.size>0?(0,o.objectFromMap)(this._storage):null}get size(){return this._storage.size}_setModified(){this._modified||(this._modified=!0,typeof this.onSetModified=="function"&&this.onSetModified())}resetModified(){this._modified&&(this._modified=!1,typeof this.onResetModified=="function"&&this.onResetModified())}get serializable(){return this._storage.size>0?this._storage:null}get hash(){let u=new i.MurmurHash3_64;for(let[d,h]of this._storage)u.update(`${d}:${JSON.stringify(h)}`);return u.hexdigest()}}t.AnnotationStorage=a},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MurmurHash3_64=void 0;var i=n(1);let o=3285377520,a=4294901760,l=65535;class u{constructor(h){this.h1=h?h&4294967295:o,this.h2=h?h&4294967295:o}update(h){let y,b;if(typeof h=="string"){y=new Uint8Array(h.length*2),b=0;for(let I=0,M=h.length;I<M;I++){let j=h.charCodeAt(I);j<=255?y[b++]=j:(y[b++]=j>>>8,y[b++]=j&255)}}else if((0,i.isArrayBuffer)(h))y=h.slice(),b=y.byteLength;else throw new Error("Wrong data format in MurmurHash3_64_update. Input must be a string or array.");let w=b>>2,p=b-w*4,m=new Uint32Array(y.buffer,0,w),f=0,g=0,v=this.h1,A=this.h2,C=3432918353,O=461845907,E=C&l,T=O&l;for(let I=0;I<w;I++)I&1?(f=m[I],f=f*C&a|f*E&l,f=f<<15|f>>>17,f=f*O&a|f*T&l,v^=f,v=v<<13|v>>>19,v=v*5+3864292196):(g=m[I],g=g*C&a|g*E&l,g=g<<15|g>>>17,g=g*O&a|g*T&l,A^=g,A=A<<13|A>>>19,A=A*5+3864292196);switch(f=0,p){case 3:f^=y[w*4+2]<<16;case 2:f^=y[w*4+1]<<8;case 1:f^=y[w*4],f=f*C&a|f*E&l,f=f<<15|f>>>17,f=f*O&a|f*T&l,w&1?v^=f:A^=f}this.h1=v,this.h2=A}hexdigest(){let h=this.h1,y=this.h2;h^=y>>>1,h=h*3981806797&a|h*36045&l,y=y*4283543511&a|((y<<16|h>>>16)*2950163797&a)>>>16,h^=y>>>1,h=h*444984403&a|h*60499&l,y=y*3301882366&a|((y<<16|h>>>16)*3120437893&a)>>>16,h^=y>>>1;let b=(h>>>0).toString(16),w=(y>>>0).toString(16);return b.padStart(8,"0")+w.padStart(8,"0")}}t.MurmurHash3_64=u},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CanvasGraphics=void 0;var i=n(1),o=n(11),a=n(12),l=n(3),u=n(5);let d=16,h=100,y=4096,b=15,w=10,p=!0,m=1e3,f=16,g=1.000001;function v(J,D){if(J._removeMirroring)throw new Error("Context is already forwarding operations.");J.__originalSave=J.save,J.__originalRestore=J.restore,J.__originalRotate=J.rotate,J.__originalScale=J.scale,J.__originalTranslate=J.translate,J.__originalTransform=J.transform,J.__originalSetTransform=J.setTransform,J.__originalResetTransform=J.resetTransform,J.__originalClip=J.clip,J.__originalMoveTo=J.moveTo,J.__originalLineTo=J.lineTo,J.__originalBezierCurveTo=J.bezierCurveTo,J.__originalRect=J.rect,J.__originalClosePath=J.closePath,J.__originalBeginPath=J.beginPath,J._removeMirroring=()=>{J.save=J.__originalSave,J.restore=J.__originalRestore,J.rotate=J.__originalRotate,J.scale=J.__originalScale,J.translate=J.__originalTranslate,J.transform=J.__originalTransform,J.setTransform=J.__originalSetTransform,J.resetTransform=J.__originalResetTransform,J.clip=J.__originalClip,J.moveTo=J.__originalMoveTo,J.lineTo=J.__originalLineTo,J.bezierCurveTo=J.__originalBezierCurveTo,J.rect=J.__originalRect,J.closePath=J.__originalClosePath,J.beginPath=J.__originalBeginPath,delete J._removeMirroring},J.save=function(){D.save(),this.__originalSave()},J.restore=function(){D.restore(),this.__originalRestore()},J.translate=function(x,R){D.translate(x,R),this.__originalTranslate(x,R)},J.scale=function(x,R){D.scale(x,R),this.__originalScale(x,R)},J.transform=function(x,R,L,F,W,V){D.transform(x,R,L,F,W,V),this.__originalTransform(x,R,L,F,W,V)},J.setTransform=function(x,R,L,F,W,V){D.setTransform(x,R,L,F,W,V),this.__originalSetTransform(x,R,L,F,W,V)},J.resetTransform=function(){D.resetTransform(),this.__originalResetTransform()},J.rotate=function(x){D.rotate(x),this.__originalRotate(x)},J.clip=function(x){D.clip(x),this.__originalClip(x)},J.moveTo=function(k,x){D.moveTo(k,x),this.__originalMoveTo(k,x)},J.lineTo=function(k,x){D.lineTo(k,x),this.__originalLineTo(k,x)},J.bezierCurveTo=function(k,x,R,L,F,W){D.bezierCurveTo(k,x,R,L,F,W),this.__originalBezierCurveTo(k,x,R,L,F,W)},J.rect=function(k,x,R,L){D.rect(k,x,R,L),this.__originalRect(k,x,R,L)},J.closePath=function(){D.closePath(),this.__originalClosePath()},J.beginPath=function(){D.beginPath(),this.__originalBeginPath()}}function A(J){if(J._transformStack&&(J._transformStack=[]),!J.mozCurrentTransform){J._originalSave=J.save,J._originalRestore=J.restore,J._originalRotate=J.rotate,J._originalScale=J.scale,J._originalTranslate=J.translate,J._originalTransform=J.transform,J._originalSetTransform=J.setTransform,J._originalResetTransform=J.resetTransform,J._transformMatrix=J._transformMatrix||[1,0,0,1,0,0],J._transformStack=[];try{let D=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(J),"lineWidth");J._setLineWidth=D.set,J._getLineWidth=D.get,Object.defineProperty(J,"lineWidth",{set:function(x){this._setLineWidth(x*g)},get:function(){return this._getLineWidth()}})}catch(D){}Object.defineProperty(J,"mozCurrentTransform",{get:function(){return this._transformMatrix}}),Object.defineProperty(J,"mozCurrentTransformInverse",{get:function(){let[k,x,R,L,F,W]=this._transformMatrix,V=k*L-x*R,Z=x*R-k*L;return[L/V,x/Z,R/Z,k/V,(L*F-R*W)/Z,(x*F-k*W)/V]}}),J.save=function(){let k=this._transformMatrix;this._transformStack.push(k),this._transformMatrix=k.slice(0,6),this._originalSave()},J.restore=function(){this._transformStack.length===0&&(0,i.warn)("Tried to restore a ctx when the stack was already empty.");let k=this._transformStack.pop();k&&(this._transformMatrix=k,this._originalRestore())},J.translate=function(k,x){let R=this._transformMatrix;R[4]=R[0]*k+R[2]*x+R[4],R[5]=R[1]*k+R[3]*x+R[5],this._originalTranslate(k,x)},J.scale=function(k,x){let R=this._transformMatrix;R[0]*=k,R[1]*=k,R[2]*=x,R[3]*=x,this._originalScale(k,x)},J.transform=function(k,x,R,L,F,W){let V=this._transformMatrix;this._transformMatrix=[V[0]*k+V[2]*x,V[1]*k+V[3]*x,V[0]*R+V[2]*L,V[1]*R+V[3]*L,V[0]*F+V[2]*W+V[4],V[1]*F+V[3]*W+V[5]],J._originalTransform(k,x,R,L,F,W)},J.setTransform=function(k,x,R,L,F,W){this._transformMatrix=[k,x,R,L,F,W],J._originalSetTransform(k,x,R,L,F,W)},J.resetTransform=function(){this._transformMatrix=[1,0,0,1,0,0],J._originalResetTransform()},J.rotate=function(k){let x=Math.cos(k),R=Math.sin(k),L=this._transformMatrix;this._transformMatrix=[L[0]*x+L[2]*R,L[1]*x+L[3]*R,L[0]*-R+L[2]*x,L[1]*-R+L[3]*x,L[4],L[5]],this._originalRotate(k)}}}class C{constructor(D){this.canvasFactory=D,this.cache=Object.create(null)}getCanvas(D,k,x,R){let L;return this.cache[D]!==void 0?(L=this.cache[D],this.canvasFactory.reset(L,k,x),L.context.setTransform(1,0,0,1,0,0)):(L=this.canvasFactory.create(k,x),this.cache[D]=L),R&&A(L.context),L}delete(D){delete this.cache[D]}clear(){for(let D in this.cache){let k=this.cache[D];this.canvasFactory.destroy(k),delete this.cache[D]}}}function O(J,D,k,x,R,L,F,W,V,Z){let[ee,ie,ue,de,ye,ke]=J.mozCurrentTransform;if(ie===0&&ue===0){let be=F*ee+ye,se=Math.round(be),Ce=W*de+ke,Re=Math.round(Ce),Y=(F+V)*ee+ye,we=Math.abs(Math.round(Y)-se)||1,Ae=(W+Z)*de+ke,Oe=Math.abs(Math.round(Ae)-Re)||1;return J.setTransform(Math.sign(ee),0,0,Math.sign(de),se,Re),J.drawImage(D,k,x,R,L,0,0,we,Oe),J.setTransform(ee,ie,ue,de,ye,ke),[we,Oe]}if(ee===0&&de===0){let be=W*ue+ye,se=Math.round(be),Ce=F*ie+ke,Re=Math.round(Ce),Y=(W+Z)*ue+ye,we=Math.abs(Math.round(Y)-se)||1,Ae=(F+V)*ie+ke,Oe=Math.abs(Math.round(Ae)-Re)||1;return J.setTransform(0,Math.sign(ie),Math.sign(ue),0,se,Re),J.drawImage(D,k,x,R,L,0,0,Oe,we),J.setTransform(ee,ie,ue,de,ye,ke),[Oe,we]}J.drawImage(D,k,x,R,L,F,W,V,Z);let He=Math.hypot(ee,ie),_e=Math.hypot(ue,de);return[He*V,_e*Z]}function E(J){let{width:D,height:k}=J;if(!p||D>m||k>m)return null;let x=1e3,R=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),L=D+1,F=new Uint8Array(L*(k+1)),W,V,Z,ee=D+7&~7,ie=new Uint8Array(ee*k),ue=0;for(let se of J.data){let Ce=128;for(;Ce>0;)ie[ue++]=se&Ce?0:255,Ce>>=1}let de=0;for(ue=0,ie[ue]!==0&&(F[0]=1,++de),V=1;V<D;V++)ie[ue]!==ie[ue+1]&&(F[V]=ie[ue]?2:1,++de),ue++;for(ie[ue]!==0&&(F[V]=2,++de),W=1;W<k;W++){ue=W*ee,Z=W*L,ie[ue-ee]!==ie[ue]&&(F[Z]=ie[ue]?1:8,++de);let se=(ie[ue]?4:0)+(ie[ue-ee]?8:0);for(V=1;V<D;V++)se=(se>>2)+(ie[ue+1]?4:0)+(ie[ue-ee+1]?8:0),R[se]&&(F[Z+V]=R[se],++de),ue++;if(ie[ue-ee]!==ie[ue]&&(F[Z+V]=ie[ue]?2:4,++de),de>x)return null}for(ue=ee*(k-1),Z=W*L,ie[ue]!==0&&(F[Z]=8,++de),V=1;V<D;V++)ie[ue]!==ie[ue+1]&&(F[Z+V]=ie[ue]?4:8,++de),ue++;if(ie[ue]!==0&&(F[Z+V]=4,++de),de>x)return null;let ye=new Int32Array([0,L,-1,0,-L,0,0,0,1]),ke,He,_e;for(l.isNodeJS?He=[]:ke=new Path2D,W=0;de&&W<=k;W++){let se=W*L,Ce=se+D;for(;se<Ce&&!F[se];)se++;if(se===Ce)continue;ke?ke.moveTo(se%L,W):_e=[se%L,W];let Re=se,Y=F[se];do{let we=ye[Y];do se+=we;while(!F[se]);let Ae=F[se];Ae!==5&&Ae!==10?(Y=Ae,F[se]=0):(Y=Ae&51*Y>>4,F[se]&=Y>>2|Y<<2),ke?ke.lineTo(se%L,se/L|0):_e.push(se%L,se/L|0),F[se]||--de}while(Re!==se);ke||He.push(_e),--W}return ie=null,F=null,function(se){if(se.save(),se.scale(1/D,-1/k),se.translate(0,-k),ke)se.fill(ke);else{se.beginPath();for(let Ce of He){se.moveTo(Ce[0],Ce[1]);for(let Re=2,Y=Ce.length;Re<Y;Re+=2)se.lineTo(Ce[Re],Ce[Re+1])}se.fill()}se.beginPath(),se.restore()}}class T{constructor(D,k){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=i.IDENTITY_MATRIX,this.textMatrixScale=1,this.fontMatrix=i.FONT_IDENTITY_MATRIX,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=i.TextRenderingMode.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps=null,this.startNewPathAndClipBox([0,0,D,k])}clone(){let D=Object.create(this);return D.clipBox=this.clipBox.slice(),D}setCurrentPoint(D,k){this.x=D,this.y=k}updatePathMinMax(D,k,x){[k,x]=i.Util.applyTransform([k,x],D),this.minX=Math.min(this.minX,k),this.minY=Math.min(this.minY,x),this.maxX=Math.max(this.maxX,k),this.maxY=Math.max(this.maxY,x)}updateRectMinMax(D,k){let x=i.Util.applyTransform(k,D),R=i.Util.applyTransform(k.slice(2),D);this.minX=Math.min(this.minX,x[0],R[0]),this.minY=Math.min(this.minY,x[1],R[1]),this.maxX=Math.max(this.maxX,x[0],R[0]),this.maxY=Math.max(this.maxY,x[1],R[1])}updateScalingPathMinMax(D,k){i.Util.scaleMinMax(D,k),this.minX=Math.min(this.minX,k[0]),this.maxX=Math.max(this.maxX,k[1]),this.minY=Math.min(this.minY,k[2]),this.maxY=Math.max(this.maxY,k[3])}updateCurvePathMinMax(D,k,x,R,L,F,W,V,Z,ee){let ie=i.Util.bezierBoundingBox(k,x,R,L,F,W,V,Z);if(ee){ee[0]=Math.min(ee[0],ie[0],ie[2]),ee[1]=Math.max(ee[1],ie[0],ie[2]),ee[2]=Math.min(ee[2],ie[1],ie[3]),ee[3]=Math.max(ee[3],ie[1],ie[3]);return}this.updateRectMinMax(D,ie)}getPathBoundingBox(D=o.PathType.FILL,k=null){let x=[this.minX,this.minY,this.maxX,this.maxY];if(D===o.PathType.STROKE){k||(0,i.unreachable)("Stroke bounding box must include transform.");let R=i.Util.singularValueDecompose2dScale(k),L=R[0]*this.lineWidth/2,F=R[1]*this.lineWidth/2;x[0]-=L,x[1]-=F,x[2]+=L,x[3]+=F}return x}updateClipFromPath(){let D=i.Util.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(D||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(D){this.clipBox=D,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(D=o.PathType.FILL,k=null){return i.Util.intersect(this.clipBox,this.getPathBoundingBox(D,k))}}function I(J,D,k=null){if(typeof ImageData!="undefined"&&D instanceof ImageData){J.putImageData(D,0,0);return}let x=D.height,R=D.width,L=x%f,F=(x-L)/f,W=L===0?F:F+1,V=J.createImageData(R,f),Z=0,ee,ie=D.data,ue=V.data,de,ye,ke,He,_e,be,se,Ce;if(k)switch(k.length){case 1:_e=k[0],be=k[0],se=k[0],Ce=k[0];break;case 4:_e=k[0],be=k[1],se=k[2],Ce=k[3];break}if(D.kind===i.ImageKind.GRAYSCALE_1BPP){let Re=ie.byteLength,Y=new Uint32Array(ue.buffer,0,ue.byteLength>>2),we=Y.length,Ae=R+7>>3,Oe=4294967295,Be=i.FeatureTest.isLittleEndian?4278190080:255;for(Ce&&Ce[0]===255&&Ce[255]===0&&([Oe,Be]=[Be,Oe]),de=0;de<W;de++){for(ke=de<F?f:L,ee=0,ye=0;ye<ke;ye++){let ot=Re-Z,ze=0,Je=ot>Ae?R:ot*8-7,Ge=Je&~7,pe=0,Q=0;for(;ze<Ge;ze+=8)Q=ie[Z++],Y[ee++]=Q&128?Oe:Be,Y[ee++]=Q&64?Oe:Be,Y[ee++]=Q&32?Oe:Be,Y[ee++]=Q&16?Oe:Be,Y[ee++]=Q&8?Oe:Be,Y[ee++]=Q&4?Oe:Be,Y[ee++]=Q&2?Oe:Be,Y[ee++]=Q&1?Oe:Be;for(;ze<Je;ze++)pe===0&&(Q=ie[Z++],pe=128),Y[ee++]=Q&pe?Oe:Be,pe>>=1}for(;ee<we;)Y[ee++]=0;J.putImageData(V,0,de*f)}}else if(D.kind===i.ImageKind.RGBA_32BPP){let Re=!!(_e||be||se);for(ye=0,He=R*f*4,de=0;de<F;de++){if(ue.set(ie.subarray(Z,Z+He)),Z+=He,Re)for(let Y=0;Y<He;Y+=4)_e&&(ue[Y+0]=_e[ue[Y+0]]),be&&(ue[Y+1]=be[ue[Y+1]]),se&&(ue[Y+2]=se[ue[Y+2]]);J.putImageData(V,0,ye),ye+=f}if(de<W){if(He=R*L*4,ue.set(ie.subarray(Z,Z+He)),Re)for(let Y=0;Y<He;Y+=4)_e&&(ue[Y+0]=_e[ue[Y+0]]),be&&(ue[Y+1]=be[ue[Y+1]]),se&&(ue[Y+2]=se[ue[Y+2]]);J.putImageData(V,0,ye)}}else if(D.kind===i.ImageKind.RGB_24BPP){let Re=!!(_e||be||se);for(ke=f,He=R*ke,de=0;de<W;de++){for(de>=F&&(ke=L,He=R*ke),ee=0,ye=He;ye--;)ue[ee++]=ie[Z++],ue[ee++]=ie[Z++],ue[ee++]=ie[Z++],ue[ee++]=255;if(Re)for(let Y=0;Y<ee;Y+=4)_e&&(ue[Y+0]=_e[ue[Y+0]]),be&&(ue[Y+1]=be[ue[Y+1]]),se&&(ue[Y+2]=se[ue[Y+2]]);J.putImageData(V,0,de*f)}}else throw new Error(`bad image kind: ${D.kind}`)}function M(J,D){if(D.bitmap){J.drawImage(D.bitmap,0,0);return}let k=D.height,x=D.width,R=k%f,L=(k-R)/f,F=R===0?L:L+1,W=J.createImageData(x,f),V=0,Z=D.data,ee=W.data;for(let ie=0;ie<F;ie++){let ue=ie<L?f:R;({srcPos:V}=(0,a.applyMaskImageData)({src:Z,srcPos:V,dest:ee,width:x,height:ue})),J.putImageData(W,0,ie*f)}}function j(J,D){let k=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font"];for(let x=0,R=k.length;x<R;x++){let L=k[x];J[L]!==void 0&&(D[L]=J[L])}J.setLineDash!==void 0&&(D.setLineDash(J.getLineDash()),D.lineDashOffset=J.lineDashOffset)}function U(J,D){J.strokeStyle=J.fillStyle=D||"#000000",J.fillRule="nonzero",J.globalAlpha=1,J.lineWidth=1,J.lineCap="butt",J.lineJoin="miter",J.miterLimit=10,J.globalCompositeOperation="source-over",J.font="10px sans-serif",J.setLineDash!==void 0&&(J.setLineDash([]),J.lineDashOffset=0)}function B(J,D,k,x){let R=J.length;for(let L=3;L<R;L+=4){let F=J[L];if(F===0)J[L-3]=D,J[L-2]=k,J[L-1]=x;else if(F<255){let W=255-F;J[L-3]=J[L-3]*F+D*W>>8,J[L-2]=J[L-2]*F+k*W>>8,J[L-1]=J[L-1]*F+x*W>>8}}}function N(J,D,k){let x=J.length,R=1/255;for(let L=3;L<x;L+=4){let F=k?k[J[L]]:J[L];D[L]=D[L]*F*R|0}}function q(J,D,k){let x=J.length;for(let R=3;R<x;R+=4){let L=J[R-3]*77+J[R-2]*152+J[R-1]*28;D[R]=k?D[R]*k[L>>8]>>8:D[R]*L>>16}}function z(J,D,k,x,R,L,F,W,V,Z,ee){let ie=!!L,ue=ie?L[0]:0,de=ie?L[1]:0,ye=ie?L[2]:0,ke;R==="Luminosity"?ke=q:ke=N;let _e=Math.min(x,Math.ceil(1048576/k));for(let be=0;be<x;be+=_e){let se=Math.min(_e,x-be),Ce=J.getImageData(W-Z,be+(V-ee),k,se),Re=D.getImageData(W,be+V,k,se);ie&&B(Ce.data,ue,de,ye),ke(Ce.data,Re.data,F),D.putImageData(Re,W,be+V)}}function ne(J,D,k,x){let R=x[0],L=x[1],F=x[2]-R,W=x[3]-L;F===0||W===0||(z(D.context,k,F,W,D.subtype,D.backdrop,D.transferMap,R,L,D.offsetX,D.offsetY),J.save(),J.globalAlpha=1,J.globalCompositeOperation="source-over",J.setTransform(1,0,0,1,0,0),J.drawImage(k.canvas,0,0),J.restore())}function oe(J,D){let k=i.Util.singularValueDecompose2dScale(J);k[0]=Math.fround(k[0]),k[1]=Math.fround(k[1]);let x=Math.fround((globalThis.devicePixelRatio||1)*u.PixelsPerInch.PDF_TO_CSS_UNITS);return D!==void 0?D:k[0]<=x||k[1]<=x}let ae=["butt","round","square"],te=["miter","round","bevel"],le={},xe={};class fe{constructor(D,k,x,R,L,F,W,V){this.ctx=D,this.current=new T(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=k,this.objs=x,this.canvasFactory=R,this.imageLayer=L,this.groupStack=[],this.processingType3=null,this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=[],this.optionalContentConfig=F,this.cachedCanvases=new C(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=W,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.backgroundColor=V?.background||null,this.foregroundColor=V?.foreground||null,D&&A(D),this._cachedScaleForStroking=null,this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(D,k=null){return typeof D=="string"?D.startsWith("g_")?this.commonObjs.get(D):this.objs.get(D):k}beginDrawing({transform:D,viewport:k,transparency:x=!1,background:R=null}){let L=this.ctx.canvas.width,F=this.ctx.canvas.height,W=R||"#ffffff";if(this.ctx.save(),this.foregroundColor&&this.backgroundColor){this.ctx.fillStyle=this.foregroundColor;let V=this.foregroundColor=this.ctx.fillStyle;this.ctx.fillStyle=this.backgroundColor;let Z=this.backgroundColor=this.ctx.fillStyle,ee=!0,ie=W;if(this.ctx.fillStyle=W,ie=this.ctx.fillStyle,ee=typeof ie=="string"&&/^#[0-9A-Fa-f]{6}$/.test(ie),V==="#000000"&&Z==="#ffffff"||V===Z||!ee)this.foregroundColor=this.backgroundColor=null;else{let ue=parseInt(ie.slice(1),16),de=(ue&&16711680)>>16,ye=(ue&&65280)>>8,ke=ue&&255,He=be=>(be/=255,be<=.03928?be/12.92:((be+.055)/1.055)**2.4),_e=Math.round(.2126*He(de)+.7152*He(ye)+.0722*He(ke));this.selectColor=(be,se,Ce)=>{let Re=.2126*He(be)+.7152*He(se)+.0722*He(Ce);return Math.round(Re)===_e?Z:V}}}if(this.ctx.fillStyle=this.backgroundColor||W,this.ctx.fillRect(0,0,L,F),this.ctx.restore(),x){let V=this.cachedCanvases.getCanvas("transparent",L,F,!0);this.compositeCtx=this.ctx,this.transparentCanvas=V.canvas,this.ctx=V.context,this.ctx.save(),this.ctx.transform.apply(this.ctx,this.compositeCtx.mozCurrentTransform)}this.ctx.save(),U(this.ctx,this.foregroundColor),D&&(this.ctx.transform.apply(this.ctx,D),this.outputScaleX=D[0],this.outputScaleY=D[0]),this.ctx.transform.apply(this.ctx,k.transform),this.viewportScale=k.scale,this.baseTransform=this.ctx.mozCurrentTransform.slice(),this.imageLayer&&this.imageLayer.beginLayout()}executeOperatorList(D,k,x,R){let L=D.argsArray,F=D.fnArray,W=k||0,V=L.length;if(V===W)return W;let Z=V-W>w&&typeof x=="function",ee=Z?Date.now()+b:0,ie=0,ue=this.commonObjs,de=this.objs,ye;for(;;){if(R!==void 0&&W===R.nextBreakPoint)return R.breakIt(W,x),W;if(ye=F[W],ye!==i.OPS.dependency)this[ye].apply(this,L[W]);else for(let ke of L[W]){let He=ke.startsWith("g_")?ue:de;if(!He.has(ke))return He.get(ke,x),W}if(W++,W===V)return W;if(Z&&++ie>w){if(Date.now()>ee)return x(),W;ie=0}}}endDrawing(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(let D of this._cachedBitmapsMap.values()){for(let k of D.values())typeof HTMLCanvasElement!="undefined"&&k instanceof HTMLCanvasElement&&(k.width=k.height=0);D.clear()}this._cachedBitmapsMap.clear(),this.imageLayer&&this.imageLayer.endLayout()}_scaleImage(D,k){let x=D.width,R=D.height,L=Math.max(Math.hypot(k[0],k[1]),1),F=Math.max(Math.hypot(k[2],k[3]),1),W=x,V=R,Z="prescale1",ee,ie;for(;L>2&&W>1||F>2&&V>1;){let ue=W,de=V;L>2&&W>1&&(ue=Math.ceil(W/2),L/=W/ue),F>2&&V>1&&(de=Math.ceil(V/2),F/=V/de),ee=this.cachedCanvases.getCanvas(Z,ue,de,!1),ie=ee.context,ie.clearRect(0,0,ue,de),ie.drawImage(D,0,0,W,V,0,0,ue,de),D=ee.canvas,W=ue,V=de,Z=Z==="prescale1"?"prescale2":"prescale1"}return{img:D,paintWidth:W,paintHeight:V}}_createMaskCanvas(D){let k=this.ctx,{width:x,height:R}=D,L=this.current.fillColor,F=this.current.patternFill,W=k.mozCurrentTransform,V,Z,ee,ie;if((D.bitmap||D.data)&&D.count>1){let we=D.bitmap||D.data.buffer,Ae=W.slice(0,4);Z=JSON.stringify(F?Ae:[Ae,L]),V=this._cachedBitmapsMap.get(we),V||(V=new Map,this._cachedBitmapsMap.set(we,V));let Oe=V.get(Z);if(Oe&&!F){let Be=Math.round(Math.min(W[0],W[2])+W[4]),ot=Math.round(Math.min(W[1],W[3])+W[5]);return{canvas:Oe,offsetX:Be,offsetY:ot}}ee=Oe}ee||(ie=this.cachedCanvases.getCanvas("maskCanvas",x,R,!1),M(ie.context,D));let ue=i.Util.transform(W,[1/x,0,0,-1/R,0,0]);ue=i.Util.transform(ue,[1,0,0,1,0,-R]);let de=i.Util.applyTransform([0,0],ue),ye=i.Util.applyTransform([x,R],ue),ke=i.Util.normalizeRect([de[0],de[1],ye[0],ye[1]]),He=Math.round(ke[2]-ke[0])||1,_e=Math.round(ke[3]-ke[1])||1,be=this.cachedCanvases.getCanvas("fillCanvas",He,_e,!0),se=be.context,Ce=Math.min(de[0],ye[0]),Re=Math.min(de[1],ye[1]);se.translate(-Ce,-Re),se.transform.apply(se,ue),ee||(ee=this._scaleImage(ie.canvas,se.mozCurrentTransformInverse),ee=ee.img,V&&F&&V.set(Z,ee)),se.imageSmoothingEnabled=oe(se.mozCurrentTransform,D.interpolate),O(se,ee,0,0,ee.width,ee.height,0,0,x,R),se.globalCompositeOperation="source-in";let Y=i.Util.transform(se.mozCurrentTransformInverse,[1,0,0,1,-Ce,-Re]);return se.fillStyle=F?L.getPattern(k,this,Y,o.PathType.FILL):L,se.fillRect(0,0,x,R),V&&!F&&(this.cachedCanvases.delete("fillCanvas"),V.set(Z,be.canvas)),{canvas:be.canvas,offsetX:Math.round(Ce),offsetY:Math.round(Re)}}setLineWidth(D){D!==this.current.lineWidth&&(this._cachedScaleForStroking=null),this.current.lineWidth=D,this.ctx.lineWidth=D}setLineCap(D){this.ctx.lineCap=ae[D]}setLineJoin(D){this.ctx.lineJoin=te[D]}setMiterLimit(D){this.ctx.miterLimit=D}setDash(D,k){let x=this.ctx;x.setLineDash!==void 0&&(x.setLineDash(D),x.lineDashOffset=k)}setRenderingIntent(D){}setFlatness(D){}setGState(D){for(let k=0,x=D.length;k<x;k++){let R=D[k],L=R[0],F=R[1];switch(L){case"LW":this.setLineWidth(F);break;case"LC":this.setLineCap(F);break;case"LJ":this.setLineJoin(F);break;case"ML":this.setMiterLimit(F);break;case"D":this.setDash(F[0],F[1]);break;case"RI":this.setRenderingIntent(F);break;case"FL":this.setFlatness(F);break;case"Font":this.setFont(F[0],F[1]);break;case"CA":this.current.strokeAlpha=R[1];break;case"ca":this.current.fillAlpha=R[1],this.ctx.globalAlpha=R[1];break;case"BM":this.ctx.globalCompositeOperation=F;break;case"SMask":this.current.activeSMask=F?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.current.transferMaps=F}}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){let D=this.inSMaskMode;this.current.activeSMask&&!D?this.beginSMaskMode():!this.current.activeSMask&&D&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");let D=this.ctx.canvas.width,k=this.ctx.canvas.height,x="smaskGroupAt"+this.groupLevel,R=this.cachedCanvases.getCanvas(x,D,k,!0);this.suspendedCtx=this.ctx,this.ctx=R.context;let L=this.ctx;L.setTransform.apply(L,this.suspendedCtx.mozCurrentTransform),j(this.suspendedCtx,L),v(L,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),j(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(D){if(!this.current.activeSMask)return;D?(D[0]=Math.floor(D[0]),D[1]=Math.floor(D[1]),D[2]=Math.ceil(D[2]),D[3]=Math.ceil(D[3])):D=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];let k=this.current.activeSMask,x=this.suspendedCtx;ne(x,k,this.ctx,D),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}save(){this.inSMaskMode?(j(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();let D=this.current;this.stateStack.push(D),this.current=D.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),j(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking=null,this._cachedGetSinglePixelWidth=null)}transform(D,k,x,R,L,F){this.ctx.transform(D,k,x,R,L,F),this._cachedScaleForStroking=null,this._cachedGetSinglePixelWidth=null}constructPath(D,k,x){let R=this.ctx,L=this.current,F=L.x,W=L.y,V,Z,ee=R.mozCurrentTransform,ie=ee[0]===0&&ee[3]===0||ee[1]===0&&ee[2]===0,ue=ie?x.slice(0):null;for(let de=0,ye=0,ke=D.length;de<ke;de++)switch(D[de]|0){case i.OPS.rectangle:F=k[ye++],W=k[ye++];let He=k[ye++],_e=k[ye++],be=F+He,se=W+_e;R.moveTo(F,W),He===0||_e===0?R.lineTo(be,se):(R.lineTo(be,W),R.lineTo(be,se),R.lineTo(F,se)),ie||L.updateRectMinMax(ee,[F,W,be,se]),R.closePath();break;case i.OPS.moveTo:F=k[ye++],W=k[ye++],R.moveTo(F,W),ie||L.updatePathMinMax(ee,F,W);break;case i.OPS.lineTo:F=k[ye++],W=k[ye++],R.lineTo(F,W),ie||L.updatePathMinMax(ee,F,W);break;case i.OPS.curveTo:V=F,Z=W,F=k[ye+4],W=k[ye+5],R.bezierCurveTo(k[ye],k[ye+1],k[ye+2],k[ye+3],F,W),L.updateCurvePathMinMax(ee,V,Z,k[ye],k[ye+1],k[ye+2],k[ye+3],F,W,ue),ye+=6;break;case i.OPS.curveTo2:V=F,Z=W,R.bezierCurveTo(F,W,k[ye],k[ye+1],k[ye+2],k[ye+3]),L.updateCurvePathMinMax(ee,V,Z,F,W,k[ye],k[ye+1],k[ye+2],k[ye+3],ue),F=k[ye+2],W=k[ye+3],ye+=4;break;case i.OPS.curveTo3:V=F,Z=W,F=k[ye+2],W=k[ye+3],R.bezierCurveTo(k[ye],k[ye+1],F,W,F,W),L.updateCurvePathMinMax(ee,V,Z,k[ye],k[ye+1],F,W,F,W,ue),ye+=4;break;case i.OPS.closePath:R.closePath();break}ie&&L.updateScalingPathMinMax(ee,ue),L.setCurrentPoint(F,W)}closePath(){this.ctx.closePath()}stroke(D){D=typeof D!="undefined"?D:!0;let k=this.ctx,x=this.current.strokeColor;k.globalAlpha=this.current.strokeAlpha,this.contentVisible&&(typeof x=="object"&&x?.getPattern?(k.save(),k.strokeStyle=x.getPattern(k,this,k.mozCurrentTransformInverse,o.PathType.STROKE),this.rescaleAndStroke(!1),k.restore()):this.rescaleAndStroke(!0)),D&&this.consumePath(this.current.getClippedPathBoundingBox()),k.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(D){D=typeof D!="undefined"?D:!0;let k=this.ctx,x=this.current.fillColor,R=this.current.patternFill,L=!1;R&&(k.save(),k.fillStyle=x.getPattern(k,this,k.mozCurrentTransformInverse,o.PathType.FILL),L=!0);let F=this.current.getClippedPathBoundingBox();this.contentVisible&&F!==null&&(this.pendingEOFill?(k.fill("evenodd"),this.pendingEOFill=!1):k.fill()),L&&k.restore(),D&&this.consumePath(F)}eoFill(){this.pendingEOFill=!0,this.fill()}fillStroke(){this.fill(!1),this.stroke(!1),this.consumePath()}eoFillStroke(){this.pendingEOFill=!0,this.fillStroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()}endPath(){this.consumePath()}clip(){this.pendingClip=le}eoClip(){this.pendingClip=xe}beginText(){this.current.textMatrix=i.IDENTITY_MATRIX,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}endText(){let D=this.pendingTextPaths,k=this.ctx;if(D===void 0){k.beginPath();return}k.save(),k.beginPath();for(let x=0;x<D.length;x++){let R=D[x];k.setTransform.apply(k,R.transform),k.translate(R.x,R.y),R.addToPath(k,R.fontSize)}k.restore(),k.clip(),k.beginPath(),delete this.pendingTextPaths}setCharSpacing(D){this.current.charSpacing=D}setWordSpacing(D){this.current.wordSpacing=D}setHScale(D){this.current.textHScale=D/100}setLeading(D){this.current.leading=-D}setFont(D,k){let x=this.commonObjs.get(D),R=this.current;if(!x)throw new Error(`Can't find font for ${D}`);if(R.fontMatrix=x.fontMatrix||i.FONT_IDENTITY_MATRIX,(R.fontMatrix[0]===0||R.fontMatrix[3]===0)&&(0,i.warn)("Invalid font matrix for font "+D),k<0?(k=-k,R.fontDirection=-1):R.fontDirection=1,this.current.font=x,this.current.fontSize=k,x.isType3Font)return;let L=x.loadedName||"sans-serif",F="normal";x.black?F="900":x.bold&&(F="bold");let W=x.italic?"italic":"normal",V=`"${L}", ${x.fallbackName}`,Z=k;k<d?Z=d:k>h&&(Z=h),this.current.fontSizeScale=k/Z,this.ctx.font=`${W} ${F} ${Z}px ${V}`}setTextRenderingMode(D){this.current.textRenderingMode=D}setTextRise(D){this.current.textRise=D}moveText(D,k){this.current.x=this.current.lineX+=D,this.current.y=this.current.lineY+=k}setLeadingMoveText(D,k){this.setLeading(-k),this.moveText(D,k)}setTextMatrix(D,k,x,R,L,F){this.current.textMatrix=[D,k,x,R,L,F],this.current.textMatrixScale=Math.hypot(D,k),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(D,k,x,R){let L=this.ctx,F=this.current,W=F.font,V=F.textRenderingMode,Z=F.fontSize/F.fontSizeScale,ee=V&i.TextRenderingMode.FILL_STROKE_MASK,ie=!!(V&i.TextRenderingMode.ADD_TO_PATH_FLAG),ue=F.patternFill&&!W.missingFile,de;(W.disableFontFace||ie||ue)&&(de=W.getPathGenerator(this.commonObjs,D)),W.disableFontFace||ue?(L.save(),L.translate(k,x),L.beginPath(),de(L,Z),R&&L.setTransform.apply(L,R),(ee===i.TextRenderingMode.FILL||ee===i.TextRenderingMode.FILL_STROKE)&&L.fill(),(ee===i.TextRenderingMode.STROKE||ee===i.TextRenderingMode.FILL_STROKE)&&L.stroke(),L.restore()):((ee===i.TextRenderingMode.FILL||ee===i.TextRenderingMode.FILL_STROKE)&&L.fillText(D,k,x),(ee===i.TextRenderingMode.STROKE||ee===i.TextRenderingMode.FILL_STROKE)&&L.strokeText(D,k,x)),ie&&(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:L.mozCurrentTransform,x:k,y:x,fontSize:Z,addToPath:de})}get isFontSubpixelAAEnabled(){let{context:D}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10,!1);D.scale(1.5,1),D.fillText("I",0,10);let k=D.getImageData(0,0,10,10).data,x=!1;for(let R=3;R<k.length;R+=4)if(k[R]>0&&k[R]<255){x=!0;break}return(0,i.shadow)(this,"isFontSubpixelAAEnabled",x)}showText(D){let k=this.current,x=k.font;if(x.isType3Font)return this.showType3Text(D);let R=k.fontSize;if(R===0)return;let L=this.ctx,F=k.fontSizeScale,W=k.charSpacing,V=k.wordSpacing,Z=k.fontDirection,ee=k.textHScale*Z,ie=D.length,ue=x.vertical,de=ue?1:-1,ye=x.defaultVMetrics,ke=R*k.fontMatrix[0],He=k.textRenderingMode===i.TextRenderingMode.FILL&&!x.disableFontFace&&!k.patternFill;L.save(),L.transform.apply(L,k.textMatrix),L.translate(k.x,k.y+k.textRise),Z>0?L.scale(ee,-1):L.scale(ee,1);let _e;if(k.patternFill){L.save();let Y=k.fillColor.getPattern(L,this,L.mozCurrentTransformInverse,o.PathType.FILL);_e=L.mozCurrentTransform,L.restore(),L.fillStyle=Y}let be=k.lineWidth,se=k.textMatrixScale;if(se===0||be===0){let Y=k.textRenderingMode&i.TextRenderingMode.FILL_STROKE_MASK;(Y===i.TextRenderingMode.STROKE||Y===i.TextRenderingMode.FILL_STROKE)&&(be=this.getSinglePixelWidth())}else be/=se;F!==1&&(L.scale(F,F),be/=F),L.lineWidth=be;let Ce=0,Re;for(Re=0;Re<ie;++Re){let Y=D[Re];if(typeof Y=="number"){Ce+=de*Y*R/1e3;continue}let we=!1,Ae=(Y.isSpace?V:0)+W,Oe=Y.fontChar,Be=Y.accent,ot,ze,Je=Y.width;if(ue){let pe=Y.vmetric||ye,Q=-(Y.vmetric?pe[1]:Je*.5)*ke,ce=pe[2]*ke;Je=pe?-pe[0]:Je,ot=Q/F,ze=(Ce+ce)/F}else ot=Ce/F,ze=0;if(x.remeasure&&Je>0){let pe=L.measureText(Oe).width*1e3/R*F;if(Je<pe&&this.isFontSubpixelAAEnabled){let Q=Je/pe;we=!0,L.save(),L.scale(Q,1),ot/=Q}else Je!==pe&&(ot+=(Je-pe)/2e3*R/F)}if(this.contentVisible&&(Y.isInFont||x.missingFile)){if(He&&!Be)L.fillText(Oe,ot,ze);else if(this.paintChar(Oe,ot,ze,_e),Be){let pe=ot+R*Be.offset.x/F,Q=ze-R*Be.offset.y/F;this.paintChar(Be.fontChar,pe,Q,_e)}}let Ge;ue?Ge=Je*ke-Ae*Z:Ge=Je*ke+Ae*Z,Ce+=Ge,we&&L.restore()}ue?k.y-=Ce:k.x+=Ce*ee,L.restore(),this.compose()}showType3Text(D){let k=this.ctx,x=this.current,R=x.font,L=x.fontSize,F=x.fontDirection,W=R.vertical?1:-1,V=x.charSpacing,Z=x.wordSpacing,ee=x.textHScale*F,ie=x.fontMatrix||i.FONT_IDENTITY_MATRIX,ue=D.length,de=x.textRenderingMode===i.TextRenderingMode.INVISIBLE,ye,ke,He,_e;if(!(de||L===0)){for(this._cachedScaleForStroking=null,this._cachedGetSinglePixelWidth=null,k.save(),k.transform.apply(k,x.textMatrix),k.translate(x.x,x.y),k.scale(ee,F),ye=0;ye<ue;++ye){if(ke=D[ye],typeof ke=="number"){_e=W*ke*L/1e3,this.ctx.translate(_e,0),x.x+=_e*ee;continue}let be=(ke.isSpace?Z:0)+V,se=R.charProcOperatorList[ke.operatorListId];if(!se){(0,i.warn)(`Type3 character "${ke.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=ke,this.save(),k.scale(L,L),k.transform.apply(k,ie),this.executeOperatorList(se),this.restore()),He=i.Util.applyTransform([ke.width,0],ie)[0]*L+be,k.translate(He,0),x.x+=He*ee}k.restore(),this.processingType3=null}}setCharWidth(D,k){}setCharWidthAndBounds(D,k,x,R,L,F){this.ctx.rect(x,R,L-x,F-R),this.ctx.clip(),this.endPath()}getColorN_Pattern(D){let k;if(D[0]==="TilingPattern"){let x=D[1],R=this.baseTransform||this.ctx.mozCurrentTransform.slice(),L={createCanvasGraphics:F=>new fe(F,this.commonObjs,this.objs,this.canvasFactory)};k=new o.TilingPattern(D,x,this.ctx,L,R)}else k=this._getPattern(D[1],D[2]);return k}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(D,k,x){let R=this.selectColor?.(D,k,x)||i.Util.makeHexColor(D,k,x);this.ctx.strokeStyle=R,this.current.strokeColor=R}setFillRGBColor(D,k,x){let R=this.selectColor?.(D,k,x)||i.Util.makeHexColor(D,k,x);this.ctx.fillStyle=R,this.current.fillColor=R,this.current.patternFill=!1}_getPattern(D,k=null){let x;return this.cachedPatterns.has(D)?x=this.cachedPatterns.get(D):(x=(0,o.getShadingPattern)(this.objs.get(D)),this.cachedPatterns.set(D,x)),k&&(x.matrix=k),x}shadingFill(D){if(!this.contentVisible)return;let k=this.ctx;this.save();let x=this._getPattern(D);k.fillStyle=x.getPattern(k,this,k.mozCurrentTransformInverse,o.PathType.SHADING);let R=k.mozCurrentTransformInverse;if(R){let L=k.canvas,F=L.width,W=L.height,V=i.Util.applyTransform([0,0],R),Z=i.Util.applyTransform([0,W],R),ee=i.Util.applyTransform([F,0],R),ie=i.Util.applyTransform([F,W],R),ue=Math.min(V[0],Z[0],ee[0],ie[0]),de=Math.min(V[1],Z[1],ee[1],ie[1]),ye=Math.max(V[0],Z[0],ee[0],ie[0]),ke=Math.max(V[1],Z[1],ee[1],ie[1]);this.ctx.fillRect(ue,de,ye-ue,ke-de)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){(0,i.unreachable)("Should not call beginInlineImage")}beginImageData(){(0,i.unreachable)("Should not call beginImageData")}paintFormXObjectBegin(D,k){if(!!this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),Array.isArray(D)&&D.length===6&&this.transform.apply(this,D),this.baseTransform=this.ctx.mozCurrentTransform,k)){let x=k[2]-k[0],R=k[3]-k[1];this.ctx.rect(k[0],k[1],x,R),this.current.updateRectMinMax(this.ctx.mozCurrentTransform,k),this.clip(),this.endPath()}}paintFormXObjectEnd(){!this.contentVisible||(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(D){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);let k=this.ctx;D.isolated||(0,i.info)("TODO: Support non-isolated groups."),D.knockout&&(0,i.warn)("Knockout groups not supported.");let x=k.mozCurrentTransform;if(D.matrix&&k.transform.apply(k,D.matrix),!D.bbox)throw new Error("Bounding box is required.");let R=i.Util.getAxialAlignedBoundingBox(D.bbox,k.mozCurrentTransform),L=[0,0,k.canvas.width,k.canvas.height];R=i.Util.intersect(R,L)||[0,0,0,0];let F=Math.floor(R[0]),W=Math.floor(R[1]),V=Math.max(Math.ceil(R[2])-F,1),Z=Math.max(Math.ceil(R[3])-W,1),ee=1,ie=1;V>y&&(ee=V/y,V=y),Z>y&&(ie=Z/y,Z=y),this.current.startNewPathAndClipBox([0,0,V,Z]);let ue="groupAt"+this.groupLevel;D.smask&&(ue+="_smask_"+this.smaskCounter++%2);let de=this.cachedCanvases.getCanvas(ue,V,Z,!0),ye=de.context;ye.scale(1/ee,1/ie),ye.translate(-F,-W),ye.transform.apply(ye,x),D.smask?this.smaskStack.push({canvas:de.canvas,context:ye,offsetX:F,offsetY:W,scaleX:ee,scaleY:ie,subtype:D.smask.subtype,backdrop:D.smask.backdrop,transferMap:D.smask.transferMap||null,startTransformInverse:null}):(k.setTransform(1,0,0,1,0,0),k.translate(F,W),k.scale(ee,ie),k.save()),j(k,ye),this.ctx=ye,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(k),this.groupLevel++}endGroup(D){if(!this.contentVisible)return;this.groupLevel--;let k=this.ctx,x=this.groupStack.pop();if(this.ctx=x,this.ctx.imageSmoothingEnabled=!1,D.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();let R=this.ctx.mozCurrentTransform;this.restore(),this.ctx.save(),this.ctx.setTransform.apply(this.ctx,R);let L=i.Util.getAxialAlignedBoundingBox([0,0,k.canvas.width,k.canvas.height],R);this.ctx.drawImage(k.canvas,0,0),this.ctx.restore(),this.compose(L)}}beginAnnotations(){this.save(),this.baseTransform&&this.ctx.setTransform.apply(this.ctx,this.baseTransform)}endAnnotations(){this.restore()}beginAnnotation(D,k,x,R,L){if(this.save(),Array.isArray(k)&&k.length===4){let F=k[2]-k[0],W=k[3]-k[1];if(L&&this.annotationCanvasMap){x=x.slice(),x[4]-=k[0],x[5]-=k[1],k=k.slice(),k[0]=k[1]=0,k[2]=F,k[3]=W;let[V,Z]=i.Util.singularValueDecompose2dScale(this.ctx.mozCurrentTransform),{viewportScale:ee}=this,ie=Math.ceil(F*this.outputScaleX*ee),ue=Math.ceil(W*this.outputScaleY*ee);this.annotationCanvas=this.canvasFactory.create(ie,ue);let{canvas:de,context:ye}=this.annotationCanvas,ke=`var(--zoom-factor) * ${u.PixelsPerInch.PDF_TO_CSS_UNITS}`;de.style.width=`calc(${F}px * ${ke})`,de.style.height=`calc(${W}px * ${ke})`,this.annotationCanvasMap.set(D,de),this.annotationCanvas.savedCtx=this.ctx,this.ctx=ye,this.ctx.setTransform(V,0,0,-Z,0,W*Z),A(this.ctx),U(this.ctx,this.foregroundColor)}else U(this.ctx,this.foregroundColor),this.ctx.rect(k[0],k[1],F,W),this.ctx.clip(),this.endPath()}this.current=new T(this.ctx.canvas.width,this.ctx.canvas.height),this.transform.apply(this,x),this.transform.apply(this,R)}endAnnotation(){this.annotationCanvas&&(this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas),this.restore()}paintImageMaskXObject(D){if(!this.contentVisible)return;let k=D.count;D=this.getObject(D.data,D),D.count=k;let x=this.ctx,R=this.processingType3;if(R&&(R.compiled===void 0&&(R.compiled=E(D)),R.compiled)){R.compiled(x);return}let L=this._createMaskCanvas(D),F=L.canvas;x.save(),x.setTransform(1,0,0,1,0,0),x.drawImage(F,L.offsetX,L.offsetY),x.restore(),this.compose()}paintImageMaskXObjectRepeat(D,k,x=0,R=0,L,F){if(!this.contentVisible)return;D=this.getObject(D.data,D);let W=this.ctx;W.save();let V=W.mozCurrentTransform;W.transform(k,x,R,L,0,0);let Z=this._createMaskCanvas(D);W.setTransform(1,0,0,1,0,0);for(let ee=0,ie=F.length;ee<ie;ee+=2){let ue=i.Util.transform(V,[k,x,R,L,F[ee],F[ee+1]]),[de,ye]=i.Util.applyTransform([0,0],ue);W.drawImage(Z.canvas,de,ye)}W.restore(),this.compose()}paintImageMaskXObjectGroup(D){if(!this.contentVisible)return;let k=this.ctx,x=this.current.fillColor,R=this.current.patternFill;for(let L=0,F=D.length;L<F;L++){let W=D[L],V=W.width,Z=W.height,ee=this.cachedCanvases.getCanvas("maskCanvas",V,Z,!1),ie=ee.context;ie.save(),M(ie,W),ie.globalCompositeOperation="source-in",ie.fillStyle=R?x.getPattern(ie,this,k.mozCurrentTransformInverse,o.PathType.FILL):x,ie.fillRect(0,0,V,Z),ie.restore(),k.save(),k.transform.apply(k,W.transform),k.scale(1,-1),O(k,ee.canvas,0,0,V,Z,0,-1,1,1),k.restore()}this.compose()}paintImageXObject(D){if(!this.contentVisible)return;let k=this.getObject(D);if(!k){(0,i.warn)("Dependent image isn't ready yet");return}this.paintInlineImageXObject(k)}paintImageXObjectRepeat(D,k,x,R){if(!this.contentVisible)return;let L=this.getObject(D);if(!L){(0,i.warn)("Dependent image isn't ready yet");return}let F=L.width,W=L.height,V=[];for(let Z=0,ee=R.length;Z<ee;Z+=2)V.push({transform:[k,0,0,x,R[Z],R[Z+1]],x:0,y:0,w:F,h:W});this.paintInlineImageXObjectGroup(L,V)}paintInlineImageXObject(D){if(!this.contentVisible)return;let k=D.width,x=D.height,R=this.ctx;this.save(),R.scale(1/k,-1/x);let L;if(typeof HTMLElement=="function"&&D instanceof HTMLElement||!D.data)L=D;else{let Z=this.cachedCanvases.getCanvas("inlineImage",k,x,!1),ee=Z.context;I(ee,D,this.current.transferMaps),L=Z.canvas}let F=this._scaleImage(L,R.mozCurrentTransformInverse);R.imageSmoothingEnabled=oe(R.mozCurrentTransform,D.interpolate);let[W,V]=O(R,F.img,0,0,F.paintWidth,F.paintHeight,0,-x,k,x);if(this.imageLayer){let Z=this.getCanvasPosition(0,-x);this.imageLayer.appendImage({imgData:D,left:Z[0],top:Z[1],width:W,height:V})}this.compose(),this.restore()}paintInlineImageXObjectGroup(D,k){if(!this.contentVisible)return;let x=this.ctx,R=D.width,L=D.height,F=this.cachedCanvases.getCanvas("inlineImage",R,L,!1),W=F.context;I(W,D,this.current.transferMaps);for(let V=0,Z=k.length;V<Z;V++){let ee=k[V];if(x.save(),x.transform.apply(x,ee.transform),x.scale(1,-1),O(x,F.canvas,ee.x,ee.y,ee.w,ee.h,0,-1,1,1),this.imageLayer){let ie=this.getCanvasPosition(ee.x,ee.y);this.imageLayer.appendImage({imgData:D,left:ie[0],top:ie[1],width:R,height:L})}x.restore()}this.compose()}paintSolidColorImageMask(){!this.contentVisible||(this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(D){}markPointProps(D,k){}beginMarkedContent(D){this.markedContentStack.push({visible:!0})}beginMarkedContentProps(D,k){D==="OC"?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(k)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(){this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(){}endCompat(){}consumePath(D){let k=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(D);let x=this.ctx;this.pendingClip&&(k||(this.pendingClip===xe?x.clip("evenodd"):x.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),x.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){let D=this.ctx.mozCurrentTransform;if(D[1]===0&&D[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(D[0]),Math.abs(D[3]));else{let k=Math.abs(D[0]*D[3]-D[2]*D[1]),x=Math.hypot(D[0],D[2]),R=Math.hypot(D[1],D[3]);this._cachedGetSinglePixelWidth=Math.max(x,R)/k}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(!this._cachedScaleForStroking){let{lineWidth:D}=this.current,k=this.ctx.mozCurrentTransform,x,R;if(k[1]===0&&k[2]===0){let L=Math.abs(k[0]),F=Math.abs(k[3]);if(D===0)x=1/L,R=1/F;else{let W=L*D,V=F*D;x=W<1?1/W:1,R=V<1?1/V:1}}else{let L=Math.abs(k[0]*k[3]-k[2]*k[1]),F=Math.hypot(k[0],k[1]),W=Math.hypot(k[2],k[3]);if(D===0)x=W/L,R=F/L;else{let V=D*L;x=W>V?W/V:1,R=F>V?F/V:1}}this._cachedScaleForStroking=[x,R]}return this._cachedScaleForStroking}rescaleAndStroke(D){let{ctx:k}=this,{lineWidth:x}=this.current,[R,L]=this.getScaleForStroking();if(k.lineWidth=x||1,R===1&&L===1){k.stroke();return}let F,W,V;D&&(F=k.mozCurrentTransform.slice(),W=k.getLineDash().slice(),V=k.lineDashOffset),k.scale(R,L);let Z=Math.max(R,L);k.setLineDash(k.getLineDash().map(ee=>ee/Z)),k.lineDashOffset/=Z,k.stroke(),D&&(k.setTransform(...F),k.setLineDash(W),k.lineDashOffset=V)}getCanvasPosition(D,k){let x=this.ctx.mozCurrentTransform;return[x[0]*D+x[2]*k+x[4],x[1]*D+x[3]*k+x[5]]}isContentVisible(){for(let D=this.markedContentStack.length-1;D>=0;D--)if(!this.markedContentStack[D].visible)return!1;return!0}}t.CanvasGraphics=fe;for(let J in i.OPS)fe.prototype[J]!==void 0&&(fe.prototype[i.OPS[J]]=fe.prototype[J])},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TilingPattern=t.PathType=void 0,t.getShadingPattern=p;var i=n(1),o=n(3);let a={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};t.PathType=a;function l(g,v){if(!v||o.isNodeJS)return;let A=v[2]-v[0],C=v[3]-v[1],O=new Path2D;O.rect(v[0],v[1],A,C),g.clip(O)}class u{constructor(){this.constructor===u&&(0,i.unreachable)("Cannot initialize BaseShadingPattern.")}getPattern(){(0,i.unreachable)("Abstract method `getPattern` called.")}}class d extends u{constructor(v){super();this._type=v[1],this._bbox=v[2],this._colorStops=v[3],this._p0=v[4],this._p1=v[5],this._r0=v[6],this._r1=v[7],this.matrix=null}_createGradient(v){let A;this._type==="axial"?A=v.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(A=v.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(let C of this._colorStops)A.addColorStop(C[0],C[1]);return A}getPattern(v,A,C,O){let E;if(O===a.STROKE||O===a.FILL){let T=A.current.getClippedPathBoundingBox(O,v.mozCurrentTransform)||[0,0,0,0],I=Math.ceil(T[2]-T[0])||1,M=Math.ceil(T[3]-T[1])||1,j=A.cachedCanvases.getCanvas("pattern",I,M,!0),U=j.context;U.clearRect(0,0,U.canvas.width,U.canvas.height),U.beginPath(),U.rect(0,0,U.canvas.width,U.canvas.height),U.translate(-T[0],-T[1]),C=i.Util.transform(C,[1,0,0,1,T[0],T[1]]),U.transform.apply(U,A.baseTransform),this.matrix&&U.transform.apply(U,this.matrix),l(U,this._bbox),U.fillStyle=this._createGradient(U),U.fill(),E=v.createPattern(j.canvas,"no-repeat");let B=new DOMMatrix(C);try{E.setTransform(B)}catch(N){(0,i.warn)(`RadialAxialShadingPattern.getPattern: "${N?.message}".`)}}else l(v,this._bbox),E=this._createGradient(v);return E}}function h(g,v,A,C,O,E,T,I){let M=v.coords,j=v.colors,U=g.data,B=g.width*4,N;M[A+1]>M[C+1]&&(N=A,A=C,C=N,N=E,E=T,T=N),M[C+1]>M[O+1]&&(N=C,C=O,O=N,N=T,T=I,I=N),M[A+1]>M[C+1]&&(N=A,A=C,C=N,N=E,E=T,T=N);let q=(M[A]+v.offsetX)*v.scaleX,z=(M[A+1]+v.offsetY)*v.scaleY,ne=(M[C]+v.offsetX)*v.scaleX,oe=(M[C+1]+v.offsetY)*v.scaleY,ae=(M[O]+v.offsetX)*v.scaleX,te=(M[O+1]+v.offsetY)*v.scaleY;if(z>=te)return;let le=j[E],xe=j[E+1],fe=j[E+2],J=j[T],D=j[T+1],k=j[T+2],x=j[I],R=j[I+1],L=j[I+2],F=Math.round(z),W=Math.round(te),V,Z,ee,ie,ue,de,ye,ke;for(let He=F;He<=W;He++){if(He<oe){let Re;He<z?Re=0:Re=(z-He)/(z-oe),V=q-(q-ne)*Re,Z=le-(le-J)*Re,ee=xe-(xe-D)*Re,ie=fe-(fe-k)*Re}else{let Re;He>te?Re=1:oe===te?Re=0:Re=(oe-He)/(oe-te),V=ne-(ne-ae)*Re,Z=J-(J-x)*Re,ee=D-(D-R)*Re,ie=k-(k-L)*Re}let _e;He<z?_e=0:He>te?_e=1:_e=(z-He)/(z-te),ue=q-(q-ae)*_e,de=le-(le-x)*_e,ye=xe-(xe-R)*_e,ke=fe-(fe-L)*_e;let be=Math.round(Math.min(V,ue)),se=Math.round(Math.max(V,ue)),Ce=B*He+be*4;for(let Re=be;Re<=se;Re++)_e=(V-Re)/(V-ue),_e<0?_e=0:_e>1&&(_e=1),U[Ce++]=Z-(Z-de)*_e|0,U[Ce++]=ee-(ee-ye)*_e|0,U[Ce++]=ie-(ie-ke)*_e|0,U[Ce++]=255}}function y(g,v,A){let C=v.coords,O=v.colors,E,T;switch(v.type){case"lattice":let I=v.verticesPerRow,M=Math.floor(C.length/I)-1,j=I-1;for(E=0;E<M;E++){let U=E*I;for(let B=0;B<j;B++,U++)h(g,A,C[U],C[U+1],C[U+I],O[U],O[U+1],O[U+I]),h(g,A,C[U+I+1],C[U+1],C[U+I],O[U+I+1],O[U+1],O[U+I])}break;case"triangles":for(E=0,T=C.length;E<T;E+=3)h(g,A,C[E],C[E+1],C[E+2],O[E],O[E+1],O[E+2]);break;default:throw new Error("illegal figure")}}class b extends u{constructor(v){super();this._coords=v[2],this._colors=v[3],this._figures=v[4],this._bounds=v[5],this._bbox=v[7],this._background=v[8],this.matrix=null}_createMeshCanvas(v,A,C){let O=1.1,E=3e3,T=2,I=Math.floor(this._bounds[0]),M=Math.floor(this._bounds[1]),j=Math.ceil(this._bounds[2])-I,U=Math.ceil(this._bounds[3])-M,B=Math.min(Math.ceil(Math.abs(j*v[0]*O)),E),N=Math.min(Math.ceil(Math.abs(U*v[1]*O)),E),q=j/B,z=U/N,ne={coords:this._coords,colors:this._colors,offsetX:-I,offsetY:-M,scaleX:1/q,scaleY:1/z},oe=B+T*2,ae=N+T*2,te=C.getCanvas("mesh",oe,ae,!1),le=te.context,xe=le.createImageData(B,N);if(A){let J=xe.data;for(let D=0,k=J.length;D<k;D+=4)J[D]=A[0],J[D+1]=A[1],J[D+2]=A[2],J[D+3]=255}for(let J of this._figures)y(xe,J,ne);return le.putImageData(xe,T,T),{canvas:te.canvas,offsetX:I-T*q,offsetY:M-T*z,scaleX:q,scaleY:z}}getPattern(v,A,C,O){l(v,this._bbox);let E;if(O===a.SHADING)E=i.Util.singularValueDecompose2dScale(v.mozCurrentTransform);else if(E=i.Util.singularValueDecompose2dScale(A.baseTransform),this.matrix){let I=i.Util.singularValueDecompose2dScale(this.matrix);E=[E[0]*I[0],E[1]*I[1]]}let T=this._createMeshCanvas(E,O===a.SHADING?null:this._background,A.cachedCanvases);return O!==a.SHADING&&(v.setTransform.apply(v,A.baseTransform),this.matrix&&v.transform.apply(v,this.matrix)),v.translate(T.offsetX,T.offsetY),v.scale(T.scaleX,T.scaleY),v.createPattern(T.canvas,"no-repeat")}}class w extends u{getPattern(){return"hotpink"}}function p(g){switch(g[0]){case"RadialAxial":return new d(g);case"Mesh":return new b(g);case"Dummy":return new w}throw new Error(`Unknown IR type: ${g[0]}`)}let m={COLORED:1,UNCOLORED:2};class f{static get MAX_PATTERN_SIZE(){return(0,i.shadow)(this,"MAX_PATTERN_SIZE",3e3)}constructor(v,A,C,O,E){this.operatorList=v[2],this.matrix=v[3]||[1,0,0,1,0,0],this.bbox=v[4],this.xstep=v[5],this.ystep=v[6],this.paintType=v[7],this.tilingType=v[8],this.color=A,this.ctx=C,this.canvasGraphicsFactory=O,this.baseTransform=E}createPatternCanvas(v){let A=this.operatorList,C=this.bbox,O=this.xstep,E=this.ystep,T=this.paintType,I=this.tilingType,M=this.color,j=this.canvasGraphicsFactory;(0,i.info)("TilingType: "+I);let U=C[0],B=C[1],N=C[2],q=C[3],z=i.Util.singularValueDecompose2dScale(this.matrix),ne=i.Util.singularValueDecompose2dScale(this.baseTransform),oe=[z[0]*ne[0],z[1]*ne[1]],ae=this.getSizeAndScale(O,this.ctx.canvas.width,oe[0]),te=this.getSizeAndScale(E,this.ctx.canvas.height,oe[1]),le=v.cachedCanvases.getCanvas("pattern",ae.size,te.size,!0),xe=le.context,fe=j.createCanvasGraphics(xe);fe.groupLevel=v.groupLevel,this.setFillAndStrokeStyleToContext(fe,T,M);let J=U,D=B,k=N,x=q;return U<0&&(J=0,k+=Math.abs(U)),B<0&&(D=0,x+=Math.abs(B)),xe.translate(-(ae.scale*J),-(te.scale*D)),fe.transform(ae.scale,0,0,te.scale,0,0),xe.save(),this.clipBbox(fe,J,D,k,x),fe.baseTransform=fe.ctx.mozCurrentTransform.slice(),fe.executeOperatorList(A),fe.endDrawing(),{canvas:le.canvas,scaleX:ae.scale,scaleY:te.scale,offsetX:J,offsetY:D}}getSizeAndScale(v,A,C){v=Math.abs(v);let O=Math.max(f.MAX_PATTERN_SIZE,A),E=Math.ceil(v*C);return E>=O?E=O:C=E/v,{scale:C,size:E}}clipBbox(v,A,C,O,E){let T=O-A,I=E-C;v.ctx.rect(A,C,T,I),v.current.updateRectMinMax(v.ctx.mozCurrentTransform,[A,C,O,E]),v.clip(),v.endPath()}setFillAndStrokeStyleToContext(v,A,C){let O=v.ctx,E=v.current;switch(A){case m.COLORED:let T=this.ctx;O.fillStyle=T.fillStyle,O.strokeStyle=T.strokeStyle,E.fillColor=T.fillStyle,E.strokeColor=T.strokeStyle;break;case m.UNCOLORED:let I=i.Util.makeHexColor(C[0],C[1],C[2]);O.fillStyle=I,O.strokeStyle=I,E.fillColor=I,E.strokeColor=I;break;default:throw new i.FormatError(`Unsupported paint type: ${A}`)}}getPattern(v,A,C,O){let E=C;O!==a.SHADING&&(E=i.Util.transform(E,A.baseTransform),this.matrix&&(E=i.Util.transform(E,this.matrix)));let T=this.createPatternCanvas(A),I=new DOMMatrix(E);I=I.translate(T.offsetX,T.offsetY),I=I.scale(1/T.scaleX,1/T.scaleY);let M=v.createPattern(T.canvas,"repeat");try{M.setTransform(I)}catch(j){(0,i.warn)(`TilingPattern.getPattern: "${j?.message}".`)}return M}}t.TilingPattern=f},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.applyMaskImageData=o;var i=n(1);function o({src:a,srcPos:l=0,dest:u,destPos:d=0,width:h,height:y,inverseDecode:b=!1}){let w=i.FeatureTest.isLittleEndian?4278190080:255,[p,m]=b?[0,w]:[w,0],f=h>>3,g=h&7,v=a.length;u=new Uint32Array(u.buffer);for(let A=0;A<y;A++){for(let O=l+f;l<O;l++){let E=l<v?a[l]:255;u[d++]=E&128?m:p,u[d++]=E&64?m:p,u[d++]=E&32?m:p,u[d++]=E&16?m:p,u[d++]=E&8?m:p,u[d++]=E&4?m:p,u[d++]=E&2?m:p,u[d++]=E&1?m:p}if(g===0)continue;let C=l<v?a[l++]:255;for(let O=0;O<g;O++)u[d++]=C&1<<7-O?m:p}return{srcPos:l,destPos:d}}},(r,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.GlobalWorkerOptions=void 0;let n=Object.create(null);t.GlobalWorkerOptions=n,n.workerPort=n.workerPort===void 0?null:n.workerPort,n.workerSrc=n.workerSrc===void 0?"":n.workerSrc},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MessageHandler=void 0;var i=n(1);let o={UNKNOWN:0,DATA:1,ERROR:2},a={UNKNOWN:0,CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function l(d){switch(d instanceof Error||typeof d=="object"&&d!==null||(0,i.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),d.name){case"AbortException":return new i.AbortException(d.message);case"MissingPDFException":return new i.MissingPDFException(d.message);case"PasswordException":return new i.PasswordException(d.message,d.code);case"UnexpectedResponseException":return new i.UnexpectedResponseException(d.message,d.status);case"UnknownErrorException":return new i.UnknownErrorException(d.message,d.details);default:return new i.UnknownErrorException(d.message,d.toString())}}class u{constructor(h,y,b){this.sourceName=h,this.targetName=y,this.comObj=b,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),this._onComObjOnMessage=w=>{let p=w.data;if(p.targetName!==this.sourceName)return;if(p.stream){this._processStreamMessage(p);return}if(p.callback){let f=p.callbackId,g=this.callbackCapabilities[f];if(!g)throw new Error(`Cannot resolve callback ${f}`);if(delete this.callbackCapabilities[f],p.callback===o.DATA)g.resolve(p.data);else if(p.callback===o.ERROR)g.reject(l(p.reason));else throw new Error("Unexpected callback case");return}let m=this.actionHandler[p.action];if(!m)throw new Error(`Unknown action from worker: ${p.action}`);if(p.callbackId){let f=this.sourceName,g=p.sourceName;new Promise(function(v){v(m(p.data))}).then(function(v){b.postMessage({sourceName:f,targetName:g,callback:o.DATA,callbackId:p.callbackId,data:v})},function(v){b.postMessage({sourceName:f,targetName:g,callback:o.ERROR,callbackId:p.callbackId,reason:l(v)})});return}if(p.streamId){this._createStreamSink(p);return}m(p.data)},b.addEventListener("message",this._onComObjOnMessage)}on(h,y){let b=this.actionHandler;if(b[h])throw new Error(`There is already an actionName called "${h}"`);b[h]=y}send(h,y,b){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:h,data:y},b)}sendWithPromise(h,y,b){let w=this.callbackId++,p=(0,i.createPromiseCapability)();this.callbackCapabilities[w]=p;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:h,callbackId:w,data:y},b)}catch(m){p.reject(m)}return p.promise}sendWithStream(h,y,b,w){let p=this.streamId++,m=this.sourceName,f=this.targetName,g=this.comObj;return new ReadableStream({start:v=>{let A=(0,i.createPromiseCapability)();return this.streamControllers[p]={controller:v,startCall:A,pullCall:null,cancelCall:null,isClosed:!1},g.postMessage({sourceName:m,targetName:f,action:h,streamId:p,data:y,desiredSize:v.desiredSize},w),A.promise},pull:v=>{let A=(0,i.createPromiseCapability)();return this.streamControllers[p].pullCall=A,g.postMessage({sourceName:m,targetName:f,stream:a.PULL,streamId:p,desiredSize:v.desiredSize}),A.promise},cancel:v=>{(0,i.assert)(v instanceof Error,"cancel must have a valid reason");let A=(0,i.createPromiseCapability)();return this.streamControllers[p].cancelCall=A,this.streamControllers[p].isClosed=!0,g.postMessage({sourceName:m,targetName:f,stream:a.CANCEL,streamId:p,reason:l(v)}),A.promise}},b)}_createStreamSink(h){let y=h.streamId,b=this.sourceName,w=h.sourceName,p=this.comObj,m=this,f=this.actionHandler[h.action],g={enqueue(v,A=1,C){if(this.isCancelled)return;let O=this.desiredSize;this.desiredSize-=A,O>0&&this.desiredSize<=0&&(this.sinkCapability=(0,i.createPromiseCapability)(),this.ready=this.sinkCapability.promise),p.postMessage({sourceName:b,targetName:w,stream:a.ENQUEUE,streamId:y,chunk:v},C)},close(){this.isCancelled||(this.isCancelled=!0,p.postMessage({sourceName:b,targetName:w,stream:a.CLOSE,streamId:y}),delete m.streamSinks[y])},error(v){(0,i.assert)(v instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,p.postMessage({sourceName:b,targetName:w,stream:a.ERROR,streamId:y,reason:l(v)}))},sinkCapability:(0,i.createPromiseCapability)(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:h.desiredSize,ready:null};g.sinkCapability.resolve(),g.ready=g.sinkCapability.promise,this.streamSinks[y]=g,new Promise(function(v){v(f(h.data,g))}).then(function(){p.postMessage({sourceName:b,targetName:w,stream:a.START_COMPLETE,streamId:y,success:!0})},function(v){p.postMessage({sourceName:b,targetName:w,stream:a.START_COMPLETE,streamId:y,reason:l(v)})})}_processStreamMessage(h){let y=h.streamId,b=this.sourceName,w=h.sourceName,p=this.comObj,m=this.streamControllers[y],f=this.streamSinks[y];switch(h.stream){case a.START_COMPLETE:h.success?m.startCall.resolve():m.startCall.reject(l(h.reason));break;case a.PULL_COMPLETE:h.success?m.pullCall.resolve():m.pullCall.reject(l(h.reason));break;case a.PULL:if(!f){p.postMessage({sourceName:b,targetName:w,stream:a.PULL_COMPLETE,streamId:y,success:!0});break}f.desiredSize<=0&&h.desiredSize>0&&f.sinkCapability.resolve(),f.desiredSize=h.desiredSize,new Promise(function(g){g(f.onPull&&f.onPull())}).then(function(){p.postMessage({sourceName:b,targetName:w,stream:a.PULL_COMPLETE,streamId:y,success:!0})},function(g){p.postMessage({sourceName:b,targetName:w,stream:a.PULL_COMPLETE,streamId:y,reason:l(g)})});break;case a.ENQUEUE:if((0,i.assert)(m,"enqueue should have stream controller"),m.isClosed)break;m.controller.enqueue(h.chunk);break;case a.CLOSE:if((0,i.assert)(m,"close should have stream controller"),m.isClosed)break;m.isClosed=!0,m.controller.close(),this._deleteStreamController(m,y);break;case a.ERROR:(0,i.assert)(m,"error should have stream controller"),m.controller.error(l(h.reason)),this._deleteStreamController(m,y);break;case a.CANCEL_COMPLETE:h.success?m.cancelCall.resolve():m.cancelCall.reject(l(h.reason)),this._deleteStreamController(m,y);break;case a.CANCEL:if(!f)break;new Promise(function(g){g(f.onCancel&&f.onCancel(l(h.reason)))}).then(function(){p.postMessage({sourceName:b,targetName:w,stream:a.CANCEL_COMPLETE,streamId:y,success:!0})},function(g){p.postMessage({sourceName:b,targetName:w,stream:a.CANCEL_COMPLETE,streamId:y,reason:l(g)})}),f.sinkCapability.reject(l(h.reason)),f.isCancelled=!0,delete this.streamSinks[y];break;default:throw new Error("Unexpected stream case")}}async _deleteStreamController(h,y){await Promise.allSettled([h.startCall&&h.startCall.promise,h.pullCall&&h.pullCall.promise,h.cancelCall&&h.cancelCall.promise]),delete this.streamControllers[y]}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}t.MessageHandler=u},(r,t,n)=>{var a,l;Object.defineProperty(t,"__esModule",{value:!0}),t.Metadata=void 0;var i=n(1);class o{constructor({parsedData:d,rawData:h}){_n(this,a,void 0);_n(this,l,void 0);Nr(this,a,d),Nr(this,l,h)}getRaw(){return It(this,l)}get(d){return It(this,a).get(d)??null}getAll(){return(0,i.objectFromMap)(It(this,a))}has(d){return It(this,a).has(d)}}a=new WeakMap,l=new WeakMap,t.Metadata=o},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionalContentConfig=void 0;var i=n(1);class o{constructor(u,d){this.visible=!0,this.name=u,this.intent=d}}class a{constructor(u){if(this.name=null,this.creator=null,this._order=null,this._groups=new Map,u!==null){this.name=u.name,this.creator=u.creator,this._order=u.order;for(let d of u.groups)this._groups.set(d.id,new o(d.name,d.intent));if(u.baseState==="OFF")for(let d of this._groups)d.visible=!1;for(let d of u.on)this._groups.get(d).visible=!0;for(let d of u.off)this._groups.get(d).visible=!1}}_evaluateVisibilityExpression(u){let d=u.length;if(d<2)return!0;let h=u[0];for(let y=1;y<d;y++){let b=u[y],w;if(Array.isArray(b))w=this._evaluateVisibilityExpression(b);else if(this._groups.has(b))w=this._groups.get(b).visible;else return(0,i.warn)(`Optional content group not found: ${b}`),!0;switch(h){case"And":if(!w)return!1;break;case"Or":if(w)return!0;break;case"Not":return!w;default:return!0}}return h==="And"}isVisible(u){if(this._groups.size===0)return!0;if(!u)return(0,i.warn)("Optional content group not defined."),!0;if(u.type==="OCG")return this._groups.has(u.id)?this._groups.get(u.id).visible:((0,i.warn)(`Optional content group not found: ${u.id}`),!0);if(u.type==="OCMD"){if(u.expression)return this._evaluateVisibilityExpression(u.expression);if(!u.policy||u.policy==="AnyOn"){for(let d of u.ids){if(!this._groups.has(d))return(0,i.warn)(`Optional content group not found: ${d}`),!0;if(this._groups.get(d).visible)return!0}return!1}else if(u.policy==="AllOn"){for(let d of u.ids){if(!this._groups.has(d))return(0,i.warn)(`Optional content group not found: ${d}`),!0;if(!this._groups.get(d).visible)return!1}return!0}else if(u.policy==="AnyOff"){for(let d of u.ids){if(!this._groups.has(d))return(0,i.warn)(`Optional content group not found: ${d}`),!0;if(!this._groups.get(d).visible)return!0}return!1}else if(u.policy==="AllOff"){for(let d of u.ids){if(!this._groups.has(d))return(0,i.warn)(`Optional content group not found: ${d}`),!0;if(this._groups.get(d).visible)return!1}return!0}return(0,i.warn)(`Unknown optional content policy ${u.policy}.`),!0}return(0,i.warn)(`Unknown group type ${u.type}.`),!0}setVisibility(u,d=!0){if(!this._groups.has(u)){(0,i.warn)(`Optional content group not found: ${u}`);return}this._groups.get(u).visible=!!d}getOrder(){return this._groups.size?this._order?this._order.slice():Array.from(this._groups.keys()):null}getGroups(){return this._groups.size>0?(0,i.objectFromMap)(this._groups):null}getGroup(u){return this._groups.get(u)||null}}t.OptionalContentConfig=a},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PDFDataTransportStream=void 0;var i=n(1),o=n(5);class a{constructor(h,y){(0,i.assert)(y,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.'),this._queuedChunks=[],this._progressiveDone=h.progressiveDone||!1,this._contentDispositionFilename=h.contentDispositionFilename||null;let b=h.initialData;if(b?.length>0){let w=new Uint8Array(b).buffer;this._queuedChunks.push(w)}this._pdfDataRangeTransport=y,this._isStreamingSupported=!h.disableStream,this._isRangeSupported=!h.disableRange,this._contentLength=h.length,this._fullRequestReader=null,this._rangeReaders=[],this._pdfDataRangeTransport.addRangeListener((w,p)=>{this._onReceiveData({begin:w,chunk:p})}),this._pdfDataRangeTransport.addProgressListener((w,p)=>{this._onProgress({loaded:w,total:p})}),this._pdfDataRangeTransport.addProgressiveReadListener(w=>{this._onReceiveData({chunk:w})}),this._pdfDataRangeTransport.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),this._pdfDataRangeTransport.transportReady()}_onReceiveData(h){let y=new Uint8Array(h.chunk).buffer;if(h.begin===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(y):this._queuedChunks.push(y);else{let b=this._rangeReaders.some(function(w){return w._begin!==h.begin?!1:(w._enqueue(y),!0)});(0,i.assert)(b,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(h){if(h.total===void 0){let y=this._rangeReaders[0];y?.onProgress&&y.onProgress({loaded:h.loaded})}else{let y=this._fullRequestReader;y?.onProgress&&y.onProgress({loaded:h.loaded,total:h.total})}}_onProgressiveDone(){this._fullRequestReader&&this._fullRequestReader.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(h){let y=this._rangeReaders.indexOf(h);y>=0&&this._rangeReaders.splice(y,1)}getFullReader(){(0,i.assert)(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");let h=this._queuedChunks;return this._queuedChunks=null,new l(this,h,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(h,y){if(y<=this._progressiveDataLength)return null;let b=new u(this,h,y);return this._pdfDataRangeTransport.requestDataRange(h,y),this._rangeReaders.push(b),b}cancelAllRequests(h){this._fullRequestReader&&this._fullRequestReader.cancel(h);for(let y of this._rangeReaders.slice(0))y.cancel(h);this._pdfDataRangeTransport.abort()}}t.PDFDataTransportStream=a;class l{constructor(h,y,b=!1,w=null){this._stream=h,this._done=b||!1,this._filename=(0,o.isPdfFile)(w)?w:null,this._queuedChunks=y||[],this._loaded=0;for(let p of this._queuedChunks)this._loaded+=p.byteLength;this._requests=[],this._headersReady=Promise.resolve(),h._fullRequestReader=this,this.onProgress=null}_enqueue(h){this._done||(this._requests.length>0?this._requests.shift().resolve({value:h,done:!1}):this._queuedChunks.push(h),this._loaded+=h.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let h=(0,i.createPromiseCapability)();return this._requests.push(h),h.promise}cancel(h){this._done=!0;for(let y of this._requests)y.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class u{constructor(h,y,b){this._stream=h,this._begin=y,this._end=b,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(h){if(!this._done){if(this._requests.length===0)this._queuedChunk=h;else{this._requests.shift().resolve({value:h,done:!1});for(let b of this._requests)b.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){let y=this._queuedChunk;return this._queuedChunk=null,{value:y,done:!1}}if(this._done)return{value:void 0,done:!0};let h=(0,i.createPromiseCapability)();return this._requests.push(h),h.promise}cancel(h){this._done=!0;for(let y of this._requests)y.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}},(r,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.XfaText=void 0;class n{static textContent(o){let a=[],l={items:a,styles:Object.create(null)};function u(d){if(!d)return;let h=null,y=d.name;if(y==="#text")h=d.value;else if(n.shouldBuildText(y))d?.attributes?.textContent?h=d.attributes.textContent:d.value&&(h=d.value);else return;if(h!==null&&a.push({str:h}),!!d.children)for(let b of d.children)u(b)}return u(o),l}static shouldBuildText(o){return!(o==="textarea"||o==="input"||o==="option"||o==="select")}}t.XfaText=n},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NodeStandardFontDataFactory=t.NodeCanvasFactory=t.NodeCMapReaderFactory=void 0;var i=n(6);let o=function(d){return new Promise((h,y)=>{vd().readFile(d,(w,p)=>{if(w||!p){y(new Error(w));return}h(new Uint8Array(p))})})};class a extends i.BaseCanvasFactory{_createCanvas(h,y){return ix().createCanvas(h,y)}}t.NodeCanvasFactory=a;class l extends i.BaseCMapReaderFactory{_fetchData(h,y){return o(h).then(b=>({cMapData:b,compressionType:y}))}}t.NodeCMapReaderFactory=l;class u extends i.BaseStandardFontDataFactory{_fetchData(h){return o(h)}}t.NodeStandardFontDataFactory=u},(r,t,n)=>{var J,lx;Object.defineProperty(t,"__esModule",{value:!0}),t.AnnotationLayer=void 0;var i=n(1),o=n(5),a=n(8),l=n(21),u=n(22);let d=1e3,h=new WeakSet;function y(k){return{width:k[2]-k[0],height:k[3]-k[1]}}class b{static create(x){switch(x.data.annotationType){case i.AnnotationType.LINK:return new p(x);case i.AnnotationType.TEXT:return new m(x);case i.AnnotationType.WIDGET:switch(x.data.fieldType){case"Tx":return new g(x);case"Btn":return x.data.radioButton?new A(x):x.data.checkBox?new v(x):new C(x);case"Ch":return new O(x)}return new f(x);case i.AnnotationType.POPUP:return new E(x);case i.AnnotationType.FREETEXT:return new I(x);case i.AnnotationType.LINE:return new M(x);case i.AnnotationType.SQUARE:return new j(x);case i.AnnotationType.CIRCLE:return new U(x);case i.AnnotationType.POLYLINE:return new B(x);case i.AnnotationType.CARET:return new q(x);case i.AnnotationType.INK:return new z(x);case i.AnnotationType.POLYGON:return new N(x);case i.AnnotationType.HIGHLIGHT:return new ne(x);case i.AnnotationType.UNDERLINE:return new oe(x);case i.AnnotationType.SQUIGGLY:return new ae(x);case i.AnnotationType.STRIKEOUT:return new te(x);case i.AnnotationType.STAMP:return new le(x);case i.AnnotationType.FILEATTACHMENT:return new xe(x);default:return new w(x)}}}class w{constructor(x,{isRenderable:R=!1,ignoreBorder:L=!1,createQuadrilaterals:F=!1}={}){this.isRenderable=R,this.data=x.data,this.layer=x.layer,this.page=x.page,this.viewport=x.viewport,this.linkService=x.linkService,this.downloadManager=x.downloadManager,this.imageResourcesPath=x.imageResourcesPath,this.renderForms=x.renderForms,this.svgFactory=x.svgFactory,this.annotationStorage=x.annotationStorage,this.enableScripting=x.enableScripting,this.hasJSActions=x.hasJSActions,this._fieldObjects=x.fieldObjects,this._mouseState=x.mouseState,R&&(this.container=this._createContainer(L)),F&&(this.quadrilaterals=this._createQuadrilaterals(L))}_createContainer(x=!1){let R=this.data,L=this.page,F=this.viewport,W=document.createElement("section"),{width:V,height:Z}=y(R.rect);W.setAttribute("data-annotation-id",R.id);let ee=i.Util.normalizeRect([R.rect[0],L.view[3]-R.rect[1]+L.view[1],R.rect[2],L.view[3]-R.rect[3]+L.view[1]]);if(R.hasOwnCanvas){let ie=F.transform.slice(),[ue,de]=i.Util.singularValueDecompose2dScale(ie);V=Math.ceil(V*ue),Z=Math.ceil(Z*de),ee[0]*=ue,ee[1]*=de;for(let ye=0;ye<4;ye++)ie[ye]=Math.sign(ie[ye]);W.style.transform=`matrix(${ie.join(",")})`}else W.style.transform=`matrix(${F.transform.join(",")})`;if(W.style.transformOrigin=`${-ee[0]}px ${-ee[1]}px`,!x&&R.borderStyle.width>0){W.style.borderWidth=`${R.borderStyle.width}px`,R.borderStyle.style!==i.AnnotationBorderStyleType.UNDERLINE&&(V-=2*R.borderStyle.width,Z-=2*R.borderStyle.width);let ie=R.borderStyle.horizontalCornerRadius,ue=R.borderStyle.verticalCornerRadius;if(ie>0||ue>0){let ye=`${ie}px / ${ue}px`;W.style.borderRadius=ye}switch(R.borderStyle.style){case i.AnnotationBorderStyleType.SOLID:W.style.borderStyle="solid";break;case i.AnnotationBorderStyleType.DASHED:W.style.borderStyle="dashed";break;case i.AnnotationBorderStyleType.BEVELED:(0,i.warn)("Unimplemented border style: beveled");break;case i.AnnotationBorderStyleType.INSET:(0,i.warn)("Unimplemented border style: inset");break;case i.AnnotationBorderStyleType.UNDERLINE:W.style.borderBottomStyle="solid";break;default:break}R.borderColor||R.color||null?W.style.borderColor=i.Util.makeHexColor(R.color[0]|0,R.color[1]|0,R.color[2]|0):W.style.borderWidth=0}return W.style.left=`${ee[0]}px`,W.style.top=`${ee[1]}px`,R.hasOwnCanvas?W.style.width=W.style.height="auto":(W.style.width=`${V}px`,W.style.height=`${Z}px`),W}get _commonActions(){let x=(R,L,F)=>{let W=F.detail[R];F.target.style[L]=l.ColorConverters[`${W[0]}_HTML`](W.slice(1))};return(0,i.shadow)(this,"_commonActions",{display:R=>{let L=R.detail.display%2==1;R.target.style.visibility=L?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{hidden:L,print:R.detail.display===0||R.detail.display===3})},print:R=>{this.annotationStorage.setValue(this.data.id,{print:R.detail.print})},hidden:R=>{R.target.style.visibility=R.detail.hidden?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{hidden:R.detail.hidden})},focus:R=>{setTimeout(()=>R.target.focus({preventScroll:!1}),0)},userName:R=>{R.target.title=R.detail.userName},readonly:R=>{R.detail.readonly?R.target.setAttribute("readonly",""):R.target.removeAttribute("readonly")},required:R=>{R.detail.required?R.target.setAttribute("required",""):R.target.removeAttribute("required")},bgColor:R=>{x("bgColor","backgroundColor",R)},fillColor:R=>{x("fillColor","backgroundColor",R)},fgColor:R=>{x("fgColor","color",R)},textColor:R=>{x("textColor","color",R)},borderColor:R=>{x("borderColor","borderColor",R)},strokeColor:R=>{x("strokeColor","borderColor",R)}})}_dispatchEventFromSandbox(x,R){let L=this._commonActions;for(let F of Object.keys(R.detail)){let W=x[F]||L[F];W&&W(R)}}_setDefaultPropertiesFromJS(x){if(!this.enableScripting)return;let R=this.annotationStorage.getRawValue(this.data.id);if(!R)return;let L=this._commonActions;for(let[F,W]of Object.entries(R)){let V=L[F];V&&(V({detail:W,target:x}),delete R[F])}}_createQuadrilaterals(x=!1){if(!this.data.quadPoints)return null;let R=[],L=this.data.rect;for(let F of this.data.quadPoints)this.data.rect=[F[2].x,F[2].y,F[1].x,F[1].y],R.push(this._createContainer(x));return this.data.rect=L,R}_createPopup(x,R){let L=this.container;this.quadrilaterals&&(x=x||this.quadrilaterals,L=this.quadrilaterals[0]),x||(x=document.createElement("div"),x.style.height=L.style.height,x.style.width=L.style.width,L.appendChild(x));let W=new T({container:L,trigger:x,color:R.color,titleObj:R.titleObj,modificationDate:R.modificationDate,contentsObj:R.contentsObj,richText:R.richText,hideWrapper:!0}).render();W.style.left=L.style.width,L.appendChild(W)}_renderQuadrilaterals(x){for(let R of this.quadrilaterals)R.className=x;return this.quadrilaterals}render(){(0,i.unreachable)("Abstract method `AnnotationElement.render` called")}_getElementsByName(x,R=null){let L=[];if(this._fieldObjects){let F=this._fieldObjects[x];if(F)for(let{page:W,id:V,exportValues:Z}of F){if(W===-1||V===R)continue;let ee=typeof Z=="string"?Z:null,ie=document.getElementById(V);if(ie&&!h.has(ie)){(0,i.warn)(`_getElementsByName - element not allowed: ${V}`);continue}L.push({id:V,exportValue:ee,domElement:ie})}return L}for(let F of document.getElementsByName(x)){let{id:W,exportValue:V}=F;W!==R&&(!h.has(F)||L.push({id:W,exportValue:V,domElement:F}))}return L}static get platform(){let x=typeof navigator!="undefined"?navigator.platform:"";return(0,i.shadow)(this,"platform",{isWin:x.includes("Win"),isMac:x.includes("Mac")})}}class p extends w{constructor(x,R=null){let L=!!(x.data.url||x.data.dest||x.data.action||x.data.isTooltipOnly||x.data.resetForm||x.data.actions&&(x.data.actions.Action||x.data.actions["Mouse Up"]||x.data.actions["Mouse Down"]));super(x,{isRenderable:L,ignoreBorder:!!R?.ignoreBorder,createQuadrilaterals:!0})}render(){let{data:x,linkService:R}=this,L=document.createElement("a");if(x.url)R.addLinkAttributes(L,x.url,x.newWindow);else if(x.action)this._bindNamedAction(L,x.action);else if(x.dest)this._bindLink(L,x.dest);else{let F=!1;x.actions&&(x.actions.Action||x.actions["Mouse Up"]||x.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(F=!0,this._bindJSAction(L,x)),x.resetForm?this._bindResetFormAction(L,x.resetForm):F||this._bindLink(L,"")}return this.quadrilaterals?this._renderQuadrilaterals("linkAnnotation").map((F,W)=>{let V=W===0?L:L.cloneNode();return F.appendChild(V),F}):(this.container.className="linkAnnotation",this.container.appendChild(L),this.container)}_bindLink(x,R){x.href=this.linkService.getDestinationHash(R),x.onclick=()=>(R&&this.linkService.goToDestination(R),!1),(R||R==="")&&(x.className="internalLink")}_bindNamedAction(x,R){x.href=this.linkService.getAnchorUrl(""),x.onclick=()=>(this.linkService.executeNamedAction(R),!1),x.className="internalLink"}_bindJSAction(x,R){x.href=this.linkService.getAnchorUrl("");let L=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(let F of Object.keys(R.actions)){let W=L.get(F);!W||(x[W]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:R.id,name:F}}),!1))}x.onclick||(x.onclick=()=>!1),x.className="internalLink"}_bindResetFormAction(x,R){let L=x.onclick;if(L||(x.href=this.linkService.getAnchorUrl("")),x.className="internalLink",!this._fieldObjects){(0,i.warn)('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),L||(x.onclick=()=>!1);return}x.onclick=()=>{L&&L();let{fields:F,refs:W,include:V}=R,Z=[];if(F.length!==0||W.length!==0){let ue=new Set(W);for(let de of F){let ye=this._fieldObjects[de]||[];for(let{id:ke}of ye)ue.add(ke)}for(let de of Object.values(this._fieldObjects))for(let ye of de)ue.has(ye.id)===V&&Z.push(ye)}else for(let ue of Object.values(this._fieldObjects))Z.push(...ue);let ee=this.annotationStorage,ie=[];for(let ue of Z){let{id:de}=ue;switch(ie.push(de),ue.type){case"text":{let ke=ue.defaultValue||"";ee.setValue(de,{value:ke});break}case"checkbox":case"radiobutton":{let ke=ue.defaultValue===ue.exportValues;ee.setValue(de,{value:ke});break}case"combobox":case"listbox":{let ke=ue.defaultValue||"";ee.setValue(de,{value:ke});break}default:continue}let ye=document.getElementById(de);!ye||!h.has(ye)||ye.dispatchEvent(new Event("resetform"))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:ie,name:"ResetForm"}}),!1}}}class m extends w{constructor(x){let R=!!(x.data.hasPopup||x.data.titleObj?.str||x.data.contentsObj?.str||x.data.richText?.str);super(x,{isRenderable:R})}render(){this.container.className="textAnnotation";let x=document.createElement("img");return x.style.height=this.container.style.height,x.style.width=this.container.style.width,x.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",x.alt="[{{type}} Annotation]",x.dataset.l10nId="text_annotation_type",x.dataset.l10nArgs=JSON.stringify({type:this.data.name}),this.data.hasPopup||this._createPopup(x,this.data),this.container.appendChild(x),this.container}}class f extends w{render(){return this.data.alternativeText&&(this.container.title=this.data.alternativeText),this.container}_getKeyModifier(x){let{isWin:R,isMac:L}=w.platform;return R&&x.ctrlKey||L&&x.metaKey}_setEventListener(x,R,L,F){R.includes("mouse")?x.addEventListener(R,W=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:L,value:F(W),shift:W.shiftKey,modifier:this._getKeyModifier(W)}})}):x.addEventListener(R,W=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:L,value:F(W)}})})}_setEventListeners(x,R,L){for(let[F,W]of R)(W==="Action"||this.data.actions?.[W])&&this._setEventListener(x,F,W,L)}_setBackgroundColor(x){let R=this.data.backgroundColor||null;x.style.backgroundColor=R===null?"transparent":i.Util.makeHexColor(R[0],R[1],R[2])}}class g extends f{constructor(x){let R=x.renderForms||!x.data.hasAppearance&&!!x.data.fieldValue;super(x,{isRenderable:R})}setPropertyOnSiblings(x,R,L,F){let W=this.annotationStorage;for(let V of this._getElementsByName(x.name,x.id))V.domElement&&(V.domElement[R]=L),W.setValue(V.id,{[F]:L})}render(){let x=this.annotationStorage,R=this.data.id;this.container.className="textWidgetAnnotation";let L=null;if(this.renderForms){let F=x.getValue(R,{value:this.data.fieldValue}),W=F.formattedValue||F.value||"",V={userValue:null,formattedValue:null,valueOnFocus:""};this.data.multiLine?(L=document.createElement("textarea"),L.textContent=W):(L=document.createElement("input"),L.type="text",L.setAttribute("value",W)),h.add(L),L.disabled=this.data.readOnly,L.name=this.data.fieldName,L.tabIndex=d,V.userValue=W,L.setAttribute("id",R),L.addEventListener("input",ee=>{x.setValue(R,{value:ee.target.value}),this.setPropertyOnSiblings(L,"value",ee.target.value,"value")}),L.addEventListener("resetform",ee=>{let ie=this.data.defaultFieldValue??"";L.value=V.userValue=ie,V.formattedValue=null});let Z=ee=>{let{formattedValue:ie}=V;ie!=null&&(ee.target.value=ie),ee.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){L.addEventListener("focus",ie=>{V.userValue&&(ie.target.value=V.userValue),V.valueOnFocus=ie.target.value}),L.addEventListener("updatefromsandbox",ie=>{let ue={value(de){V.userValue=de.detail.value??"",x.setValue(R,{value:V.userValue.toString()}),de.target.value=V.userValue},formattedValue(de){let{formattedValue:ye}=de.detail;V.formattedValue=ye,ye!=null&&de.target!==document.activeElement&&(de.target.value=ye),x.setValue(R,{formattedValue:ye})},selRange(de){de.target.setSelectionRange(...de.detail.selRange)}};this._dispatchEventFromSandbox(ue,ie)}),L.addEventListener("keydown",ie=>{let ue=-1;if(ie.key==="Escape"?ue=0:ie.key==="Enter"?ue=2:ie.key==="Tab"&&(ue=3),ue===-1)return;let{value:de}=ie.target;V.valueOnFocus!==de&&(V.userValue=de,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:R,name:"Keystroke",value:de,willCommit:!0,commitKey:ue,selStart:ie.target.selectionStart,selEnd:ie.target.selectionEnd}}))});let ee=Z;Z=null,L.addEventListener("blur",ie=>{let{value:ue}=ie.target;V.userValue=ue,this._mouseState.isDown&&V.valueOnFocus!==ue&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:R,name:"Keystroke",value:ue,willCommit:!0,commitKey:1,selStart:ie.target.selectionStart,selEnd:ie.target.selectionEnd}}),ee(ie)}),this.data.actions?.Keystroke&&L.addEventListener("beforeinput",ie=>{let{data:ue,target:de}=ie,{value:ye,selectionStart:ke,selectionEnd:He}=de,_e=ke,be=He;switch(ie.inputType){case"deleteWordBackward":{let se=ye.substring(0,ke).match(/\w*[^\w]*$/);se&&(_e-=se[0].length);break}case"deleteWordForward":{let se=ye.substring(ke).match(/^[^\w]*\w*/);se&&(be+=se[0].length);break}case"deleteContentBackward":ke===He&&(_e-=1);break;case"deleteContentForward":ke===He&&(be+=1);break}ie.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:R,name:"Keystroke",value:ye,change:ue||"",willCommit:!1,selStart:_e,selEnd:be}})}),this._setEventListeners(L,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],ie=>ie.target.value)}if(Z&&L.addEventListener("blur",Z),this.data.maxLen!==null&&(L.maxLength=this.data.maxLen),this.data.comb){let ie=(this.data.rect[2]-this.data.rect[0])/this.data.maxLen;L.classList.add("comb"),L.style.letterSpacing=`calc(${ie}px - 1ch)`}}else L=document.createElement("div"),L.textContent=this.data.fieldValue,L.style.verticalAlign="middle",L.style.display="table-cell";return this._setTextStyle(L),this._setBackgroundColor(L),this._setDefaultPropertiesFromJS(L),this.container.appendChild(L),this.container}_setTextStyle(x){let R=["left","center","right"],{fontSize:L,fontColor:F}=this.data.defaultAppearanceData,W=x.style;L&&(W.fontSize=`${L}px`),W.color=i.Util.makeHexColor(F[0],F[1],F[2]),this.data.textAlignment!==null&&(W.textAlign=R[this.data.textAlignment])}}class v extends f{constructor(x){super(x,{isRenderable:x.renderForms})}render(){let x=this.annotationStorage,R=this.data,L=R.id,F=x.getValue(L,{value:R.exportValue===R.fieldValue}).value;typeof F=="string"&&(F=F!=="Off",x.setValue(L,{value:F})),this.container.className="buttonWidgetAnnotation checkBox";let W=document.createElement("input");return h.add(W),W.disabled=R.readOnly,W.type="checkbox",W.name=R.fieldName,F&&W.setAttribute("checked",!0),W.setAttribute("id",L),W.setAttribute("exportValue",R.exportValue),W.tabIndex=d,W.addEventListener("change",V=>{let{name:Z,checked:ee}=V.target;for(let ie of this._getElementsByName(Z,L)){let ue=ee&&ie.exportValue===R.exportValue;ie.domElement&&(ie.domElement.checked=ue),x.setValue(ie.id,{value:ue})}x.setValue(L,{value:ee})}),W.addEventListener("resetform",V=>{let Z=R.defaultFieldValue||"Off";V.target.checked=Z===R.exportValue}),this.enableScripting&&this.hasJSActions&&(W.addEventListener("updatefromsandbox",V=>{let Z={value(ee){ee.target.checked=ee.detail.value!=="Off",x.setValue(L,{value:ee.target.checked})}};this._dispatchEventFromSandbox(Z,V)}),this._setEventListeners(W,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],V=>V.target.checked)),this._setBackgroundColor(W),this._setDefaultPropertiesFromJS(W),this.container.appendChild(W),this.container}}class A extends f{constructor(x){super(x,{isRenderable:x.renderForms})}render(){this.container.className="buttonWidgetAnnotation radioButton";let x=this.annotationStorage,R=this.data,L=R.id,F=x.getValue(L,{value:R.fieldValue===R.buttonValue}).value;typeof F=="string"&&(F=F!==R.buttonValue,x.setValue(L,{value:F}));let W=document.createElement("input");if(h.add(W),W.disabled=R.readOnly,W.type="radio",W.name=R.fieldName,F&&W.setAttribute("checked",!0),W.setAttribute("id",L),W.tabIndex=d,W.addEventListener("change",V=>{let{name:Z,checked:ee}=V.target;for(let ie of this._getElementsByName(Z,L))x.setValue(ie.id,{value:!1});x.setValue(L,{value:ee})}),W.addEventListener("resetform",V=>{let Z=R.defaultFieldValue;V.target.checked=Z!=null&&Z===R.buttonValue}),this.enableScripting&&this.hasJSActions){let V=R.buttonValue;W.addEventListener("updatefromsandbox",Z=>{let ee={value:ie=>{let ue=V===ie.detail.value;for(let de of this._getElementsByName(ie.target.name)){let ye=ue&&de.id===L;de.domElement&&(de.domElement.checked=ye),x.setValue(de.id,{value:ye})}}};this._dispatchEventFromSandbox(ee,Z)}),this._setEventListeners(W,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],Z=>Z.target.checked)}return this._setBackgroundColor(W),this._setDefaultPropertiesFromJS(W),this.container.appendChild(W),this.container}}class C extends p{constructor(x){super(x,{ignoreBorder:x.data.hasAppearance})}render(){let x=super.render();return x.className="buttonWidgetAnnotation pushButton",this.data.alternativeText&&(x.title=this.data.alternativeText),this._setDefaultPropertiesFromJS(x),x}}class O extends f{constructor(x){super(x,{isRenderable:x.renderForms})}render(){this.container.className="choiceWidgetAnnotation";let x=this.annotationStorage,R=this.data.id,L=x.getValue(R,{value:this.data.fieldValue}),{fontSize:F}=this.data.defaultAppearanceData;F||(F=9);let W=`calc(${F}px * var(--zoom-factor))`,V=document.createElement("select");h.add(V),V.disabled=this.data.readOnly,V.name=this.data.fieldName,V.setAttribute("id",R),V.tabIndex=d,V.style.fontSize=`${F}px`,this.data.combo||(V.size=this.data.options.length,this.data.multiSelect&&(V.multiple=!0)),V.addEventListener("resetform",ie=>{let ue=this.data.defaultFieldValue;for(let de of V.options)de.selected=de.value===ue});for(let ie of this.data.options){let ue=document.createElement("option");ue.textContent=ie.displayValue,ue.value=ie.exportValue,this.data.combo&&(ue.style.fontSize=W),L.value.includes(ie.exportValue)&&ue.setAttribute("selected",!0),V.appendChild(ue)}let Z=(ie,ue)=>{let de=ue?"value":"textContent",ye=ie.target.options;return ie.target.multiple?Array.prototype.filter.call(ye,ke=>ke.selected).map(ke=>ke[de]):ye.selectedIndex===-1?null:ye[ye.selectedIndex][de]},ee=ie=>{let ue=ie.target.options;return Array.prototype.map.call(ue,de=>({displayValue:de.textContent,exportValue:de.value}))};return this.enableScripting&&this.hasJSActions?(V.addEventListener("updatefromsandbox",ie=>{let ue={value(de){let ye=de.detail.value,ke=new Set(Array.isArray(ye)?ye:[ye]);for(let He of V.options)He.selected=ke.has(He.value);x.setValue(R,{value:Z(de,!0)})},multipleSelection(de){V.multiple=!0},remove(de){let ye=V.options,ke=de.detail.remove;ye[ke].selected=!1,V.remove(ke),ye.length>0&&Array.prototype.findIndex.call(ye,_e=>_e.selected)===-1&&(ye[0].selected=!0),x.setValue(R,{value:Z(de,!0),items:ee(de)})},clear(de){for(;V.length!==0;)V.remove(0);x.setValue(R,{value:null,items:[]})},insert(de){let{index:ye,displayValue:ke,exportValue:He}=de.detail.insert,_e=document.createElement("option");_e.textContent=ke,_e.value=He,V.insertBefore(_e,V.children[ye]),x.setValue(R,{value:Z(de,!0),items:ee(de)})},items(de){let{items:ye}=de.detail;for(;V.length!==0;)V.remove(0);for(let ke of ye){let{displayValue:He,exportValue:_e}=ke,be=document.createElement("option");be.textContent=He,be.value=_e,V.appendChild(be)}V.options.length>0&&(V.options[0].selected=!0),x.setValue(R,{value:Z(de,!0),items:ee(de)})},indices(de){let ye=new Set(de.detail.indices);for(let ke of de.target.options)ke.selected=ye.has(ke.index);x.setValue(R,{value:Z(de,!0)})},editable(de){de.target.disabled=!de.detail.editable}};this._dispatchEventFromSandbox(ue,ie)}),V.addEventListener("input",ie=>{let ue=Z(ie,!0),de=Z(ie,!1);x.setValue(R,{value:ue}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:R,name:"Keystroke",value:de,changeEx:ue,willCommit:!0,commitKey:1,keyDown:!1}})}),this._setEventListeners(V,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"]],ie=>ie.target.checked)):V.addEventListener("input",function(ie){x.setValue(R,{value:Z(ie,!0)})}),this._setBackgroundColor(V),this._setDefaultPropertiesFromJS(V),this.container.appendChild(V),this.container}}class E extends w{constructor(x){let R=!!(x.data.titleObj?.str||x.data.contentsObj?.str||x.data.richText?.str);super(x,{isRenderable:R})}render(){let x=["Line","Square","Circle","PolyLine","Polygon","Ink"];if(this.container.className="popupAnnotation",x.includes(this.data.parentType))return this.container;let R=`[data-annotation-id="${this.data.parentId}"]`,L=this.layer.querySelectorAll(R);if(L.length===0)return this.container;let F=new T({container:this.container,trigger:Array.from(L),color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText}),W=this.page,V=i.Util.normalizeRect([this.data.parentRect[0],W.view[3]-this.data.parentRect[1]+W.view[1],this.data.parentRect[2],W.view[3]-this.data.parentRect[3]+W.view[1]]),Z=V[0]+this.data.parentRect[2]-this.data.parentRect[0],ee=V[1];return this.container.style.transformOrigin=`${-Z}px ${-ee}px`,this.container.style.left=`${Z}px`,this.container.style.top=`${ee}px`,this.container.appendChild(F.render()),this.container}}class T{constructor(x){this.container=x.container,this.trigger=x.trigger,this.color=x.color,this.titleObj=x.titleObj,this.modificationDate=x.modificationDate,this.contentsObj=x.contentsObj,this.richText=x.richText,this.hideWrapper=x.hideWrapper||!1,this.pinned=!1}render(){let x=.7,R=document.createElement("div");R.className="popupWrapper",this.hideElement=this.hideWrapper?R:this.container,this.hideElement.hidden=!0;let L=document.createElement("div");L.className="popup";let F=this.color;if(F){let Z=x*(255-F[0])+F[0],ee=x*(255-F[1])+F[1],ie=x*(255-F[2])+F[2];L.style.backgroundColor=i.Util.makeHexColor(Z|0,ee|0,ie|0)}let W=document.createElement("h1");W.dir=this.titleObj.dir,W.textContent=this.titleObj.str,L.appendChild(W);let V=o.PDFDateString.toDateObject(this.modificationDate);if(V){let Z=document.createElement("span");Z.className="popupDate",Z.textContent="{{date}}, {{time}}",Z.dataset.l10nId="annotation_date_string",Z.dataset.l10nArgs=JSON.stringify({date:V.toLocaleDateString(),time:V.toLocaleTimeString()}),L.appendChild(Z)}if(this.richText?.str&&(!this.contentsObj?.str||this.contentsObj.str===this.richText.str))u.XfaLayer.render({xfaHtml:this.richText.html,intent:"richText",div:L}),L.lastChild.className="richText popupContent";else{let Z=this._formatContents(this.contentsObj);L.appendChild(Z)}Array.isArray(this.trigger)||(this.trigger=[this.trigger]);for(let Z of this.trigger)Z.addEventListener("click",this._toggle.bind(this)),Z.addEventListener("mouseover",this._show.bind(this,!1)),Z.addEventListener("mouseout",this._hide.bind(this,!1));return L.addEventListener("click",this._hide.bind(this,!0)),R.appendChild(L),R}_formatContents({str:x,dir:R}){let L=document.createElement("p");L.className="popupContent",L.dir=R;let F=x.split(/(?:\r\n?|\n)/);for(let W=0,V=F.length;W<V;++W){let Z=F[W];L.appendChild(document.createTextNode(Z)),W<V-1&&L.appendChild(document.createElement("br"))}return L}_toggle(){this.pinned?this._hide(!0):this._show(!0)}_show(x=!1){x&&(this.pinned=!0),this.hideElement.hidden&&(this.hideElement.hidden=!1,this.container.style.zIndex+=1)}_hide(x=!0){x&&(this.pinned=!1),!this.hideElement.hidden&&!this.pinned&&(this.hideElement.hidden=!0,this.container.style.zIndex-=1)}}class I extends w{constructor(x){let R=!!(x.data.hasPopup||x.data.titleObj?.str||x.data.contentsObj?.str||x.data.richText?.str);super(x,{isRenderable:R,ignoreBorder:!0})}render(){return this.container.className="freeTextAnnotation",this.data.hasPopup||this._createPopup(null,this.data),this.container}}class M extends w{constructor(x){let R=!!(x.data.hasPopup||x.data.titleObj?.str||x.data.contentsObj?.str||x.data.richText?.str);super(x,{isRenderable:R,ignoreBorder:!0})}render(){this.container.className="lineAnnotation";let x=this.data,{width:R,height:L}=y(x.rect),F=this.svgFactory.create(R,L),W=this.svgFactory.createElement("svg:line");return W.setAttribute("x1",x.rect[2]-x.lineCoordinates[0]),W.setAttribute("y1",x.rect[3]-x.lineCoordinates[1]),W.setAttribute("x2",x.rect[2]-x.lineCoordinates[2]),W.setAttribute("y2",x.rect[3]-x.lineCoordinates[3]),W.setAttribute("stroke-width",x.borderStyle.width||1),W.setAttribute("stroke","transparent"),W.setAttribute("fill","transparent"),F.appendChild(W),this.container.append(F),this._createPopup(W,x),this.container}}class j extends w{constructor(x){let R=!!(x.data.hasPopup||x.data.titleObj?.str||x.data.contentsObj?.str||x.data.richText?.str);super(x,{isRenderable:R,ignoreBorder:!0})}render(){this.container.className="squareAnnotation";let x=this.data,{width:R,height:L}=y(x.rect),F=this.svgFactory.create(R,L),W=x.borderStyle.width,V=this.svgFactory.createElement("svg:rect");return V.setAttribute("x",W/2),V.setAttribute("y",W/2),V.setAttribute("width",R-W),V.setAttribute("height",L-W),V.setAttribute("stroke-width",W||1),V.setAttribute("stroke","transparent"),V.setAttribute("fill","transparent"),F.appendChild(V),this.container.append(F),this._createPopup(V,x),this.container}}class U extends w{constructor(x){let R=!!(x.data.hasPopup||x.data.titleObj?.str||x.data.contentsObj?.str||x.data.richText?.str);super(x,{isRenderable:R,ignoreBorder:!0})}render(){this.container.className="circleAnnotation";let x=this.data,{width:R,height:L}=y(x.rect),F=this.svgFactory.create(R,L),W=x.borderStyle.width,V=this.svgFactory.createElement("svg:ellipse");return V.setAttribute("cx",R/2),V.setAttribute("cy",L/2),V.setAttribute("rx",R/2-W/2),V.setAttribute("ry",L/2-W/2),V.setAttribute("stroke-width",W||1),V.setAttribute("stroke","transparent"),V.setAttribute("fill","transparent"),F.appendChild(V),this.container.append(F),this._createPopup(V,x),this.container}}class B extends w{constructor(x){let R=!!(x.data.hasPopup||x.data.titleObj?.str||x.data.contentsObj?.str||x.data.richText?.str);super(x,{isRenderable:R,ignoreBorder:!0});this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.className=this.containerClassName;let x=this.data,{width:R,height:L}=y(x.rect),F=this.svgFactory.create(R,L),W=[];for(let Z of x.vertices){let ee=Z.x-x.rect[0],ie=x.rect[3]-Z.y;W.push(ee+","+ie)}W=W.join(" ");let V=this.svgFactory.createElement(this.svgElementName);return V.setAttribute("points",W),V.setAttribute("stroke-width",x.borderStyle.width||1),V.setAttribute("stroke","transparent"),V.setAttribute("fill","transparent"),F.appendChild(V),this.container.append(F),this._createPopup(V,x),this.container}}class N extends B{constructor(x){super(x);this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class q extends w{constructor(x){let R=!!(x.data.hasPopup||x.data.titleObj?.str||x.data.contentsObj?.str||x.data.richText?.str);super(x,{isRenderable:R,ignoreBorder:!0})}render(){return this.container.className="caretAnnotation",this.data.hasPopup||this._createPopup(null,this.data),this.container}}class z extends w{constructor(x){let R=!!(x.data.hasPopup||x.data.titleObj?.str||x.data.contentsObj?.str||x.data.richText?.str);super(x,{isRenderable:R,ignoreBorder:!0});this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline"}render(){this.container.className=this.containerClassName;let x=this.data,{width:R,height:L}=y(x.rect),F=this.svgFactory.create(R,L);for(let W of x.inkLists){let V=[];for(let ee of W){let ie=ee.x-x.rect[0],ue=x.rect[3]-ee.y;V.push(`${ie},${ue}`)}V=V.join(" ");let Z=this.svgFactory.createElement(this.svgElementName);Z.setAttribute("points",V),Z.setAttribute("stroke-width",x.borderStyle.width||1),Z.setAttribute("stroke","transparent"),Z.setAttribute("fill","transparent"),this._createPopup(Z,x),F.appendChild(Z)}return this.container.append(F),this.container}}class ne extends w{constructor(x){let R=!!(x.data.hasPopup||x.data.titleObj?.str||x.data.contentsObj?.str||x.data.richText?.str);super(x,{isRenderable:R,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return this.data.hasPopup||this._createPopup(null,this.data),this.quadrilaterals?this._renderQuadrilaterals("highlightAnnotation"):(this.container.className="highlightAnnotation",this.container)}}class oe extends w{constructor(x){let R=!!(x.data.hasPopup||x.data.titleObj?.str||x.data.contentsObj?.str||x.data.richText?.str);super(x,{isRenderable:R,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return this.data.hasPopup||this._createPopup(null,this.data),this.quadrilaterals?this._renderQuadrilaterals("underlineAnnotation"):(this.container.className="underlineAnnotation",this.container)}}class ae extends w{constructor(x){let R=!!(x.data.hasPopup||x.data.titleObj?.str||x.data.contentsObj?.str||x.data.richText?.str);super(x,{isRenderable:R,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return this.data.hasPopup||this._createPopup(null,this.data),this.quadrilaterals?this._renderQuadrilaterals("squigglyAnnotation"):(this.container.className="squigglyAnnotation",this.container)}}class te extends w{constructor(x){let R=!!(x.data.hasPopup||x.data.titleObj?.str||x.data.contentsObj?.str||x.data.richText?.str);super(x,{isRenderable:R,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return this.data.hasPopup||this._createPopup(null,this.data),this.quadrilaterals?this._renderQuadrilaterals("strikeoutAnnotation"):(this.container.className="strikeoutAnnotation",this.container)}}class le extends w{constructor(x){let R=!!(x.data.hasPopup||x.data.titleObj?.str||x.data.contentsObj?.str||x.data.richText?.str);super(x,{isRenderable:R,ignoreBorder:!0})}render(){return this.container.className="stampAnnotation",this.data.hasPopup||this._createPopup(null,this.data),this.container}}class xe extends w{constructor(x){super(x,{isRenderable:!0});let{filename:R,content:L}=this.data.file;this.filename=(0,o.getFilenameFromUrl)(R),this.content=L,this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,filename:R,content:L})}render(){this.container.className="fileAttachmentAnnotation";let x=document.createElement("div");return x.style.height=this.container.style.height,x.style.width=this.container.style.width,x.addEventListener("dblclick",this._download.bind(this)),!this.data.hasPopup&&(this.data.titleObj?.str||this.data.contentsObj?.str||this.data.richText)&&this._createPopup(x,this.data),this.container.appendChild(x),this.container}_download(){this.downloadManager?.openOrDownloadData(this.container,this.content,this.filename)}}class fe{static render(x){let R=[],L=[];for(let W of x.annotations){if(!W)continue;let{width:V,height:Z}=y(W.rect);if(!(V<=0||Z<=0)){if(W.annotationType===i.AnnotationType.POPUP){L.push(W);continue}R.push(W)}}L.length&&R.push(...L);let F=x.div;for(let W of R){let V=b.create({data:W,layer:F,page:x.page,viewport:x.viewport,linkService:x.linkService,downloadManager:x.downloadManager,imageResourcesPath:x.imageResourcesPath||"",renderForms:x.renderForms!==!1,svgFactory:new o.DOMSVGFactory,annotationStorage:x.annotationStorage||new a.AnnotationStorage,enableScripting:x.enableScripting,hasJSActions:x.hasJSActions,fieldObjects:x.fieldObjects,mouseState:x.mouseState||{isDown:!1}});if(V.isRenderable){let Z=V.render();if(W.hidden&&(Z.style.visibility="hidden"),Array.isArray(Z))for(let ee of Z)F.appendChild(ee);else V instanceof E?F.prepend(Z):F.appendChild(Z)}}Dr(this,J,lx).call(this,F,x.annotationCanvasMap)}static update(x){let{page:R,viewport:L,annotations:F,annotationCanvasMap:W,div:V}=x,Z=L.transform,ee=`matrix(${Z.join(",")})`,ie,ue;for(let de of F){let ye=V.querySelectorAll(`[data-annotation-id="${de.id}"]`);if(ye)for(let ke of ye)if(de.hasOwnCanvas){let He=i.Util.normalizeRect([de.rect[0],R.view[3]-de.rect[1]+R.view[1],de.rect[2],R.view[3]-de.rect[3]+R.view[1]]);if(!ue){ie=Math.abs(Z[0]||Z[1]);let se=Z.slice();for(let Ce=0;Ce<4;Ce++)se[Ce]=Math.sign(se[Ce]);ue=`matrix(${se.join(",")})`}let _e=He[0]*ie,be=He[1]*ie;ke.style.left=`${_e}px`,ke.style.top=`${be}px`,ke.style.transformOrigin=`${-_e}px ${-be}px`,ke.style.transform=ue}else ke.style.transform=ee}Dr(this,J,lx).call(this,V,W),V.hidden=!1}}J=new WeakSet,lx=function(x,R){if(!!R){for(let[L,F]of R){let W=x.querySelector(`[data-annotation-id="${L}"]`);if(!W)continue;let{firstChild:V}=W;V.nodeName==="CANVAS"?W.replaceChild(F,V):W.insertBefore(F,V)}R.clear()}},_n(fe,J),t.AnnotationLayer=fe},(r,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorConverters=void 0;function n(o){return Math.floor(Math.max(0,Math.min(1,o))*255).toString(16).padStart(2,"0")}class i{static CMYK_G([a,l,u,d]){return["G",1-Math.min(1,.3*a+.59*u+.11*l+d)]}static G_CMYK([a]){return["CMYK",0,0,0,1-a]}static G_RGB([a]){return["RGB",a,a,a]}static G_HTML([a]){let l=n(a);return`#${l}${l}${l}`}static RGB_G([a,l,u]){return["G",.3*a+.59*l+.11*u]}static RGB_HTML([a,l,u]){let d=n(a),h=n(l),y=n(u);return`#${d}${h}${y}`}static T_HTML(){return"#00000000"}static CMYK_RGB([a,l,u,d]){return["RGB",1-Math.min(1,a+d),1-Math.min(1,u+d),1-Math.min(1,l+d)]}static CMYK_HTML(a){return this.RGB_HTML(this.CMYK_RGB(a))}static RGB_CMYK([a,l,u]){let d=1-a,h=1-l,y=1-u,b=Math.min(d,h,y);return["CMYK",d,h,y,b]}}t.ColorConverters=i},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.XfaLayer=void 0;var i=n(18);class o{static setupStorage(l,u,d,h,y){let b=h.getValue(u,{value:null});switch(d.name){case"textarea":if(b.value!==null&&(l.textContent=b.value),y==="print")break;l.addEventListener("input",w=>{h.setValue(u,{value:w.target.value})});break;case"input":if(d.attributes.type==="radio"||d.attributes.type==="checkbox"){if(b.value===d.attributes.xfaOn?l.setAttribute("checked",!0):b.value===d.attributes.xfaOff&&l.removeAttribute("checked"),y==="print")break;l.addEventListener("change",w=>{h.setValue(u,{value:w.target.checked?w.target.getAttribute("xfaOn"):w.target.getAttribute("xfaOff")})})}else{if(b.value!==null&&l.setAttribute("value",b.value),y==="print")break;l.addEventListener("input",w=>{h.setValue(u,{value:w.target.value})})}break;case"select":if(b.value!==null)for(let w of d.children)w.attributes.value===b.value&&(w.attributes.selected=!0);l.addEventListener("input",w=>{let p=w.target.options,m=p.selectedIndex===-1?"":p[p.selectedIndex].value;h.setValue(u,{value:m})});break}}static setAttributes({html:l,element:u,storage:d=null,intent:h,linkService:y}){let{attributes:b}=u,w=l instanceof HTMLAnchorElement;b.type==="radio"&&(b.name=`${b.name}-${h}`);for(let[p,m]of Object.entries(b))if(!(m==null||p==="dataId"))if(p!=="style")if(p==="textContent")l.textContent=m;else if(p==="class")m.length&&l.setAttribute(p,m.join(" "));else{if(w&&(p==="href"||p==="newWindow"))continue;l.setAttribute(p,m)}else Object.assign(l.style,m);w&&y.addLinkAttributes(l,b.href,b.newWindow),d&&b.dataId&&this.setupStorage(l,b.dataId,u,d)}static render(l){let u=l.annotationStorage,d=l.linkService,h=l.xfaHtml,y=l.intent||"display",b=document.createElement(h.name);h.attributes&&this.setAttributes({html:b,element:h,intent:y,linkService:d});let w=[[h,-1,b]],p=l.div;if(p.appendChild(b),l.viewport){let f=`matrix(${l.viewport.transform.join(",")})`;p.style.transform=f}y!=="richText"&&p.setAttribute("class","xfaLayer xfaFont");let m=[];for(;w.length>0;){let[f,g,v]=w[w.length-1];if(g+1===f.children.length){w.pop();continue}let A=f.children[++w[w.length-1][1]];if(A===null)continue;let{name:C}=A;if(C==="#text"){let E=document.createTextNode(A.value);m.push(E),v.appendChild(E);continue}let O;if(A?.attributes?.xmlns?O=document.createElementNS(A.attributes.xmlns,C):O=document.createElement(C),v.appendChild(O),A.attributes&&this.setAttributes({html:O,element:A,storage:u,intent:y,linkService:d}),A.children&&A.children.length>0)w.push([A,-1,O]);else if(A.value){let E=document.createTextNode(A.value);i.XfaText.shouldBuildText(C)&&m.push(E),O.appendChild(E)}}for(let f of p.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))f.setAttribute("readOnly",!0);return{textDivs:m}}static update(l){let u=`matrix(${l.viewport.transform.join(",")})`;l.div.style.transform=u,l.div.hidden=!1}}t.XfaLayer=o},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.renderTextLayer=v;var i=n(1);let o=1e5,a=30,l=.8,u=new Map,d=/^\s+$/g;function h(A,C){let O=u.get(A);if(O)return O;C.save(),C.font=`${a}px ${A}`;let E=C.measureText(""),T=E.fontBoundingBoxAscent,I=Math.abs(E.fontBoundingBoxDescent);if(T){C.restore();let j=T/(T+I);return u.set(A,j),j}C.strokeStyle="red",C.clearRect(0,0,a,a),C.strokeText("g",0,0);let M=C.getImageData(0,0,a,a).data;I=0;for(let j=M.length-1-3;j>=0;j-=4)if(M[j]>0){I=Math.ceil(j/4/a);break}C.clearRect(0,0,a,a),C.strokeText("A",0,a),M=C.getImageData(0,0,a,a).data,T=0;for(let j=0,U=M.length;j<U;j+=4)if(M[j]>0){T=a-Math.floor(j/4/a);break}if(C.restore(),T){let j=T/(T+I);return u.set(A,j),j}return u.set(A,l),l}function y(A,C,O,E){let T=document.createElement("span"),I=A._enhanceTextSelection?{angle:0,canvasWidth:0,hasText:C.str!=="",hasEOL:C.hasEOL,originalTransform:null,paddingBottom:0,paddingLeft:0,paddingRight:0,paddingTop:0,scale:1}:{angle:0,canvasWidth:0,hasText:C.str!=="",hasEOL:C.hasEOL};A._textDivs.push(T);let M=i.Util.transform(A._viewport.transform,C.transform),j=Math.atan2(M[1],M[0]),U=O[C.fontName];U.vertical&&(j+=Math.PI/2);let B=Math.hypot(M[2],M[3]),N=B*h(U.fontFamily,E),q,z;j===0?(q=M[4],z=M[5]-N):(q=M[4]+N*Math.sin(j),z=M[5]-N*Math.cos(j)),T.style.left=`${q}px`,T.style.top=`${z}px`,T.style.fontSize=`${B}px`,T.style.fontFamily=U.fontFamily,T.setAttribute("role","presentation"),T.textContent=C.str,T.dir=C.dir,A._fontInspectorEnabled&&(T.dataset.fontName=C.fontName),j!==0&&(I.angle=j*(180/Math.PI));let ne=!1;if(C.str.length>1||A._enhanceTextSelection&&d.test(C.str))ne=!0;else if(C.str!==" "&&C.transform[0]!==C.transform[3]){let oe=Math.abs(C.transform[0]),ae=Math.abs(C.transform[3]);oe!==ae&&Math.max(oe,ae)/Math.min(oe,ae)>1.5&&(ne=!0)}if(ne&&(U.vertical?I.canvasWidth=C.height*A._viewport.scale:I.canvasWidth=C.width*A._viewport.scale),A._textDivProperties.set(T,I),A._textContentStream&&A._layoutText(T),A._enhanceTextSelection&&I.hasText){let oe=1,ae=0;j!==0&&(oe=Math.cos(j),ae=Math.sin(j));let te=(U.vertical?C.height:C.width)*A._viewport.scale,le=B,xe,fe;j!==0?(xe=[oe,ae,-ae,oe,q,z],fe=i.Util.getAxialAlignedBoundingBox([0,0,te,le],xe)):fe=[q,z,q+te,z+le],A._bounds.push({left:fe[0],top:fe[1],right:fe[2],bottom:fe[3],div:T,size:[te,le],m:xe})}}function b(A){if(A._canceled)return;let C=A._textDivs,O=A._capability,E=C.length;if(E>o){A._renderingDone=!0,O.resolve();return}if(!A._textContentStream)for(let T=0;T<E;T++)A._layoutText(C[T]);A._renderingDone=!0,O.resolve()}function w(A,C,O){let E=0;for(let T=0;T<O;T++){let I=A[C++];I>0&&(E=E?Math.min(I,E):I)}return E}function p(A){let C=A._bounds,O=A._viewport,E=m(O.width,O.height,C);for(let T=0;T<E.length;T++){let I=C[T].div,M=A._textDivProperties.get(I);if(M.angle===0){M.paddingLeft=C[T].left-E[T].left,M.paddingTop=C[T].top-E[T].top,M.paddingRight=E[T].right-C[T].right,M.paddingBottom=E[T].bottom-C[T].bottom,A._textDivProperties.set(I,M);continue}let j=E[T],U=C[T],B=U.m,N=B[0],q=B[1],z=[[0,0],[0,U.size[1]],[U.size[0],0],U.size],ne=new Float64Array(64);for(let ae=0,te=z.length;ae<te;ae++){let le=i.Util.applyTransform(z[ae],B);ne[ae+0]=N&&(j.left-le[0])/N,ne[ae+4]=q&&(j.top-le[1])/q,ne[ae+8]=N&&(j.right-le[0])/N,ne[ae+12]=q&&(j.bottom-le[1])/q,ne[ae+16]=q&&(j.left-le[0])/-q,ne[ae+20]=N&&(j.top-le[1])/N,ne[ae+24]=q&&(j.right-le[0])/-q,ne[ae+28]=N&&(j.bottom-le[1])/N,ne[ae+32]=N&&(j.left-le[0])/-N,ne[ae+36]=q&&(j.top-le[1])/-q,ne[ae+40]=N&&(j.right-le[0])/-N,ne[ae+44]=q&&(j.bottom-le[1])/-q,ne[ae+48]=q&&(j.left-le[0])/q,ne[ae+52]=N&&(j.top-le[1])/-N,ne[ae+56]=q&&(j.right-le[0])/q,ne[ae+60]=N&&(j.bottom-le[1])/-N}let oe=1+Math.min(Math.abs(N),Math.abs(q));M.paddingLeft=w(ne,32,16)/oe,M.paddingTop=w(ne,48,16)/oe,M.paddingRight=w(ne,0,16)/oe,M.paddingBottom=w(ne,16,16)/oe,A._textDivProperties.set(I,M)}}function m(A,C,O){let E=O.map(function(I,M){return{x1:I.left,y1:I.top,x2:I.right,y2:I.bottom,index:M,x1New:void 0,x2New:void 0}});f(A,E);let T=new Array(O.length);for(let I of E){let M=I.index;T[M]={left:I.x1New,top:0,right:I.x2New,bottom:0}}O.map(function(I,M){let j=T[M],U=E[M];U.x1=I.top,U.y1=A-j.right,U.x2=I.bottom,U.y2=A-j.left,U.index=M,U.x1New=void 0,U.x2New=void 0}),f(C,E);for(let I of E){let M=I.index;T[M].top=I.x1New,T[M].bottom=I.x2New}return T}function f(A,C){C.sort(function(T,I){return T.x1-I.x1||T.index-I.index});let E=[{start:-1/0,end:1/0,boundary:{x1:-1/0,y1:-1/0,x2:0,y2:1/0,index:-1,x1New:0,x2New:0}}];for(let T of C){let I=0;for(;I<E.length&&E[I].end<=T.y1;)I++;let M=E.length-1;for(;M>=0&&E[M].start>=T.y2;)M--;let j,U,B,N,q=-1/0;for(B=I;B<=M;B++){j=E[B],U=j.boundary;let oe;U.x2>T.x1?oe=U.index>T.index?U.x1New:T.x1:U.x2New===void 0?oe=(U.x2+T.x1)/2:oe=U.x2New,oe>q&&(q=oe)}for(T.x1New=q,B=I;B<=M;B++)j=E[B],U=j.boundary,U.x2New===void 0?U.x2>T.x1?U.index>T.index&&(U.x2New=U.x2):U.x2New=q:U.x2New>q&&(U.x2New=Math.max(q,U.x2));let z=[],ne=null;for(B=I;B<=M;B++){j=E[B],U=j.boundary;let oe=U.x2>T.x2?U:T;ne===oe?z[z.length-1].end=j.end:(z.push({start:j.start,end:j.end,boundary:oe}),ne=oe)}for(E[I].start<T.y1&&(z[0].start=T.y1,z.unshift({start:E[I].start,end:T.y1,boundary:E[I].boundary})),T.y2<E[M].end&&(z[z.length-1].end=T.y2,z.push({start:T.y2,end:E[M].end,boundary:E[M].boundary})),B=I;B<=M;B++){if(j=E[B],U=j.boundary,U.x2New!==void 0)continue;let oe=!1;for(N=I-1;!oe&&N>=0&&E[N].start>=U.y1;N--)oe=E[N].boundary===U;for(N=M+1;!oe&&N<E.length&&E[N].end<=U.y2;N++)oe=E[N].boundary===U;for(N=0;!oe&&N<z.length;N++)oe=z[N].boundary===U;oe||(U.x2New=q)}Array.prototype.splice.apply(E,[I,M-I+1].concat(z))}for(let T of E){let I=T.boundary;I.x2New===void 0&&(I.x2New=Math.max(A,I.x2))}}class g{constructor({textContent:C,textContentStream:O,container:E,viewport:T,textDivs:I,textContentItemsStr:M,enhanceTextSelection:j}){this._textContent=C,this._textContentStream=O,this._container=E,this._document=E.ownerDocument,this._viewport=T,this._textDivs=I||[],this._textContentItemsStr=M||[],this._enhanceTextSelection=!!j,this._fontInspectorEnabled=!!globalThis.FontInspector?.enabled,this._reader=null,this._layoutTextLastFontSize=null,this._layoutTextLastFontFamily=null,this._layoutTextCtx=null,this._textDivProperties=new WeakMap,this._renderingDone=!1,this._canceled=!1,this._capability=(0,i.createPromiseCapability)(),this._renderTimer=null,this._bounds=[],this._capability.promise.finally(()=>{this._enhanceTextSelection||(this._textDivProperties=null),this._layoutTextCtx&&(this._layoutTextCtx.canvas.width=0,this._layoutTextCtx.canvas.height=0,this._layoutTextCtx=null)}).catch(()=>{})}get promise(){return this._capability.promise}cancel(){this._canceled=!0,this._reader&&(this._reader.cancel(new i.AbortException("TextLayer task cancelled.")).catch(()=>{}),this._reader=null),this._renderTimer!==null&&(clearTimeout(this._renderTimer),this._renderTimer=null),this._capability.reject(new Error("TextLayer task cancelled."))}_processItems(C,O){for(let E=0,T=C.length;E<T;E++){if(C[E].str===void 0){if(C[E].type==="beginMarkedContentProps"||C[E].type==="beginMarkedContent"){let I=this._container;this._container=document.createElement("span"),this._container.classList.add("markedContent"),C[E].id!==null&&this._container.setAttribute("id",`${C[E].id}`),I.appendChild(this._container)}else C[E].type==="endMarkedContent"&&(this._container=this._container.parentNode);continue}this._textContentItemsStr.push(C[E].str),y(this,C[E],O,this._layoutTextCtx)}}_layoutText(C){let O=this._textDivProperties.get(C),E="";if(O.canvasWidth!==0&&O.hasText){let{fontSize:T,fontFamily:I}=C.style;(T!==this._layoutTextLastFontSize||I!==this._layoutTextLastFontFamily)&&(this._layoutTextCtx.font=`${T} ${I}`,this._layoutTextLastFontSize=T,this._layoutTextLastFontFamily=I);let{width:M}=this._layoutTextCtx.measureText(C.textContent);if(M>0){let j=O.canvasWidth/M;this._enhanceTextSelection&&(O.scale=j),E=`scaleX(${j})`}}if(O.angle!==0&&(E=`rotate(${O.angle}deg) ${E}`),E.length>0&&(this._enhanceTextSelection&&(O.originalTransform=E),C.style.transform=E),O.hasText&&this._container.appendChild(C),O.hasEOL){let T=document.createElement("br");T.setAttribute("role","presentation"),this._container.appendChild(T)}}_render(C=0){let O=(0,i.createPromiseCapability)(),E=Object.create(null),T=this._document.createElement("canvas");if(T.height=T.width=a,this._layoutTextCtx=T.getContext("2d",{alpha:!1}),this._textContent){let I=this._textContent.items,M=this._textContent.styles;this._processItems(I,M),O.resolve()}else if(this._textContentStream){let I=()=>{this._reader.read().then(({value:M,done:j})=>{if(j){O.resolve();return}Object.assign(E,M.styles),this._processItems(M.items,E),I()},O.reject)};this._reader=this._textContentStream.getReader(),I()}else throw new Error('Neither "textContent" nor "textContentStream" parameters specified.');O.promise.then(()=>{E=null,C?this._renderTimer=setTimeout(()=>{b(this),this._renderTimer=null},C):b(this)},this._capability.reject)}expandTextDivs(C=!1){if(!this._enhanceTextSelection||!this._renderingDone)return;this._bounds!==null&&(p(this),this._bounds=null);let O=[],E=[];for(let T=0,I=this._textDivs.length;T<I;T++){let M=this._textDivs[T],j=this._textDivProperties.get(M);!j.hasText||(C?(O.length=0,E.length=0,j.originalTransform&&O.push(j.originalTransform),j.paddingTop>0?(E.push(`${j.paddingTop}px`),O.push(`translateY(${-j.paddingTop}px)`)):E.push(0),j.paddingRight>0?E.push(`${j.paddingRight/j.scale}px`):E.push(0),j.paddingBottom>0?E.push(`${j.paddingBottom}px`):E.push(0),j.paddingLeft>0?(E.push(`${j.paddingLeft/j.scale}px`),O.push(`translateX(${-j.paddingLeft/j.scale}px)`)):E.push(0),M.style.padding=E.join(" "),O.length&&(M.style.transform=O.join(" "))):(M.style.padding=null,M.style.transform=j.originalTransform))}}}function v(A){let C=new g({textContent:A.textContent,textContentStream:A.textContentStream,container:A.container,viewport:A.viewport,textDivs:A.textDivs,textContentItemsStr:A.textContentItemsStr,enhanceTextSelection:A.enhanceTextSelection});return C._render(A.timeout),C}},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SVGGraphics=void 0;var i=n(1),o=n(5),a=n(3);let l=class{constructor(){(0,i.unreachable)("Not implemented: SVGGraphics")}};t.SVGGraphics=l;{let f=function(E){let T=[],I=[];for(let M of E){if(M.fn==="save"){T.push({fnId:92,fn:"group",items:[]}),I.push(T),T=T[T.length-1].items;continue}M.fn==="restore"?T=I.pop():T.push(M)}return T},g=function(E){if(Number.isInteger(E))return E.toString();let T=E.toFixed(10),I=T.length-1;if(T[I]!=="0")return T;do I--;while(T[I]==="0");return T.substring(0,T[I]==="."?I:I+1)},v=function(E){if(E[4]===0&&E[5]===0){if(E[1]===0&&E[2]===0)return E[0]===1&&E[3]===1?"":`scale(${g(E[0])} ${g(E[3])})`;if(E[0]===E[3]&&E[1]===-E[2]){let T=Math.acos(E[0])*180/Math.PI;return`rotate(${g(T)})`}}else if(E[0]===1&&E[1]===0&&E[2]===0&&E[3]===1)return`translate(${g(E[4])} ${g(E[5])})`;return`matrix(${g(E[0])} ${g(E[1])} ${g(E[2])} ${g(E[3])} ${g(E[4])} ${g(E[5])})`},u={fontStyle:"normal",fontWeight:"normal",fillColor:"#000000"},d="http://www.w3.org/XML/1998/namespace",h="http://www.w3.org/1999/xlink",y=["butt","round","square"],b=["miter","round","bevel"],w=function(E,T="",I=!1){if(URL.createObjectURL&&typeof Blob!="undefined"&&!I)return URL.createObjectURL(new Blob([E],{type:T}));let M="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",j=`data:${T};base64,`;for(let U=0,B=E.length;U<B;U+=3){let N=E[U]&255,q=E[U+1]&255,z=E[U+2]&255,ne=N>>2,oe=(N&3)<<4|q>>4,ae=U+1<B?(q&15)<<2|z>>6:64,te=U+2<B?z&63:64;j+=M[ne]+M[oe]+M[ae]+M[te]}return j},p=function(){let E=new Uint8Array([137,80,78,71,13,10,26,10]),T=12,I=new Int32Array(256);for(let z=0;z<256;z++){let ne=z;for(let oe=0;oe<8;oe++)ne&1?ne=3988292384^ne>>1&2147483647:ne=ne>>1&2147483647;I[z]=ne}function M(z,ne,oe){let ae=-1;for(let te=ne;te<oe;te++){let le=(ae^z[te])&255,xe=I[le];ae=ae>>>8^xe}return ae^-1}function j(z,ne,oe,ae){let te=ae,le=ne.length;oe[te]=le>>24&255,oe[te+1]=le>>16&255,oe[te+2]=le>>8&255,oe[te+3]=le&255,te+=4,oe[te]=z.charCodeAt(0)&255,oe[te+1]=z.charCodeAt(1)&255,oe[te+2]=z.charCodeAt(2)&255,oe[te+3]=z.charCodeAt(3)&255,te+=4,oe.set(ne,te),te+=ne.length;let xe=M(oe,ae+4,te);oe[te]=xe>>24&255,oe[te+1]=xe>>16&255,oe[te+2]=xe>>8&255,oe[te+3]=xe&255}function U(z,ne,oe){let ae=1,te=0;for(let le=ne;le<oe;++le)ae=(ae+(z[le]&255))%65521,te=(te+ae)%65521;return te<<16|ae}function B(z){if(!a.isNodeJS)return N(z);try{let ne;parseInt(process.versions.node)>=8?ne=z:ne=Buffer.from(z);let oe=rx().deflateSync(ne,{level:9});return oe instanceof Uint8Array?oe:new Uint8Array(oe)}catch(ne){(0,i.warn)("Not compressing PNG because zlib.deflateSync is unavailable: "+ne)}return N(z)}function N(z){let ne=z.length,oe=65535,ae=Math.ceil(ne/oe),te=new Uint8Array(2+ne+ae*5+4),le=0;te[le++]=120,te[le++]=156;let xe=0;for(;ne>oe;)te[le++]=0,te[le++]=255,te[le++]=255,te[le++]=0,te[le++]=0,te.set(z.subarray(xe,xe+oe),le),le+=oe,xe+=oe,ne-=oe;te[le++]=1,te[le++]=ne&255,te[le++]=ne>>8&255,te[le++]=~ne&65535&255,te[le++]=(~ne&65535)>>8&255,te.set(z.subarray(xe),le),le+=z.length-xe;let fe=U(z,0,z.length);return te[le++]=fe>>24&255,te[le++]=fe>>16&255,te[le++]=fe>>8&255,te[le++]=fe&255,te}function q(z,ne,oe,ae){let te=z.width,le=z.height,xe,fe,J,D=z.data;switch(ne){case i.ImageKind.GRAYSCALE_1BPP:fe=0,xe=1,J=te+7>>3;break;case i.ImageKind.RGB_24BPP:fe=2,xe=8,J=te*3;break;case i.ImageKind.RGBA_32BPP:fe=6,xe=8,J=te*4;break;default:throw new Error("invalid format")}let k=new Uint8Array((1+J)*le),x=0,R=0;for(let ee=0;ee<le;++ee)k[x++]=0,k.set(D.subarray(R,R+J),x),R+=J,x+=J;if(ne===i.ImageKind.GRAYSCALE_1BPP&&ae){x=0;for(let ee=0;ee<le;ee++){x++;for(let ie=0;ie<J;ie++)k[x++]^=255}}let L=new Uint8Array([te>>24&255,te>>16&255,te>>8&255,te&255,le>>24&255,le>>16&255,le>>8&255,le&255,xe,fe,0,0,0]),F=B(k),W=E.length+T*3+L.length+F.length,V=new Uint8Array(W),Z=0;return V.set(E,Z),Z+=E.length,j("IHDR",L,V,Z),Z+=T+L.length,j("IDATA",F,V,Z),Z+=T+F.length,j("IEND",new Uint8Array(0),V,Z),w(V,"image/png",oe)}return function(ne,oe,ae){let te=ne.kind===void 0?i.ImageKind.GRAYSCALE_1BPP:ne.kind;return q(ne,te,oe,ae)}}();class m{constructor(){this.fontSizeScale=1,this.fontWeight=u.fontWeight,this.fontSize=0,this.textMatrix=i.IDENTITY_MATRIX,this.fontMatrix=i.FONT_IDENTITY_MATRIX,this.leading=0,this.textRenderingMode=i.TextRenderingMode.FILL,this.textMatrixScale=1,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRise=0,this.fillColor=u.fillColor,this.strokeColor="#000000",this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.lineJoin="",this.lineCap="",this.miterLimit=0,this.dashArray=[],this.dashPhase=0,this.dependencies=[],this.activeClipUrl=null,this.clipGroup=null,this.maskId=""}clone(){return Object.create(this)}setCurrentPoint(T,I){this.x=T,this.y=I}}let A=0,C=0,O=0;t.SVGGraphics=l=class{constructor(E,T,I=!1){this.svgFactory=new o.DOMSVGFactory,this.current=new m,this.transformMatrix=i.IDENTITY_MATRIX,this.transformStack=[],this.extraStack=[],this.commonObjs=E,this.objs=T,this.pendingClip=null,this.pendingEOFill=!1,this.embedFonts=!1,this.embeddedFonts=Object.create(null),this.cssStyle=null,this.forceDataSchema=!!I,this._operatorIdMapping=[];for(let M in i.OPS)this._operatorIdMapping[i.OPS[M]]=M}save(){this.transformStack.push(this.transformMatrix);let E=this.current;this.extraStack.push(E),this.current=E.clone()}restore(){this.transformMatrix=this.transformStack.pop(),this.current=this.extraStack.pop(),this.pendingClip=null,this.tgrp=null}group(E){this.save(),this.executeOpTree(E),this.restore()}loadDependencies(E){let T=E.fnArray,I=E.argsArray;for(let M=0,j=T.length;M<j;M++)if(T[M]===i.OPS.dependency)for(let U of I[M]){let B=U.startsWith("g_")?this.commonObjs:this.objs,N=new Promise(q=>{B.get(U,q)});this.current.dependencies.push(N)}return Promise.all(this.current.dependencies)}transform(E,T,I,M,j,U){let B=[E,T,I,M,j,U];this.transformMatrix=i.Util.transform(this.transformMatrix,B),this.tgrp=null}getSVG(E,T){this.viewport=T;let I=this._initialize(T);return this.loadDependencies(E).then(()=>(this.transformMatrix=i.IDENTITY_MATRIX,this.executeOpTree(this.convertOpList(E)),I))}convertOpList(E){let T=this._operatorIdMapping,I=E.argsArray,M=E.fnArray,j=[];for(let U=0,B=M.length;U<B;U++){let N=M[U];j.push({fnId:N,fn:T[N],args:I[U]})}return f(j)}executeOpTree(E){for(let T of E){let I=T.fn,M=T.fnId,j=T.args;switch(M|0){case i.OPS.beginText:this.beginText();break;case i.OPS.dependency:break;case i.OPS.setLeading:this.setLeading(j);break;case i.OPS.setLeadingMoveText:this.setLeadingMoveText(j[0],j[1]);break;case i.OPS.setFont:this.setFont(j);break;case i.OPS.showText:this.showText(j[0]);break;case i.OPS.showSpacedText:this.showText(j[0]);break;case i.OPS.endText:this.endText();break;case i.OPS.moveText:this.moveText(j[0],j[1]);break;case i.OPS.setCharSpacing:this.setCharSpacing(j[0]);break;case i.OPS.setWordSpacing:this.setWordSpacing(j[0]);break;case i.OPS.setHScale:this.setHScale(j[0]);break;case i.OPS.setTextMatrix:this.setTextMatrix(j[0],j[1],j[2],j[3],j[4],j[5]);break;case i.OPS.setTextRise:this.setTextRise(j[0]);break;case i.OPS.setTextRenderingMode:this.setTextRenderingMode(j[0]);break;case i.OPS.setLineWidth:this.setLineWidth(j[0]);break;case i.OPS.setLineJoin:this.setLineJoin(j[0]);break;case i.OPS.setLineCap:this.setLineCap(j[0]);break;case i.OPS.setMiterLimit:this.setMiterLimit(j[0]);break;case i.OPS.setFillRGBColor:this.setFillRGBColor(j[0],j[1],j[2]);break;case i.OPS.setStrokeRGBColor:this.setStrokeRGBColor(j[0],j[1],j[2]);break;case i.OPS.setStrokeColorN:this.setStrokeColorN(j);break;case i.OPS.setFillColorN:this.setFillColorN(j);break;case i.OPS.shadingFill:this.shadingFill(j[0]);break;case i.OPS.setDash:this.setDash(j[0],j[1]);break;case i.OPS.setRenderingIntent:this.setRenderingIntent(j[0]);break;case i.OPS.setFlatness:this.setFlatness(j[0]);break;case i.OPS.setGState:this.setGState(j[0]);break;case i.OPS.fill:this.fill();break;case i.OPS.eoFill:this.eoFill();break;case i.OPS.stroke:this.stroke();break;case i.OPS.fillStroke:this.fillStroke();break;case i.OPS.eoFillStroke:this.eoFillStroke();break;case i.OPS.clip:this.clip("nonzero");break;case i.OPS.eoClip:this.clip("evenodd");break;case i.OPS.paintSolidColorImageMask:this.paintSolidColorImageMask();break;case i.OPS.paintImageXObject:this.paintImageXObject(j[0]);break;case i.OPS.paintInlineImageXObject:this.paintInlineImageXObject(j[0]);break;case i.OPS.paintImageMaskXObject:this.paintImageMaskXObject(j[0]);break;case i.OPS.paintFormXObjectBegin:this.paintFormXObjectBegin(j[0],j[1]);break;case i.OPS.paintFormXObjectEnd:this.paintFormXObjectEnd();break;case i.OPS.closePath:this.closePath();break;case i.OPS.closeStroke:this.closeStroke();break;case i.OPS.closeFillStroke:this.closeFillStroke();break;case i.OPS.closeEOFillStroke:this.closeEOFillStroke();break;case i.OPS.nextLine:this.nextLine();break;case i.OPS.transform:this.transform(j[0],j[1],j[2],j[3],j[4],j[5]);break;case i.OPS.constructPath:this.constructPath(j[0],j[1]);break;case i.OPS.endPath:this.endPath();break;case 92:this.group(T.items);break;default:(0,i.warn)(`Unimplemented operator ${I}`);break}}}setWordSpacing(E){this.current.wordSpacing=E}setCharSpacing(E){this.current.charSpacing=E}nextLine(){this.moveText(0,this.current.leading)}setTextMatrix(E,T,I,M,j,U){let B=this.current;B.textMatrix=B.lineMatrix=[E,T,I,M,j,U],B.textMatrixScale=Math.hypot(E,T),B.x=B.lineX=0,B.y=B.lineY=0,B.xcoords=[],B.ycoords=[],B.tspan=this.svgFactory.createElement("svg:tspan"),B.tspan.setAttributeNS(null,"font-family",B.fontFamily),B.tspan.setAttributeNS(null,"font-size",`${g(B.fontSize)}px`),B.tspan.setAttributeNS(null,"y",g(-B.y)),B.txtElement=this.svgFactory.createElement("svg:text"),B.txtElement.appendChild(B.tspan)}beginText(){let E=this.current;E.x=E.lineX=0,E.y=E.lineY=0,E.textMatrix=i.IDENTITY_MATRIX,E.lineMatrix=i.IDENTITY_MATRIX,E.textMatrixScale=1,E.tspan=this.svgFactory.createElement("svg:tspan"),E.txtElement=this.svgFactory.createElement("svg:text"),E.txtgrp=this.svgFactory.createElement("svg:g"),E.xcoords=[],E.ycoords=[]}moveText(E,T){let I=this.current;I.x=I.lineX+=E,I.y=I.lineY+=T,I.xcoords=[],I.ycoords=[],I.tspan=this.svgFactory.createElement("svg:tspan"),I.tspan.setAttributeNS(null,"font-family",I.fontFamily),I.tspan.setAttributeNS(null,"font-size",`${g(I.fontSize)}px`),I.tspan.setAttributeNS(null,"y",g(-I.y))}showText(E){let T=this.current,I=T.font,M=T.fontSize;if(M===0)return;let j=T.fontSizeScale,U=T.charSpacing,B=T.wordSpacing,N=T.fontDirection,q=T.textHScale*N,z=I.vertical,ne=z?1:-1,oe=I.defaultVMetrics,ae=M*T.fontMatrix[0],te=0;for(let fe of E){if(fe===null){te+=N*B;continue}else if(typeof fe=="number"){te+=ne*fe*M/1e3;continue}let J=(fe.isSpace?B:0)+U,D=fe.fontChar,k,x,R=fe.width;if(z){let F,W=fe.vmetric||oe;F=fe.vmetric?W[1]:R*.5,F=-F*ae;let V=W[2]*ae;R=W?-W[0]:R,k=F/j,x=(te+V)/j}else k=te/j,x=0;(fe.isInFont||I.missingFile)&&(T.xcoords.push(T.x+k),z&&T.ycoords.push(-T.y+x),T.tspan.textContent+=D);let L;z?L=R*ae-J*N:L=R*ae+J*N,te+=L}T.tspan.setAttributeNS(null,"x",T.xcoords.map(g).join(" ")),z?T.tspan.setAttributeNS(null,"y",T.ycoords.map(g).join(" ")):T.tspan.setAttributeNS(null,"y",g(-T.y)),z?T.y-=te:T.x+=te*q,T.tspan.setAttributeNS(null,"font-family",T.fontFamily),T.tspan.setAttributeNS(null,"font-size",`${g(T.fontSize)}px`),T.fontStyle!==u.fontStyle&&T.tspan.setAttributeNS(null,"font-style",T.fontStyle),T.fontWeight!==u.fontWeight&&T.tspan.setAttributeNS(null,"font-weight",T.fontWeight);let le=T.textRenderingMode&i.TextRenderingMode.FILL_STROKE_MASK;if(le===i.TextRenderingMode.FILL||le===i.TextRenderingMode.FILL_STROKE?(T.fillColor!==u.fillColor&&T.tspan.setAttributeNS(null,"fill",T.fillColor),T.fillAlpha<1&&T.tspan.setAttributeNS(null,"fill-opacity",T.fillAlpha)):T.textRenderingMode===i.TextRenderingMode.ADD_TO_PATH?T.tspan.setAttributeNS(null,"fill","transparent"):T.tspan.setAttributeNS(null,"fill","none"),le===i.TextRenderingMode.STROKE||le===i.TextRenderingMode.FILL_STROKE){let fe=1/(T.textMatrixScale||1);this._setStrokeAttributes(T.tspan,fe)}let xe=T.textMatrix;T.textRise!==0&&(xe=xe.slice(),xe[5]+=T.textRise),T.txtElement.setAttributeNS(null,"transform",`${v(xe)} scale(${g(q)}, -1)`),T.txtElement.setAttributeNS(d,"xml:space","preserve"),T.txtElement.appendChild(T.tspan),T.txtgrp.appendChild(T.txtElement),this._ensureTransformGroup().appendChild(T.txtElement)}setLeadingMoveText(E,T){this.setLeading(-T),this.moveText(E,T)}addFontStyle(E){if(!E.data)throw new Error('addFontStyle: No font data available, ensure that the "fontExtraProperties" API parameter is set.');this.cssStyle||(this.cssStyle=this.svgFactory.createElement("svg:style"),this.cssStyle.setAttributeNS(null,"type","text/css"),this.defs.appendChild(this.cssStyle));let T=w(E.data,E.mimetype,this.forceDataSchema);this.cssStyle.textContent+=`@font-face { font-family: "${E.loadedName}"; src: url(${T}); }
|
|
70
|
-
`}setFont(E){let T=this.current,I=this.commonObjs.get(E[0]),M=E[1];T.font=I,this.embedFonts&&!I.missingFile&&!this.embeddedFonts[I.loadedName]&&(this.addFontStyle(I),this.embeddedFonts[I.loadedName]=I),T.fontMatrix=I.fontMatrix||i.FONT_IDENTITY_MATRIX;let j="normal";I.black?j="900":I.bold&&(j="bold");let U=I.italic?"italic":"normal";M<0?(M=-M,T.fontDirection=-1):T.fontDirection=1,T.fontSize=M,T.fontFamily=I.loadedName,T.fontWeight=j,T.fontStyle=U,T.tspan=this.svgFactory.createElement("svg:tspan"),T.tspan.setAttributeNS(null,"y",g(-T.y)),T.xcoords=[],T.ycoords=[]}endText(){let E=this.current;E.textRenderingMode&i.TextRenderingMode.ADD_TO_PATH_FLAG&&E.txtElement?.hasChildNodes()&&(E.element=E.txtElement,this.clip("nonzero"),this.endPath())}setLineWidth(E){E>0&&(this.current.lineWidth=E)}setLineCap(E){this.current.lineCap=y[E]}setLineJoin(E){this.current.lineJoin=b[E]}setMiterLimit(E){this.current.miterLimit=E}setStrokeAlpha(E){this.current.strokeAlpha=E}setStrokeRGBColor(E,T,I){this.current.strokeColor=i.Util.makeHexColor(E,T,I)}setFillAlpha(E){this.current.fillAlpha=E}setFillRGBColor(E,T,I){this.current.fillColor=i.Util.makeHexColor(E,T,I),this.current.tspan=this.svgFactory.createElement("svg:tspan"),this.current.xcoords=[],this.current.ycoords=[]}setStrokeColorN(E){this.current.strokeColor=this._makeColorN_Pattern(E)}setFillColorN(E){this.current.fillColor=this._makeColorN_Pattern(E)}shadingFill(E){let T=this.viewport.width,I=this.viewport.height,M=i.Util.inverseTransform(this.transformMatrix),j=i.Util.applyTransform([0,0],M),U=i.Util.applyTransform([0,I],M),B=i.Util.applyTransform([T,0],M),N=i.Util.applyTransform([T,I],M),q=Math.min(j[0],U[0],B[0],N[0]),z=Math.min(j[1],U[1],B[1],N[1]),ne=Math.max(j[0],U[0],B[0],N[0]),oe=Math.max(j[1],U[1],B[1],N[1]),ae=this.svgFactory.createElement("svg:rect");ae.setAttributeNS(null,"x",q),ae.setAttributeNS(null,"y",z),ae.setAttributeNS(null,"width",ne-q),ae.setAttributeNS(null,"height",oe-z),ae.setAttributeNS(null,"fill",this._makeShadingPattern(E)),this.current.fillAlpha<1&&ae.setAttributeNS(null,"fill-opacity",this.current.fillAlpha),this._ensureTransformGroup().appendChild(ae)}_makeColorN_Pattern(E){return E[0]==="TilingPattern"?this._makeTilingPattern(E):this._makeShadingPattern(E)}_makeTilingPattern(E){let T=E[1],I=E[2],M=E[3]||i.IDENTITY_MATRIX,[j,U,B,N]=E[4],q=E[5],z=E[6],ne=E[7],oe=`shading${O++}`,[ae,te,le,xe]=i.Util.normalizeRect([...i.Util.applyTransform([j,U],M),...i.Util.applyTransform([B,N],M)]),[fe,J]=i.Util.singularValueDecompose2dScale(M),D=q*fe,k=z*J,x=this.svgFactory.createElement("svg:pattern");x.setAttributeNS(null,"id",oe),x.setAttributeNS(null,"patternUnits","userSpaceOnUse"),x.setAttributeNS(null,"width",D),x.setAttributeNS(null,"height",k),x.setAttributeNS(null,"x",`${ae}`),x.setAttributeNS(null,"y",`${te}`);let R=this.svg,L=this.transformMatrix,F=this.current.fillColor,W=this.current.strokeColor,V=this.svgFactory.create(le-ae,xe-te);if(this.svg=V,this.transformMatrix=M,ne===2){let Z=i.Util.makeHexColor(...T);this.current.fillColor=Z,this.current.strokeColor=Z}return this.executeOpTree(this.convertOpList(I)),this.svg=R,this.transformMatrix=L,this.current.fillColor=F,this.current.strokeColor=W,x.appendChild(V.childNodes[0]),this.defs.appendChild(x),`url(#${oe})`}_makeShadingPattern(E){switch(typeof E=="string"&&(E=this.objs.get(E)),E[0]){case"RadialAxial":let T=`shading${O++}`,I=E[3],M;switch(E[1]){case"axial":let j=E[4],U=E[5];M=this.svgFactory.createElement("svg:linearGradient"),M.setAttributeNS(null,"id",T),M.setAttributeNS(null,"gradientUnits","userSpaceOnUse"),M.setAttributeNS(null,"x1",j[0]),M.setAttributeNS(null,"y1",j[1]),M.setAttributeNS(null,"x2",U[0]),M.setAttributeNS(null,"y2",U[1]);break;case"radial":let B=E[4],N=E[5],q=E[6],z=E[7];M=this.svgFactory.createElement("svg:radialGradient"),M.setAttributeNS(null,"id",T),M.setAttributeNS(null,"gradientUnits","userSpaceOnUse"),M.setAttributeNS(null,"cx",N[0]),M.setAttributeNS(null,"cy",N[1]),M.setAttributeNS(null,"r",z),M.setAttributeNS(null,"fx",B[0]),M.setAttributeNS(null,"fy",B[1]),M.setAttributeNS(null,"fr",q);break;default:throw new Error(`Unknown RadialAxial type: ${E[1]}`)}for(let j of I){let U=this.svgFactory.createElement("svg:stop");U.setAttributeNS(null,"offset",j[0]),U.setAttributeNS(null,"stop-color",j[1]),M.appendChild(U)}return this.defs.appendChild(M),`url(#${T})`;case"Mesh":return(0,i.warn)("Unimplemented pattern Mesh"),null;case"Dummy":return"hotpink";default:throw new Error(`Unknown IR type: ${E[0]}`)}}setDash(E,T){this.current.dashArray=E,this.current.dashPhase=T}constructPath(E,T){let I=this.current,M=I.x,j=I.y,U=[],B=0;for(let N of E)switch(N|0){case i.OPS.rectangle:M=T[B++],j=T[B++];let q=T[B++],z=T[B++],ne=M+q,oe=j+z;U.push("M",g(M),g(j),"L",g(ne),g(j),"L",g(ne),g(oe),"L",g(M),g(oe),"Z");break;case i.OPS.moveTo:M=T[B++],j=T[B++],U.push("M",g(M),g(j));break;case i.OPS.lineTo:M=T[B++],j=T[B++],U.push("L",g(M),g(j));break;case i.OPS.curveTo:M=T[B+4],j=T[B+5],U.push("C",g(T[B]),g(T[B+1]),g(T[B+2]),g(T[B+3]),g(M),g(j)),B+=6;break;case i.OPS.curveTo2:U.push("C",g(M),g(j),g(T[B]),g(T[B+1]),g(T[B+2]),g(T[B+3])),M=T[B+2],j=T[B+3],B+=4;break;case i.OPS.curveTo3:M=T[B+2],j=T[B+3],U.push("C",g(T[B]),g(T[B+1]),g(M),g(j),g(M),g(j)),B+=4;break;case i.OPS.closePath:U.push("Z");break}U=U.join(" "),I.path&&E.length>0&&E[0]!==i.OPS.rectangle&&E[0]!==i.OPS.moveTo?U=I.path.getAttributeNS(null,"d")+U:(I.path=this.svgFactory.createElement("svg:path"),this._ensureTransformGroup().appendChild(I.path)),I.path.setAttributeNS(null,"d",U),I.path.setAttributeNS(null,"fill","none"),I.element=I.path,I.setCurrentPoint(M,j)}endPath(){let E=this.current;if(E.path=null,!this.pendingClip)return;if(!E.element){this.pendingClip=null;return}let T=`clippath${A++}`,I=this.svgFactory.createElement("svg:clipPath");I.setAttributeNS(null,"id",T),I.setAttributeNS(null,"transform",v(this.transformMatrix));let M=E.element.cloneNode(!0);if(this.pendingClip==="evenodd"?M.setAttributeNS(null,"clip-rule","evenodd"):M.setAttributeNS(null,"clip-rule","nonzero"),this.pendingClip=null,I.appendChild(M),this.defs.appendChild(I),E.activeClipUrl){E.clipGroup=null;for(let j of this.extraStack)j.clipGroup=null;I.setAttributeNS(null,"clip-path",E.activeClipUrl)}E.activeClipUrl=`url(#${T})`,this.tgrp=null}clip(E){this.pendingClip=E}closePath(){let E=this.current;if(E.path){let T=`${E.path.getAttributeNS(null,"d")}Z`;E.path.setAttributeNS(null,"d",T)}}setLeading(E){this.current.leading=-E}setTextRise(E){this.current.textRise=E}setTextRenderingMode(E){this.current.textRenderingMode=E}setHScale(E){this.current.textHScale=E/100}setRenderingIntent(E){}setFlatness(E){}setGState(E){for(let[T,I]of E)switch(T){case"LW":this.setLineWidth(I);break;case"LC":this.setLineCap(I);break;case"LJ":this.setLineJoin(I);break;case"ML":this.setMiterLimit(I);break;case"D":this.setDash(I[0],I[1]);break;case"RI":this.setRenderingIntent(I);break;case"FL":this.setFlatness(I);break;case"Font":this.setFont(I);break;case"CA":this.setStrokeAlpha(I);break;case"ca":this.setFillAlpha(I);break;default:(0,i.warn)(`Unimplemented graphic state operator ${T}`);break}}fill(){let E=this.current;E.element&&(E.element.setAttributeNS(null,"fill",E.fillColor),E.element.setAttributeNS(null,"fill-opacity",E.fillAlpha),this.endPath())}stroke(){let E=this.current;E.element&&(this._setStrokeAttributes(E.element),E.element.setAttributeNS(null,"fill","none"),this.endPath())}_setStrokeAttributes(E,T=1){let I=this.current,M=I.dashArray;T!==1&&M.length>0&&(M=M.map(function(j){return T*j})),E.setAttributeNS(null,"stroke",I.strokeColor),E.setAttributeNS(null,"stroke-opacity",I.strokeAlpha),E.setAttributeNS(null,"stroke-miterlimit",g(I.miterLimit)),E.setAttributeNS(null,"stroke-linecap",I.lineCap),E.setAttributeNS(null,"stroke-linejoin",I.lineJoin),E.setAttributeNS(null,"stroke-width",g(T*I.lineWidth)+"px"),E.setAttributeNS(null,"stroke-dasharray",M.map(g).join(" ")),E.setAttributeNS(null,"stroke-dashoffset",g(T*I.dashPhase)+"px")}eoFill(){this.current.element&&this.current.element.setAttributeNS(null,"fill-rule","evenodd"),this.fill()}fillStroke(){this.stroke(),this.fill()}eoFillStroke(){this.current.element&&this.current.element.setAttributeNS(null,"fill-rule","evenodd"),this.fillStroke()}closeStroke(){this.closePath(),this.stroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.closePath(),this.eoFillStroke()}paintSolidColorImageMask(){let E=this.svgFactory.createElement("svg:rect");E.setAttributeNS(null,"x","0"),E.setAttributeNS(null,"y","0"),E.setAttributeNS(null,"width","1px"),E.setAttributeNS(null,"height","1px"),E.setAttributeNS(null,"fill",this.current.fillColor),this._ensureTransformGroup().appendChild(E)}paintImageXObject(E){let T=E.startsWith("g_")?this.commonObjs.get(E):this.objs.get(E);if(!T){(0,i.warn)(`Dependent image with object ID ${E} is not ready yet`);return}this.paintInlineImageXObject(T)}paintInlineImageXObject(E,T){let I=E.width,M=E.height,j=p(E,this.forceDataSchema,!!T),U=this.svgFactory.createElement("svg:rect");U.setAttributeNS(null,"x","0"),U.setAttributeNS(null,"y","0"),U.setAttributeNS(null,"width",g(I)),U.setAttributeNS(null,"height",g(M)),this.current.element=U,this.clip("nonzero");let B=this.svgFactory.createElement("svg:image");B.setAttributeNS(h,"xlink:href",j),B.setAttributeNS(null,"x","0"),B.setAttributeNS(null,"y",g(-M)),B.setAttributeNS(null,"width",g(I)+"px"),B.setAttributeNS(null,"height",g(M)+"px"),B.setAttributeNS(null,"transform",`scale(${g(1/I)} ${g(-1/M)})`),T?T.appendChild(B):this._ensureTransformGroup().appendChild(B)}paintImageMaskXObject(E){let T=this.current,I=E.width,M=E.height,j=T.fillColor;T.maskId=`mask${C++}`;let U=this.svgFactory.createElement("svg:mask");U.setAttributeNS(null,"id",T.maskId);let B=this.svgFactory.createElement("svg:rect");B.setAttributeNS(null,"x","0"),B.setAttributeNS(null,"y","0"),B.setAttributeNS(null,"width",g(I)),B.setAttributeNS(null,"height",g(M)),B.setAttributeNS(null,"fill",j),B.setAttributeNS(null,"mask",`url(#${T.maskId})`),this.defs.appendChild(U),this._ensureTransformGroup().appendChild(B),this.paintInlineImageXObject(E,U)}paintFormXObjectBegin(E,T){if(Array.isArray(E)&&E.length===6&&this.transform(E[0],E[1],E[2],E[3],E[4],E[5]),T){let I=T[2]-T[0],M=T[3]-T[1],j=this.svgFactory.createElement("svg:rect");j.setAttributeNS(null,"x",T[0]),j.setAttributeNS(null,"y",T[1]),j.setAttributeNS(null,"width",g(I)),j.setAttributeNS(null,"height",g(M)),this.current.element=j,this.clip("nonzero"),this.endPath()}}paintFormXObjectEnd(){}_initialize(E){let T=this.svgFactory.create(E.width,E.height),I=this.svgFactory.createElement("svg:defs");T.appendChild(I),this.defs=I;let M=this.svgFactory.createElement("svg:g");return M.setAttributeNS(null,"transform",v(E.transform)),T.appendChild(M),this.svg=M,T}_ensureClipGroup(){if(!this.current.clipGroup){let E=this.svgFactory.createElement("svg:g");E.setAttributeNS(null,"clip-path",this.current.activeClipUrl),this.svg.appendChild(E),this.current.clipGroup=E}return this.current.clipGroup}_ensureTransformGroup(){return this.tgrp||(this.tgrp=this.svgFactory.createElement("svg:g"),this.tgrp.setAttributeNS(null,"transform",v(this.transformMatrix)),this.current.activeClipUrl?this._ensureClipGroup().appendChild(this.tgrp):this.svg.appendChild(this.tgrp)),this.tgrp}}}},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PDFNodeStream=void 0;var i=n(1),o=n(26);let a=vd(),l=ox(),u=sx(),d=bd(),h=/^file:\/\/\/[a-zA-Z]:\//;function y(C){let O=d.parse(C);return O.protocol==="file:"||O.host?O:/^[a-z]:[/\\]/i.test(C)?d.parse(`file:///${C}`):(O.host||(O.protocol="file:"),O)}class b{constructor(O){this.source=O,this.url=y(O.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.httpHeaders=this.isHttp&&O.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return(0,i.assert)(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new v(this):new f(this),this._fullRequestReader}getRangeReader(O,E){if(E<=this._progressiveDataLength)return null;let T=this.isFsUrl?new A(this,O,E):new g(this,O,E);return this._rangeRequestReaders.push(T),T}cancelAllRequests(O){this._fullRequestReader&&this._fullRequestReader.cancel(O);for(let E of this._rangeRequestReaders.slice(0))E.cancel(O)}}t.PDFNodeStream=b;class w{constructor(O){this._url=O.url,this._done=!1,this._storedError=null,this.onProgress=null;let E=O.source;this._contentLength=E.length,this._loaded=0,this._filename=null,this._disableRange=E.disableRange||!1,this._rangeChunkSize=E.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!E.disableStream,this._isRangeSupported=!E.disableRange,this._readableStream=null,this._readCapability=(0,i.createPromiseCapability)(),this._headersCapability=(0,i.createPromiseCapability)()}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let O=this._readableStream.read();return O===null?(this._readCapability=(0,i.createPromiseCapability)(),this.read()):(this._loaded+=O.length,this.onProgress&&this.onProgress({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(O).buffer,done:!1})}cancel(O){if(!this._readableStream){this._error(O);return}this._readableStream.destroy(O)}_error(O){this._storedError=O,this._readCapability.resolve()}_setReadableStream(O){this._readableStream=O,O.on("readable",()=>{this._readCapability.resolve()}),O.on("end",()=>{O.destroy(),this._done=!0,this._readCapability.resolve()}),O.on("error",E=>{this._error(E)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new i.AbortException("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class p{constructor(O){this._url=O.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=(0,i.createPromiseCapability)();let E=O.source;this._isStreamingSupported=!E.disableStream}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let O=this._readableStream.read();return O===null?(this._readCapability=(0,i.createPromiseCapability)(),this.read()):(this._loaded+=O.length,this.onProgress&&this.onProgress({loaded:this._loaded}),{value:new Uint8Array(O).buffer,done:!1})}cancel(O){if(!this._readableStream){this._error(O);return}this._readableStream.destroy(O)}_error(O){this._storedError=O,this._readCapability.resolve()}_setReadableStream(O){this._readableStream=O,O.on("readable",()=>{this._readCapability.resolve()}),O.on("end",()=>{O.destroy(),this._done=!0,this._readCapability.resolve()}),O.on("error",E=>{this._error(E)}),this._storedError&&this._readableStream.destroy(this._storedError)}}function m(C,O){return{protocol:C.protocol,auth:C.auth,host:C.hostname,port:C.port,path:C.path,method:"GET",headers:O}}class f extends w{constructor(O){super(O);let E=T=>{if(T.statusCode===404){let U=new i.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=U,this._headersCapability.reject(U);return}this._headersCapability.resolve(),this._setReadableStream(T);let I=U=>this._readableStream.headers[U.toLowerCase()],{allowRangeRequests:M,suggestedLength:j}=(0,o.validateRangeRequestCapabilities)({getResponseHeader:I,isHttp:O.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=M,this._contentLength=j||this._contentLength,this._filename=(0,o.extractFilenameFromHeader)(I)};this._request=null,this._url.protocol==="http:"?this._request=l.request(m(this._url,O.httpHeaders),E):this._request=u.request(m(this._url,O.httpHeaders),E),this._request.on("error",T=>{this._storedError=T,this._headersCapability.reject(T)}),this._request.end()}}class g extends p{constructor(O,E,T){super(O);this._httpHeaders={};for(let M in O.httpHeaders){let j=O.httpHeaders[M];typeof j!="undefined"&&(this._httpHeaders[M]=j)}this._httpHeaders.Range=`bytes=${E}-${T-1}`;let I=M=>{if(M.statusCode===404){let j=new i.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=j;return}this._setReadableStream(M)};this._request=null,this._url.protocol==="http:"?this._request=l.request(m(this._url,this._httpHeaders),I):this._request=u.request(m(this._url,this._httpHeaders),I),this._request.on("error",M=>{this._storedError=M}),this._request.end()}}class v extends w{constructor(O){super(O);let E=decodeURIComponent(this._url.path);h.test(this._url.href)&&(E=E.replace(/^\//,"")),a.lstat(E,(T,I)=>{if(T){T.code==="ENOENT"&&(T=new i.MissingPDFException(`Missing PDF "${E}".`)),this._storedError=T,this._headersCapability.reject(T);return}this._contentLength=I.size,this._setReadableStream(a.createReadStream(E)),this._headersCapability.resolve()})}}class A extends p{constructor(O,E,T){super(O);let I=decodeURIComponent(this._url.path);h.test(this._url.href)&&(I=I.replace(/^\//,"")),this._setReadableStream(a.createReadStream(I,{start:E,end:T-1}))}}},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createResponseStatusError=d,t.extractFilenameFromHeader=u,t.validateRangeRequestCapabilities=l,t.validateResponseStatus=h;var i=n(1),o=n(27),a=n(5);function l({getResponseHeader:y,isHttp:b,rangeChunkSize:w,disableRange:p}){let m={allowRangeRequests:!1,suggestedLength:void 0},f=parseInt(y("Content-Length"),10);return!Number.isInteger(f)||(m.suggestedLength=f,f<=2*w)||p||!b||y("Accept-Ranges")!=="bytes"||(y("Content-Encoding")||"identity")!=="identity"||(m.allowRangeRequests=!0),m}function u(y){let b=y("Content-Disposition");if(b){let w=(0,o.getFilenameFromContentDispositionHeader)(b);if(w.includes("%"))try{w=decodeURIComponent(w)}catch(p){}if((0,a.isPdfFile)(w))return w}return null}function d(y,b){return y===404||y===0&&b.startsWith("file:")?new i.MissingPDFException('Missing PDF "'+b+'".'):new i.UnexpectedResponseException(`Unexpected server response (${y}) while retrieving PDF "${b}".`,y)}function h(y){return y===200||y===206}},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getFilenameFromContentDispositionHeader=o;var i=n(1);function o(a){let l=!0,u=d("filename\\*","i").exec(a);if(u){u=u[1];let f=w(u);return f=unescape(f),f=p(f),f=m(f),y(f)}if(u=b(a),u){let f=m(u);return y(f)}if(u=d("filename","i").exec(a),u){u=u[1];let f=w(u);return f=m(f),y(f)}function d(f,g){return new RegExp("(?:^|;)\\s*"+f+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',g)}function h(f,g){if(f){if(!/^[\x00-\xFF]+$/.test(g))return g;try{let v=new TextDecoder(f,{fatal:!0}),A=(0,i.stringToBytes)(g);g=v.decode(A),l=!1}catch(v){}}return g}function y(f){return l&&/[\x80-\xff]/.test(f)&&(f=h("utf-8",f),l&&(f=h("iso-8859-1",f))),f}function b(f){let g=[],v,A=d("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(v=A.exec(f))!==null;){let[,O,E,T]=v;if(O=parseInt(O,10),O in g){if(O===0)break;continue}g[O]=[E,T]}let C=[];for(let O=0;O<g.length&&O in g;++O){let[E,T]=g[O];T=w(T),E&&(T=unescape(T),O===0&&(T=p(T))),C.push(T)}return C.join("")}function w(f){if(f.startsWith('"')){let g=f.slice(1).split('\\"');for(let v=0;v<g.length;++v){let A=g[v].indexOf('"');A!==-1&&(g[v]=g[v].slice(0,A),g.length=v+1),g[v]=g[v].replace(/\\(.)/g,"$1")}f=g.join('"')}return f}function p(f){let g=f.indexOf("'");if(g===-1)return f;let v=f.slice(0,g),C=f.slice(g+1).replace(/^[^']*'/,"");return h(v,C)}function m(f){return!f.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(f)?f:f.replace(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(g,v,A,C){if(A==="q"||A==="Q")return C=C.replace(/_/g," "),C=C.replace(/=([0-9a-fA-F]{2})/g,function(O,E){return String.fromCharCode(parseInt(E,16))}),h(v,C);try{C=atob(C)}catch(O){}return h(v,C)})}return""}},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PDFNetworkStream=void 0;var i=n(1),o=n(26);let a=200,l=206;function u(w){let p=w.response;return typeof p!="string"?p:(0,i.stringToBytes)(p).buffer}class d{constructor(p,m={}){this.url=p,this.isHttp=/^https?:/i.test(p),this.httpHeaders=this.isHttp&&m.httpHeaders||Object.create(null),this.withCredentials=m.withCredentials||!1,this.getXhr=m.getXhr||function(){return new XMLHttpRequest},this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(p,m,f){let g={begin:p,end:m};for(let v in f)g[v]=f[v];return this.request(g)}requestFull(p){return this.request(p)}request(p){let m=this.getXhr(),f=this.currXhrId++,g=this.pendingRequests[f]={xhr:m};m.open("GET",this.url),m.withCredentials=this.withCredentials;for(let v in this.httpHeaders){let A=this.httpHeaders[v];typeof A!="undefined"&&m.setRequestHeader(v,A)}return this.isHttp&&"begin"in p&&"end"in p?(m.setRequestHeader("Range",`bytes=${p.begin}-${p.end-1}`),g.expectedStatus=l):g.expectedStatus=a,m.responseType="arraybuffer",p.onError&&(m.onerror=function(v){p.onError(m.status)}),m.onreadystatechange=this.onStateChange.bind(this,f),m.onprogress=this.onProgress.bind(this,f),g.onHeadersReceived=p.onHeadersReceived,g.onDone=p.onDone,g.onError=p.onError,g.onProgress=p.onProgress,m.send(null),f}onProgress(p,m){let f=this.pendingRequests[p];!f||f.onProgress?.(m)}onStateChange(p,m){let f=this.pendingRequests[p];if(!f)return;let g=f.xhr;if(g.readyState>=2&&f.onHeadersReceived&&(f.onHeadersReceived(),delete f.onHeadersReceived),g.readyState!==4||!(p in this.pendingRequests))return;if(delete this.pendingRequests[p],g.status===0&&this.isHttp){f.onError?.(g.status);return}let v=g.status||a;if(!(v===a&&f.expectedStatus===l)&&v!==f.expectedStatus){f.onError?.(g.status);return}let C=u(g);if(v===l){let O=g.getResponseHeader("Content-Range"),E=/bytes (\d+)-(\d+)\/(\d+)/.exec(O);f.onDone({begin:parseInt(E[1],10),chunk:C})}else C?f.onDone({begin:0,chunk:C}):f.onError?.(g.status)}getRequestXhr(p){return this.pendingRequests[p].xhr}isPendingRequest(p){return p in this.pendingRequests}abortRequest(p){let m=this.pendingRequests[p].xhr;delete this.pendingRequests[p],m.abort()}}class h{constructor(p){this._source=p,this._manager=new d(p.url,{httpHeaders:p.httpHeaders,withCredentials:p.withCredentials}),this._rangeChunkSize=p.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(p){let m=this._rangeRequestReaders.indexOf(p);m>=0&&this._rangeRequestReaders.splice(m,1)}getFullReader(){return(0,i.assert)(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new y(this._manager,this._source),this._fullRequestReader}getRangeReader(p,m){let f=new b(this._manager,p,m);return f.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(f),f}cancelAllRequests(p){this._fullRequestReader?.cancel(p);for(let m of this._rangeRequestReaders.slice(0))m.cancel(p)}}t.PDFNetworkStream=h;class y{constructor(p,m){this._manager=p;let f={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=m.url,this._fullRequestId=p.requestFull(f),this._headersReceivedCapability=(0,i.createPromiseCapability)(),this._disableRange=m.disableRange||!1,this._contentLength=m.length,this._rangeChunkSize=m.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){let p=this._fullRequestId,m=this._manager.getRequestXhr(p),f=A=>m.getResponseHeader(A),{allowRangeRequests:g,suggestedLength:v}=(0,o.validateRangeRequestCapabilities)({getResponseHeader:f,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});g&&(this._isRangeSupported=!0),this._contentLength=v||this._contentLength,this._filename=(0,o.extractFilenameFromHeader)(f),this._isRangeSupported&&this._manager.abortRequest(p),this._headersReceivedCapability.resolve()}_onDone(p){if(p&&(this._requests.length>0?this._requests.shift().resolve({value:p.chunk,done:!1}):this._cachedChunks.push(p.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(let m of this._requests)m.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(p){this._storedError=(0,o.createResponseStatusError)(p,this._url),this._headersReceivedCapability.reject(this._storedError);for(let m of this._requests)m.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(p){this.onProgress?.({loaded:p.loaded,total:p.lengthComputable?p.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersReceivedCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let p=(0,i.createPromiseCapability)();return this._requests.push(p),p.promise}cancel(p){this._done=!0,this._headersReceivedCapability.reject(p);for(let m of this._requests)m.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class b{constructor(p,m,f){this._manager=p;let g={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=p.url,this._requestId=p.requestRange(m,f,g),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_close(){this.onClosed?.(this)}_onDone(p){let m=p.chunk;this._requests.length>0?this._requests.shift().resolve({value:m,done:!1}):this._queuedChunk=m,this._done=!0;for(let f of this._requests)f.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(p){this._storedError=(0,o.createResponseStatusError)(p,this._url);for(let m of this._requests)m.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(p){this.isStreamingSupported||this.onProgress?.({loaded:p.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){let m=this._queuedChunk;return this._queuedChunk=null,{value:m,done:!1}}if(this._done)return{value:void 0,done:!0};let p=(0,i.createPromiseCapability)();return this._requests.push(p),p.promise}cancel(p){this._done=!0;for(let m of this._requests)m.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PDFFetchStream=void 0;var i=n(1),o=n(26);function a(y,b,w){return{method:"GET",headers:y,signal:w?.signal,mode:"cors",credentials:b?"include":"same-origin",redirect:"follow"}}function l(y){let b=new Headers;for(let w in y){let p=y[w];typeof p!="undefined"&&b.append(w,p)}return b}class u{constructor(b){this.source=b,this.isHttp=/^https?:/i.test(b.url),this.httpHeaders=this.isHttp&&b.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return(0,i.assert)(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new d(this),this._fullRequestReader}getRangeReader(b,w){if(w<=this._progressiveDataLength)return null;let p=new h(this,b,w);return this._rangeRequestReaders.push(p),p}cancelAllRequests(b){this._fullRequestReader&&this._fullRequestReader.cancel(b);for(let w of this._rangeRequestReaders.slice(0))w.cancel(b)}}t.PDFFetchStream=u;class d{constructor(b){this._stream=b,this._reader=null,this._loaded=0,this._filename=null;let w=b.source;this._withCredentials=w.withCredentials||!1,this._contentLength=w.length,this._headersCapability=(0,i.createPromiseCapability)(),this._disableRange=w.disableRange||!1,this._rangeChunkSize=w.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),typeof AbortController!="undefined"&&(this._abortController=new AbortController),this._isStreamingSupported=!w.disableStream,this._isRangeSupported=!w.disableRange,this._headers=l(this._stream.httpHeaders);let p=w.url;fetch(p,a(this._headers,this._withCredentials,this._abortController)).then(m=>{if(!(0,o.validateResponseStatus)(m.status))throw(0,o.createResponseStatusError)(m.status,p);this._reader=m.body.getReader(),this._headersCapability.resolve();let f=A=>m.headers.get(A),{allowRangeRequests:g,suggestedLength:v}=(0,o.validateRangeRequestCapabilities)({getResponseHeader:f,isHttp:this._stream.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=g,this._contentLength=v||this._contentLength,this._filename=(0,o.extractFilenameFromHeader)(f),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new i.AbortException("Streaming is disabled."))}).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;let{value:b,done:w}=await this._reader.read();return w?{value:b,done:w}:(this._loaded+=b.byteLength,this.onProgress&&this.onProgress({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(b).buffer,done:!1})}cancel(b){this._reader&&this._reader.cancel(b),this._abortController&&this._abortController.abort()}}class h{constructor(b,w,p){this._stream=b,this._reader=null,this._loaded=0;let m=b.source;this._withCredentials=m.withCredentials||!1,this._readCapability=(0,i.createPromiseCapability)(),this._isStreamingSupported=!m.disableStream,typeof AbortController!="undefined"&&(this._abortController=new AbortController),this._headers=l(this._stream.httpHeaders),this._headers.append("Range",`bytes=${w}-${p-1}`);let f=m.url;fetch(f,a(this._headers,this._withCredentials,this._abortController)).then(g=>{if(!(0,o.validateResponseStatus)(g.status))throw(0,o.createResponseStatusError)(g.status,f);this._readCapability.resolve(),this._reader=g.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;let{value:b,done:w}=await this._reader.read();return w?{value:b,done:w}:(this._loaded+=b.byteLength,this.onProgress&&this.onProgress({loaded:this._loaded}),{value:new Uint8Array(b).buffer,done:!1})}cancel(b){this._reader&&this._reader.cancel(b),this._abortController&&this._abortController.abort()}}}],__webpack_module_cache__={};function __w_pdfjs_require__(r){var t=__webpack_module_cache__[r];if(t!==void 0)return t.exports;var n=__webpack_module_cache__[r]={exports:{}};return __webpack_modules__[r](n,n.exports,__w_pdfjs_require__),n.exports}var __webpack_exports__={};return(()=>{var r=__webpack_exports__;Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"AnnotationLayer",{enumerable:!0,get:function(){return o.AnnotationLayer}}),Object.defineProperty(r,"AnnotationMode",{enumerable:!0,get:function(){return t.AnnotationMode}}),Object.defineProperty(r,"CMapCompressionType",{enumerable:!0,get:function(){return t.CMapCompressionType}}),Object.defineProperty(r,"GlobalWorkerOptions",{enumerable:!0,get:function(){return a.GlobalWorkerOptions}}),Object.defineProperty(r,"InvalidPDFException",{enumerable:!0,get:function(){return t.InvalidPDFException}}),Object.defineProperty(r,"LoopbackPort",{enumerable:!0,get:function(){return n.LoopbackPort}}),Object.defineProperty(r,"MissingPDFException",{enumerable:!0,get:function(){return t.MissingPDFException}}),Object.defineProperty(r,"OPS",{enumerable:!0,get:function(){return t.OPS}}),Object.defineProperty(r,"PDFDataRangeTransport",{enumerable:!0,get:function(){return n.PDFDataRangeTransport}}),Object.defineProperty(r,"PDFDateString",{enumerable:!0,get:function(){return i.PDFDateString}}),Object.defineProperty(r,"PDFWorker",{enumerable:!0,get:function(){return n.PDFWorker}}),Object.defineProperty(r,"PasswordResponses",{enumerable:!0,get:function(){return t.PasswordResponses}}),Object.defineProperty(r,"PermissionFlag",{enumerable:!0,get:function(){return t.PermissionFlag}}),Object.defineProperty(r,"PixelsPerInch",{enumerable:!0,get:function(){return i.PixelsPerInch}}),Object.defineProperty(r,"RenderingCancelledException",{enumerable:!0,get:function(){return i.RenderingCancelledException}}),Object.defineProperty(r,"SVGGraphics",{enumerable:!0,get:function(){return d.SVGGraphics}}),Object.defineProperty(r,"UNSUPPORTED_FEATURES",{enumerable:!0,get:function(){return t.UNSUPPORTED_FEATURES}}),Object.defineProperty(r,"UnexpectedResponseException",{enumerable:!0,get:function(){return t.UnexpectedResponseException}}),Object.defineProperty(r,"Util",{enumerable:!0,get:function(){return t.Util}}),Object.defineProperty(r,"VerbosityLevel",{enumerable:!0,get:function(){return t.VerbosityLevel}}),Object.defineProperty(r,"XfaLayer",{enumerable:!0,get:function(){return h.XfaLayer}}),Object.defineProperty(r,"build",{enumerable:!0,get:function(){return n.build}}),Object.defineProperty(r,"createPromiseCapability",{enumerable:!0,get:function(){return t.createPromiseCapability}}),Object.defineProperty(r,"createValidAbsoluteUrl",{enumerable:!0,get:function(){return t.createValidAbsoluteUrl}}),Object.defineProperty(r,"getDocument",{enumerable:!0,get:function(){return n.getDocument}}),Object.defineProperty(r,"getFilenameFromUrl",{enumerable:!0,get:function(){return i.getFilenameFromUrl}}),Object.defineProperty(r,"getPdfFilenameFromUrl",{enumerable:!0,get:function(){return i.getPdfFilenameFromUrl}}),Object.defineProperty(r,"getXfaPageViewport",{enumerable:!0,get:function(){return i.getXfaPageViewport}}),Object.defineProperty(r,"isPdfFile",{enumerable:!0,get:function(){return i.isPdfFile}}),Object.defineProperty(r,"loadScript",{enumerable:!0,get:function(){return i.loadScript}}),Object.defineProperty(r,"renderTextLayer",{enumerable:!0,get:function(){return u.renderTextLayer}}),Object.defineProperty(r,"shadow",{enumerable:!0,get:function(){return t.shadow}}),Object.defineProperty(r,"version",{enumerable:!0,get:function(){return n.version}});var t=__w_pdfjs_require__(1),n=__w_pdfjs_require__(4),i=__w_pdfjs_require__(5),o=__w_pdfjs_require__(20),a=__w_pdfjs_require__(13),l=__w_pdfjs_require__(3),u=__w_pdfjs_require__(23),d=__w_pdfjs_require__(24),h=__w_pdfjs_require__(22);let y="2.14.305",b="eaaa8b4ad";if(l.isNodeJS){let{PDFNodeStream:w}=__w_pdfjs_require__(25);(0,n.setPDFNetworkStreamFactory)(p=>new w(p))}else{let{PDFNetworkStream:w}=__w_pdfjs_require__(28),{PDFFetchStream:p}=__w_pdfjs_require__(29);(0,n.setPDFNetworkStreamFactory)(m=>(0,i.isValidFetchUrl)(m.url)?new p(m):new w(m))}})(),__webpack_exports__})())});var U8={};BP(U8,{Link:()=>Ul,default:()=>F8,load:()=>H8});H();H();H();var dw=nt(cw()),hw=nt(Un());H();var uw=nt(Un());function Ks(r,t){return uw.TaJson.deserialize(r,t)}var bo=class extends dw.Publication{static async fromUrl(t,n){let o=await(await fetch(t.href,n)).json(),a=Ks(o,bo);return a.manifestUrl=t,a}get readingOrder(){return this.Spine??[]}get resources(){return this.Resources??[]}get tableOfContents(){return this.sample?.isSampleRead&&this.positions?.length>0?this.limitedTOC():this.TOC}limitedTOC(){function t(i){for(let o=0;o<i.Children.length;o++){let a=i.Children[o];a.Href=void 0,a.Children&&t(a)}}return this.TOC.map(i=>{if(i.Href){let o=this.positionsByHref(this.getRelativeHref(i.Href));if(o?.length>0){let a=o[0],l=Math.round(a.locations.totalProgression?a.locations.totalProgression:0*100);this.sample?.limit&&(l<=this.sample?.limit||(i.Href=void 0,i.Children&&t(i)))}}return i})}get landmarks(){return this.Landmarks}get pageList(){return this.PageList}get isFixedLayout(){return this.Metadata.Rendition?.Layout==="fixed"}get isReflowable(){return!this.isFixedLayout}get layout(){return this.isFixedLayout?"fixed":"reflowable"}get hasMediaOverlays(){return this.readingOrder?this.readingOrder.filter(t=>t.Properties?.MediaOverlay).length>0:!1}getStartLink(){if(this.readingOrder!==void 0&&this.readingOrder.length>0)return this.readingOrder[0]}getPreviousSpineItem(t){let n=this.getSpineIndex(t);if(n!==void 0&&this.readingOrder!==void 0&&n>0)return this.readingOrder[n-1]}getNextSpineItem(t){let n=this.getSpineIndex(t);if(n!==void 0&&this.readingOrder!==void 0&&n<this.readingOrder.length-1)return this.readingOrder[n+1]}getSpineItem(t){let n=this.getSpineIndex(t);if(n!==void 0&&this.readingOrder!==void 0)return this.readingOrder[n]}getSpineIndex(t){return this.readingOrder?.findIndex(n=>n.Href&&this.getAbsoluteHref(n.Href)===t)}getAbsoluteHref(t){return new URL(t,this.manifestUrl.href).href}getRelativeHref(t){let n=this.manifestUrl.href.replace("/manifest.json",""),i=t.replace(n,"");return i.indexOf("#")>0&&(i=i.slice(0,i.indexOf("#"))),i.charAt(0)==="/"&&(i=i.substring(1)),i}getTOCItemAbsolute(t){let n=this.getAbsoluteHref(t),i=(a,l)=>{for(let u=0;u<l.length;u++){let d=l[u];if(d.Href){let h=d.Href.indexOf("#")!==-1?d.Href.slice(0,d.Href.indexOf("#")):d.Href;if(this.getAbsoluteHref(h)===a)return d}if(d.Children){let h=i(a,d.Children);if(h!==void 0)return h}}},o=i(n,this.tableOfContents);return o===void 0&&this.readingOrder!==void 0&&(o=i(n,this.readingOrder)),o}getTOCItem(t){let n=(o,a)=>{for(let l=0;l<a.length;l++){let u=a[l];if(u.Href&&this.getAbsoluteHref(u.Href)===o)return u;if(u.Children){let d=n(o,u.Children);if(d!==void 0)return d}}},i=n(t,this.tableOfContents);if(i===void 0&&this.readingOrder!==void 0&&(i=n(t,this.readingOrder)),i===void 0&&t.indexOf("#")!==-1){let o=t.slice(0,t.indexOf("#"));i=n(o,this.tableOfContents),i===void 0&&this.readingOrder!==void 0&&(i=n(o,this.readingOrder))}return i}positionsByHref(t){let n=decodeURI(t)??"";return this.positions?.filter(i=>n.includes(i.href))}async autoGeneratePositions(t,n=ZL){let i=0,o=0,a=[];if(this.readingOrder!==void 0)for(let u of this.readingOrder)if(this.isFixedLayout){let d={href:u.Href,locations:{progression:0,position:i+1},type:u.TypeLink};a.push(d),i=i+1}else{let d=this.getAbsoluteHref(u.Href),h=await n(d,t);u.contentLength=h,o+=h;let b=Math.max(1,Math.ceil(h/1024));for(let w=0;w<b;w++){let p={href:u.Href,locations:{progression:w/b,position:i+(w+1)},type:u.TypeLink};a.push(p)}i=i+b}var l=0;if(this.isReflowable&&this.readingOrder!==void 0)for(let u of this.readingOrder){if(!u.contentLength){console.error("Link is missing contentLength",u);return}u.contentWeight=100/o*u.contentLength,l=l+u.contentWeight}for(let u of a){let d=a.filter(y=>y.href===decodeURI(u.href)),h=Math.ceil((u.locations.progression?u.locations.progression:0)*(d.length-1));u.locations.position&&(u.locations.totalProgression=(u.locations.position-1)/a.length),u.locations.remainingPositions=Math.abs(h-(d.length-1)),u.locations.position&&(u.locations.totalRemainingPositions=Math.abs(u.locations.position-1-(a.length-1)))}this.positions=a}async fetchPositionsFromService(t,n){let o=await(await fetch(t,n)).json();this.positions=o.positions}async fetchWeightsFromService(t,n){if(this.isFixedLayout){console.warn("Not fetching weights from service for fixed layout publication.");return}let o=await(await fetch(t,n)).json();this.readingOrder!==void 0&&this.readingOrder.forEach(a=>{a.contentWeight=o[a.Href]})}};bo=Lc([(0,hw.JsonObject)()],bo);var ZL=async(r,t)=>(await(await fetch(r,t)).blob()).size;H();H();var Ys=class{json(){return JSON.stringify(this)}},fw=class extends Ys{constructor(t,n,i){super();this.value=t,this.ref=n,this.name=i}toString(){return this.value}},pw=class extends Ys{constructor(t,n,i){super();this.value=t,this.ref=n,this.name=i}toString(){return this.value}toJson(){return JSON.parse(this.value)}},gw=class extends Ys{constructor(t,n,i,o){super();this.value=t,this.values=n,this.ref=i,this.name=o}toString(){return this.values[this.value]}},mw=class extends Ys{constructor(t,n,i,o,a,l,u){super();this.countDecimals=function(t){return t%1!=0?t.toString().split(".")[1].length:1};this.value=t,this.min=n,this.max=i,this.step=o,this.suffix=a,this.ref=l,this.name=u}toString(){return this.value.toString()+this.suffix}increment(){let t=this.countDecimals(this.max);parseFloat(this.value.toFixed(t))<this.max&&(this.value=parseFloat(this.value.toFixed(t))+this.step)}decrement(){let t=this.countDecimals(this.min);parseFloat(this.value.toFixed(t))>this.min&&(this.value=parseFloat(this.value.toFixed(t))-this.step)}},Xa=class extends Ys{constructor(t,n,i,o,a){super();this.value=i,this.onValue=t,this.offValue=n,this.ref=o,this.name=a}toString(){return this.value?this.onValue:this.offValue}switch(){this.value=!this.value}},Wr=class{constructor(){this.properties=[]}addIncremental(t,n,i,o,a,l,u){this.properties.push(new mw(t,n,i,o,a,l,u))}addStringable(t,n,i){this.properties.push(new fw(t,n,i))}addJSONable(t,n,i){this.properties.push(new pw(t,n,i))}addSwitchable(t,n,i,o,a){this.properties.push(new Xa(t,n,i,o,a))}addEnumerable(t,n,i,o){this.properties.push(new gw(t,n,i,o))}getByRef(t){let n=this.properties.filter(i=>i.ref===t);return n.length>0?n[0]:null}getByKey(t){let n=this.properties.filter(i=>i.key===t);return n.length>0?n[0]:null}};H();var wi=class{},me=wi;me.FONT_SIZE_REF="fontSize",me.FONT_FAMILY_REF="fontFamily",me.FONT_OVERRIDE_REF="fontOverride",me.APPEARANCE_REF="appearance",me.SCROLL_REF="scroll",me.TEXT_ALIGNMENT_REF="textAlign",me.COLUMN_COUNT_REF="colCount",me.WORD_SPACING_REF="wordSpacing",me.LETTER_SPACING_REF="letterSpacing",me.PAGE_MARGINS_REF="pageMargins",me.LINE_HEIGHT_REF="lineHeight",me.FONT_SIZE_KEY="--USER__"+wi.FONT_SIZE_REF,me.FONT_FAMILY_KEY="--USER__"+wi.FONT_FAMILY_REF,me.FONT_OVERRIDE_KEY="--USER__"+wi.FONT_OVERRIDE_REF,me.APPEARANCE_KEY="--USER__"+wi.APPEARANCE_REF,me.SCROLL_KEY="--USER__"+wi.SCROLL_REF,me.TEXT_ALIGNMENT_KEY="--USER__"+wi.TEXT_ALIGNMENT_REF,me.COLUMN_COUNT_KEY="--USER__"+wi.COLUMN_COUNT_REF,me.WORD_SPACING_KEY="--USER__"+wi.WORD_SPACING_REF,me.LETTER_SPACING_KEY="--USER__"+wi.LETTER_SPACING_REF,me.PAGE_MARGINS_KEY="--USER__"+wi.PAGE_MARGINS_REF,me.LINE_HEIGHT_KEY="--USER__"+wi.LINE_HEIGHT_REF;H();function Ie(r,t){return r.querySelector(t)}function mt(r,t){let n=Ie(r,t);if(n&&n instanceof HTMLElement)return n;throw new Error("required element "+t+" not found")}function un(r,t){if(r===null)throw new Error("parent element is null");return r.querySelector(t)}function Gr(r,t){let n=un(r,t);if(n)return n;throw new Error("required element "+t+" not found in iframe")}function Cn(r,t,n){r.setAttribute(t,n)}H();H();var d_=nt(E0());var wl=class{constructor(t){this.getScrollingElement=t=>t.scrollingElement?t.scrollingElement:t.body;this.navigator=t}async handleFootnote(t,n){let i=t.getAttribute("href");if(i&&i.indexOf("#")>0){let a=function(u){let d=document.location.href;return new URL(u,d).href},o=i.substring(i.indexOf("#")+1),l=a(i);l&&(l=l.substring(0,l.indexOf("#")),n.preventDefault(),n.stopPropagation(),this.navigator.api?.getContent?await this.navigator.api?.getContent(i).then(u=>{let y=new DOMParser().parseFromString(u,"text/html").querySelector("#"+o);y&&(n.preventDefault(),n.stopPropagation(),this.showPopup(y,n))}):await fetch(l,this.navigator.requestConfig).then(u=>u.text()).then(async u=>{let y=new DOMParser().parseFromString(u,"text/html").querySelector("#"+o);y&&(n.preventDefault(),n.stopPropagation(),this.showPopup(y,n))}))}}async hidePopover(){let t=this.navigator.iframes[0].contentDocument?.getElementById("d2-popover");t&&t.parentElement?.removeChild(t);let n=mt(document,"#iframe-wrapper");n.style.overflow="auto"}async showPopover(t,n){let i=t.getAttribute("href"),o=t.getAttribute("src");function a(l){let u=document.location.href;return new URL(l,u).href}if(i){let l=a(i);if(l){n.preventDefault(),n.stopPropagation();let u=this.navigator.iframes[0].contentDocument?.getElementById("d2-popover");u&&u.parentElement?.removeChild(u);let d=document.createElement("div");d.id="d2-popover",d.className="d2-popover is-active";let h=mt(document,"#iframe-wrapper");h.style.overflow="hidden",d.style.top=h.scrollTop+"px",d.style.height=h.clientHeight*.9+"px";let y=document.createElement("div");y.className="d2-popover-wrapper",d.appendChild(y);let b=document.createElement("div");b.className="d2-popover-content",y.appendChild(b),this.navigator.api?.getContent?await this.navigator.api?.getContent(i).then(m=>{b.innerHTML=m;let f=this.navigator.iframes[0].contentDocument;f&&f.body.appendChild(d)}):await fetch(l,this.navigator.requestConfig).then(m=>m.text()).then(async m=>{b.innerHTML=m;let f=this.navigator.iframes[0].contentDocument;f&&f.body.appendChild(d)});let w=this.navigator.iframes[0].contentWindow;if(!w)return;let p=this;w.onclick=function(m){n.target!==m.target&&d.parentElement&&(p.hidePopover(),w&&(w.onclick=null))}}}else if(o&&a(o)){n.preventDefault(),n.stopPropagation();let u=this.navigator.iframes[0].contentDocument?.getElementById("d2-popover");u&&u.parentElement?.removeChild(u);let d=document.createElement("div");d.id="d2-popover",d.className="d2-popover is-active";let h=mt(document,"#iframe-wrapper");h.style.overflow="hidden",d.style.top=h.scrollTop+"px",d.style.height=h.clientHeight*.9+"px";let y=document.createElement("div");y.className="d2-popover-wrapper",d.appendChild(y);let b=document.createElement("img");b.className="d2-popover-content",y.appendChild(b),b.src=o;let w=this.navigator.iframes[0].contentDocument;w&&w.body.appendChild(d);let p=this.navigator.iframes[0].contentWindow;if(!p)return;let m=this;p.onclick=function(f){n.target!==f.target&&d.parentElement&&(m.hidePopover(),p&&(p.onclick=null))}}}showPopup(t,n){let i=this.navigator.iframes[0].contentDocument?.getElementById("d2-popup");i&&i.parentElement?.removeChild(i);let o=document.createElement("aside");o.id="d2-popup",o.className="d2-popup is-active";let a=document.createElement("div");a.className="d2-popup-wrapper",o.appendChild(a);let l=document.createElement("div");l.className="d2-popup-content",a.appendChild(l);let u=document.createElement("p");l.appendChild(u),typeof t=="string"?u.innerHTML=t:u.innerHTML=(0,d_.default)(t.innerHTML,{allowedTags:[],allowedAttributes:{}});let d=this.navigator.view?.isPaginated(),h=this.navigator.iframes[0].contentDocument;if(!h)return;let y=this.getScrollingElement(h),b=d?y.scrollLeft:0,w=d?y.scrollTop:0,p=n.x+b,m=n.y+w;o.style.top=m+"px",d&&(o.style.left=p+"px"),h.body.appendChild(o);let f=this.navigator.iframes[0].contentWindow;!f||(f.onclick=function(g){n.target!==g.target&&o.parentElement&&(o.style.display="none",o.parentElement.removeChild(o),f&&(f.onclick=null))})}};var $d=nt(Jt());function Ee(r,t,n){r&&r.addEventListener(t,n,!0)}function je(r,t,n){r&&r.removeEventListener(t,n,!0)}var qd=class{constructor(t){this.onInternalLink=()=>{};this.onClickThrough=()=>{};this.checkForLink=t=>{let n=t.target;for(;n&&n.tagName.toLowerCase()!=="body";){if(n.tagName.toLowerCase()==="a"&&n.href)return n;n=n.parentElement}return null};this.linkInPublication=(t,n)=>t.some(i=>!i.Rel?.includes("external")&&this.navigator.publication.getRelativeHref(n).includes(i.Href));this.isReadingOrderInternal=t=>($d.default.log("clickedLink: ",t),this.linkInPublication(this.navigator.publication.readingOrder,t.href));this.isResourceInternal=t=>($d.default.log("clickedLink: ",t),this.linkInPublication(this.navigator.publication.resources,t.href));this.handleLinks=async t=>{$d.default.log("R2 Click Handler");let n=this.checkForLink(t);if(n){let i=window.location.protocol===n.protocol&&window.location.port===n.port&&window.location.hostname===n.hostname,o=this.isReadingOrderInternal(n),a=this.isResourceInternal(n);a||await this.popup.hidePopover();let l=n.href.indexOf("#");if(!o&&!a)window.open(n.href,n.target??"_blank"),t.preventDefault(),t.stopPropagation();else if(t.target.href=n.href,(i||o)&&l!==-1){let u=t.target;u?u.getAttribute("epub:type")==="noteref"?await this.popup.handleFootnote(u,t):a&&!o?await this.popup.showPopover(u,t):this.onInternalLink(t):this.onInternalLink(t)}else(i||o)&&l===-1&&this.onInternalLink(t)}else this.onClickThrough(t)};this.navigator=t,this.popup=new wl(this.navigator)}setupEvents(t){if(t!==null)t.addEventListener("dblclick",async n=>{let i=n.target;n.target&&i.tagName.toLowerCase()==="img"&&await this.popup.showPopover(i,n)},!0),t.addEventListener("click",this.handleLinks.bind(this));else throw"cannot setup events for null"}};H();H();function f_(){return mt(document,"#iframe-wrapper").clientWidth}function tr(){return mt(document,"#iframe-wrapper").clientHeight}var g_=nt(So()),Wd=class{constructor(t){this.layout="reflowable";this.USERSETTINGS="userSetting";this.sideMargin=20;this.height=0;this.attributes={margin:0};this.hasFixedScrollWidth=!1;this.store=t,this.scrollMode?(this.name="readium-scroll-on",this.label="Scrolling"):(this.name="readium-scroll-off",this.label="Paginated")}setMode(t){if(this.scrollMode=t,t){this.name="readium-scroll-on",this.label="Scrolling";let n=this.iframe.contentDocument;if(n){let i=un(n,"head");if(i){let a=Ie(i,"meta[name=viewport]");a&&a.remove()}let o=un(n,"html");o&&o.style.setProperty("--USER__scroll","readium-scroll-on")}this.setSize(),this.setIframeHeight(this.iframe)}else{this.height=tr()-40-this.attributes.margin,this.name="readium-scroll-off",this.label="Paginated",this.checkForFixedScrollWidth();let n=this.iframe.contentDocument;if(n){let i=un(n,"html");i&&i.style.setProperty("--USER__scroll","readium-scroll-off")}this.setSize()}this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate()}start(){if(this.scrollMode){let t=this.iframe.contentDocument;if(t){let n=un(t,"head");if(n){let i=Ie(n,"meta[name=viewport]");i&&i.remove()}}this.setSize(),this.setIframeHeight(this.iframe)}else{this.iframe.height="0",this.iframe.width="0",this.setSize();let t=document.createElement("meta");t.name="viewport",t.content="width=device-width, initial-scale=1, maximum-scale=1",this.checkForFixedScrollWidth()}}stop(){if(this.iframe.height="0",this.iframe.width="0",this.iframe.contentDocument){let n=un(this.iframe.contentDocument,"body"),i=Array.prototype.slice.call(n.querySelectorAll("img"));for(let o of i)o.style.maxWidth=""}}getCurrentPosition(){let t=mt(document,"#iframe-wrapper");if(this.scrollMode)return t.scrollTop/this.scrollingElement.scrollHeight;{let n=this.getColumnWidth(),i=this.getLeftColumnsWidth(),o=this.getRightColumnsWidth(),a=i+n+o;return i/a}}goToProgression(t){let n=mt(document,"#iframe-wrapper");if(this.scrollMode)n.scrollTop=this.scrollingElement.scrollHeight*t;else{let i=this.getColumnWidth(),o=this.getLeftColumnsWidth(),a=this.getRightColumnsWidth(),l=o+i+a,u=t*l,d=Math.round(u/i)*i;d>=l&&(d=d-i),this.setLeftColumnsWidth(d)}}goToCssSelector(t,n){let i=this.iframe.contentDocument;if(i){let o=i.querySelector(t);this.goToElement(o,n)}}goToFragment(t,n){let i=this.iframe.contentDocument;if(i){let o=i.getElementById(t);this.goToElement(o,n)}}snap(t,n){if(t&&!this.scrollMode){let i=t.style.height;t.style.height="0";let o=this.getColumnWidth(),a=this.getLeftColumnsWidth()+t.getBoundingClientRect().left,l=Math.floor(a/o)*o;t.style.height=i,this.setLeftColumnsWidth(l),this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(0)}}goToElement(t,n){if(this.scrollMode)t&&t.scrollIntoView({block:"center"});else if(t){let i=t.style.height;t.style.height="0";let o=t.getBoundingClientRect().left,a=this.getColumnWidth(),l=this.scrollingElement.scrollLeft-a,u=Math.ceil(o/a)*a+l;if(n){let d=this.getLeftColumnsWidth();u=Math.ceil(o/a)*a+d}t.style.height=i,this.setLeftColumnsWidth(u),this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)}}atStart(){return this.scrollMode?mt(document,"#iframe-wrapper").scrollTop===0:this.getLeftColumnsWidth()<=0}atEnd(){if(this.scrollMode){let t=mt(document,"#iframe-wrapper");return Math.ceil(this.scrollingElement.scrollHeight-t.scrollTop)-1<=tr()}else return Math.floor(this.getRightColumnsWidth())<=0||Math.ceil(this.getCurrentPage())===this.getPageCount()}goToPreviousPage(){let t=mt(document,"#iframe-wrapper");if(this.scrollMode){let n=t.scrollTop,i=this.getScreenHeight()-40,o=n-i;o>=0?t.scrollTop=o:t.scrollTop=0}else{let n=this.getLeftColumnsWidth(),i=this.getColumnWidth(),o=n-i;o>=0?this.setLeftColumnsWidth(o):this.setLeftColumnsWidth(0),this.navigator.checkResourcePosition()}this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate()}goToNextPage(){let t=mt(document,"#iframe-wrapper");if(this.scrollMode){let n=t.scrollTop,i=this.getScreenHeight()-40,o=this.scrollingElement.scrollHeight,a=n+i;a<o?t.scrollTop=a:t.scrollTop=o}else{let n=this.getLeftColumnsWidth(),i=this.getColumnWidth(),o=this.scrollWidth,a=n+i;a<o?this.setLeftColumnsWidth(a):this.setLeftColumnsWidth(o),this.navigator.checkResourcePosition()}this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate()}getCurrentPage(){return this.scrollMode?0:this.getCurrentPosition()*this.getPageCount()+1}getPageCount(){if(this.scrollMode)return 0;{let t=this.getColumnWidth();return this.scrollWidth/t}}isPaginated(){if(this.iframe){let t=this.iframe.contentDocument;if(t){let n=un(t,"html");if(n)return!(n.style.getPropertyValue("--USER__scroll")==="readium-scroll-on")}}return!this.scrollMode}isScrollMode(){if(this.iframe){let t=this.iframe.contentDocument;if(t){let n=un(t,"html");if(n)return n.style.getPropertyValue("--USER__scroll")==="readium-scroll-on"}}return this.scrollMode}async getProperty(t){let n=await this.store.get(this.USERSETTINGS);if(n){let i=JSON.parse(n);return i=i.filter(o=>o.name===t),i.length===0?null:i[0]}return null}getScreenHeight(){return mt(document,"#iframe-wrapper").clientHeight}setIframeHeight(t){(0,g_.debounce)(i=>{if(i){let o=i.contentWindow.document.body,a=i.contentWindow.document.documentElement,l=Math.max(o?.scrollHeight,o?.offsetHeight,a?.clientHeight,a?.scrollHeight,a?.offsetHeight);if(l){let u=tr()-this.attributes.margin;i.height=Math.max(u,l)+"px"}}},200)(t)}checkForFixedScrollWidth(){let t=this.iframe.contentDocument;if(t){let n=un(t,"body"),i=n?.scrollWidth;this.hasFixedScrollWidth=n?.scrollWidth===i}}setSize(){if(this.iframe.width=f_()+"px",this.scrollMode){let t=this.iframe.contentWindow?.document?.documentElement;this.iframe.height=t?.offsetHeight+"px"}else{let t=this.iframe.contentDocument;t&&t.documentElement&&(t.documentElement.style.height=this.height+"px"),this.iframe.height=this.height+"px"}}getLeftColumnsWidth(){return Math.ceil(this.scrollingElement.scrollLeft)}getRightColumnsWidth(){let t=this.getColumnWidth(),n=this.scrollWidth-t;if(this.hasFixedScrollWidth){let i=this.getLeftColumnsWidth();n=Math.max(0,n-i)}return n}getColumnWidth(){return this.scrollingElement.clientWidth}setLeftColumnsWidth(t){this.scrollingElement.scrollLeft=t}get scrollingElement(){return this.iframe.contentDocument?.scrollingElement?this.iframe.contentDocument?.scrollingElement:this.iframe.contentDocument?.body?this.iframe.contentDocument?.body:document.createElement("body")}get scrollWidth(){let t=this.scrollingElement?.scrollWidth,n=this.getColumnWidth();return Math.ceil(t/n)*n}};H();var Gd=class{constructor(){this.layout="fixed";this.sideMargin=20;this.height=0;this.attributes={margin:0}}start(){}stop(){}getCurrentPosition(){return 0}getScreenHeight(){return mt(document,"#iframe-wrapper").clientHeight}goToProgression(t){}goToCssSelector(t,n){}goToFragment(t,n){}snap(t,n){}getCurrentPage(){return 0}getPageCount(){return 1}setSize(){}isPaginated(){return!0}isScrollMode(){return!1}atEnd(){return!0}atStart(){return!0}};var _i=nt(Jt()),kt=class{constructor(t,n,i,o,a){this.USERSETTINGS="userSetting";this.fontSize=100;this.fontOverride=!1;this.fontFamily=0;this.appearance=0;this.verticalScroll=!0;this.textAlignment=0;this.columnCount=0;this.wordSpacing=0;this.letterSpacing=0;this.pageMargins=2;this.lineHeight=1;this.settingsChangeCallback=()=>{};this.settingsColumnsChangeCallback=()=>{};this.viewChangeCallback=()=>{};this.store=t,this.view=a==="fixed"?new Gd:new Wd(this.store),this.headerMenu=n,this.api=i,this.injectables=o,this.injectables?.forEach(l=>{l.type==="style"&&(l.fontFamily&&this.addFont(l.fontFamily),l.appearance&&this.addAppearance(l.appearance))})}async isPaginated(){return!await this.getPropertyAndFallback("verticalScroll",me.SCROLL_KEY)}async isScrollMode(){return!await this.isPaginated()}static async create(t){let n=new this(t.store,t.headerMenu,t.api,t.injectables,t.layout);if(await n.initialise(),t.initialUserSettings){n.userProperties||(n.userProperties=n.getUserSettings());let i=t.initialUserSettings;if(i.verticalScroll!==void 0){n.verticalScroll=this.parseScrollSetting(i.verticalScroll);let o=n.userProperties.getByRef(me.SCROLL_REF);o&&(o.value=n.verticalScroll,await n.saveProperty(o)),_i.default.log(n.verticalScroll)}if(i.appearance){n.appearance=kt.appearanceValues.findIndex(a=>a===i.appearance);let o=n.userProperties.getByRef(me.APPEARANCE_REF);o&&(o.value=n.appearance,await n.saveProperty(o)),_i.default.log(n.appearance)}if(i.fontSize){n.fontSize=i.fontSize;let o=n.userProperties.getByRef(me.FONT_SIZE_REF);o&&(o.value=n.fontSize,await n.saveProperty(o)),_i.default.log(n.fontSize)}if(i.fontFamily){n.fontFamily=kt.fontFamilyValues.findIndex(a=>a===i.fontFamily);let o=n.userProperties.getByRef(me.FONT_FAMILY_REF);o&&(o.value=n.fontFamily,await n.saveProperty(o)),_i.default.log(n.fontFamily),n.fontFamily!==0&&(n.fontOverride=!0)}if(i.textAlignment){n.textAlignment=kt.textAlignmentValues.findIndex(a=>a===i.textAlignment);let o=n.userProperties.getByRef(me.TEXT_ALIGNMENT_REF);o&&(o.value=n.textAlignment,await n.saveProperty(o)),_i.default.log(n.textAlignment)}if(i.columnCount){n.columnCount=kt.columnCountValues.findIndex(a=>a===i.columnCount);let o=n.userProperties.getByRef(me.COLUMN_COUNT_REF);o&&(o.value=n.columnCount,await n.saveProperty(o)),_i.default.log(n.columnCount)}if(i.wordSpacing){n.wordSpacing=i.wordSpacing;let o=n.userProperties.getByRef(me.WORD_SPACING_REF);o&&(o.value=n.wordSpacing,await n.saveProperty(o)),_i.default.log(n.wordSpacing)}if(i.letterSpacing){n.letterSpacing=i.letterSpacing;let o=n.userProperties.getByRef(me.LETTER_SPACING_REF);o&&(o.value=n.letterSpacing,await n.saveProperty(o)),_i.default.log(n.letterSpacing)}if(i.pageMargins){n.pageMargins=i.pageMargins;let o=n.userProperties.getByRef(me.PAGE_MARGINS_REF);o&&(o.value=n.pageMargins,await n.saveProperty(o)),_i.default.log(n.pageMargins)}if(i.lineHeight){n.lineHeight=i.lineHeight;let o=n.userProperties.getByRef(me.LINE_HEIGHT_REF);o&&(o.value=n.lineHeight,await n.saveProperty(o)),_i.default.log(n.lineHeight)}n.userProperties=n.getUserSettings(),await n.initialise()}return await n.initializeSelections(),new Promise(i=>i(n))}stop(){_i.default.log("book settings stop")}async initialise(){this.appearance=await this.getPropertyAndFallback("appearance",me.APPEARANCE_KEY),this.verticalScroll=await this.getPropertyAndFallback("verticalScroll",me.SCROLL_KEY),this.fontFamily=await this.getPropertyAndFallback("fontFamily",me.FONT_FAMILY_KEY),this.fontFamily!==0&&(this.fontOverride=!0),this.textAlignment=await this.getPropertyAndFallback("textAlignment",me.TEXT_ALIGNMENT_KEY),this.columnCount=await this.getPropertyAndFallback("columnCount",me.COLUMN_COUNT_KEY),this.fontSize=await this.getPropertyAndFallback("fontSize",me.FONT_SIZE_KEY),this.wordSpacing=await this.getPropertyAndFallback("wordSpacing",me.WORD_SPACING_KEY),this.letterSpacing=await this.getPropertyAndFallback("letterSpacing",me.LETTER_SPACING_KEY),this.pageMargins=await this.getPropertyAndFallback("pageMargins",me.PAGE_MARGINS_KEY),this.lineHeight=await this.getPropertyAndFallback("lineHeight",me.LINE_HEIGHT_KEY),this.userProperties=this.getUserSettings()}async reset(){this.appearance=0,this.verticalScroll=!0,this.fontSize=100,this.fontOverride=!1,this.fontFamily=0,this.textAlignment=0,this.columnCount=0,this.wordSpacing=0,this.letterSpacing=0,this.pageMargins=2,this.lineHeight=1,this.userProperties=this.getUserSettings();let t=this.iframe.contentDocument;if(t){let n=un(t,"html");if(n){let i=document.documentElement,o=mt(i,"body");n.style.removeProperty(me.FONT_SIZE_KEY),n.style.removeProperty(me.WORD_SPACING_KEY),n.style.removeProperty(me.LETTER_SPACING_KEY),n.style.removeProperty(me.COLUMN_COUNT_KEY),n.style.removeProperty(me.TEXT_ALIGNMENT_KEY),n.style.removeProperty(me.LINE_HEIGHT_KEY),n.style.removeProperty(me.PAGE_MARGINS_KEY),n.style.removeProperty(me.APPEARANCE_KEY),Cn(i,"data-viewer-theme","day"),Cn(o,"data-viewer-theme","day"),n.style.removeProperty(me.FONT_FAMILY_KEY),Cn(n,"data-viewer-font","publisher"),n.style.setProperty(me.FONT_OVERRIDE_KEY,"readium-font-off")}}}async initializeSelections(){this.headerMenu&&(this.settingsView=Ie(this.headerMenu,"#container-view-settings"))}async applyProperties(){this.userProperties=this.getUserSettings();let t=this.iframe.contentDocument;if(t){let n=un(t,"html");if(n){let i=document.documentElement,o=mt(i,"body");if(this.view?.navigator.publication.isReflowable&&(await this.getProperty(me.FONT_SIZE_KEY)&&n.style.setProperty(me.FONT_SIZE_KEY,this.userProperties.getByRef(me.FONT_SIZE_REF)?.toString()??null),await this.getProperty(me.WORD_SPACING_KEY)&&n.style.setProperty(me.WORD_SPACING_KEY,this.userProperties.getByRef(me.WORD_SPACING_REF)?.toString()??null),await this.getProperty(me.LETTER_SPACING_KEY)&&n.style.setProperty(me.LETTER_SPACING_KEY,this.userProperties.getByRef(me.LETTER_SPACING_REF)?.toString()??null)),await this.getProperty(me.COLUMN_COUNT_KEY)&&n.style.setProperty(me.COLUMN_COUNT_KEY,this.userProperties.getByRef(me.COLUMN_COUNT_REF)?.toString()??null),this.view?.navigator.publication.isReflowable&&(await this.getProperty(me.TEXT_ALIGNMENT_KEY)&&(this.userProperties.getByRef(me.TEXT_ALIGNMENT_REF)?.toString()==="auto"?n.style.removeProperty(me.TEXT_ALIGNMENT_KEY):n.style.setProperty(me.TEXT_ALIGNMENT_KEY,this.userProperties.getByRef(me.TEXT_ALIGNMENT_REF)?.toString()??null)),await this.getProperty(me.LINE_HEIGHT_KEY)&&n.style.setProperty(me.LINE_HEIGHT_KEY,this.userProperties.getByRef(me.LINE_HEIGHT_REF)?.toString()??null),await this.getProperty(me.PAGE_MARGINS_KEY)&&n.style.setProperty(me.PAGE_MARGINS_KEY,this.userProperties.getByRef(me.PAGE_MARGINS_REF)?.toString()??null)),await this.getProperty(me.APPEARANCE_KEY)?(n.style.setProperty(me.APPEARANCE_KEY,this.userProperties.getByRef(me.APPEARANCE_REF)?.toString()??null),this.userProperties.getByRef(me.APPEARANCE_REF)?.value===0?(Cn(i,"data-viewer-theme","day"),Cn(o,"data-viewer-theme","day")):this.userProperties.getByRef(me.APPEARANCE_REF)?.value===1?(Cn(i,"data-viewer-theme","sepia"),Cn(o,"data-viewer-theme","sepia")):this.userProperties.getByRef(me.APPEARANCE_REF)?.value===2&&(Cn(i,"data-viewer-theme","night"),Cn(o,"data-viewer-theme","night"))):(n.style.setProperty(me.APPEARANCE_KEY,this.userProperties.getByRef(me.APPEARANCE_REF)?.toString()??null),Cn(i,"data-viewer-theme","day"),Cn(o,"data-viewer-theme","day")),this.view?.navigator.publication.isReflowable){if(await this.getProperty(me.FONT_FAMILY_KEY))if(n.style.setProperty(me.FONT_FAMILY_KEY,this.userProperties.getByRef(me.FONT_FAMILY_REF)?.toString()??null),this.userProperties.getByRef(me.FONT_FAMILY_REF)?.value===0)Cn(n,"data-viewer-font","publisher"),n.style.setProperty(me.FONT_OVERRIDE_KEY,"readium-font-off");else if(this.userProperties.getByRef(me.FONT_FAMILY_REF)?.value===1)Cn(n,"data-viewer-font","serif"),n.style.setProperty(me.FONT_OVERRIDE_KEY,"readium-font-on");else if(this.userProperties.getByRef(me.FONT_FAMILY_REF)?.value===2)Cn(n,"data-viewer-font","sans"),n.style.setProperty(me.FONT_OVERRIDE_KEY,"readium-font-on");else{let a=this.userProperties.getByRef(me.FONT_FAMILY_REF);a&&Cn(n,"data-viewer-font",a.toString()),n.style.setProperty(me.FONT_OVERRIDE_KEY,"readium-font-on")}else n.style.setProperty(me.FONT_FAMILY_KEY,this.userProperties.getByRef(me.FONT_FAMILY_REF)?.toString()??null),Cn(n,"data-viewer-font","publisher"),n.style.setProperty(me.FONT_OVERRIDE_KEY,"readium-font-off");await this.getProperty(me.SCROLL_KEY)?this.userProperties.getByRef(me.SCROLL_REF)?.value===!0?n.style.setProperty("--USER__scroll","readium-scroll-on"):n.style.setProperty("--USER__scroll","readium-scroll-off"):n.style.setProperty("--USER__scroll","readium-scroll-on"),n.style.setProperty("--USER__advancedSettings","readium-advanced-on"),this.isScrollMode().then(a=>{this.view?.setMode?.(a)})}}}}setIframe(t){this.iframe=t,this.view&&(this.view.iframe=t),this.settingsView&&kt.renderControls(this.settingsView)}static renderControls(t){Ee(Ie(t,"ul"),"click",n=>{n.stopPropagation()})}onSettingsChange(t){this.settingsChangeCallback=t}onColumnSettingsChange(t){this.settingsColumnsChangeCallback=t}onViewChange(t){this.viewChangeCallback=t}async storeProperty(t){await this.updateUserSettings(),await this.saveProperty(t)}addAppearance(t){kt.appearanceValues.includes(t)||kt.appearanceValues.push(t)}initAddedAppearance(){this.applyProperties()}addFont(t){kt.fontFamilyValues.includes(t)||kt.fontFamilyValues.push(t)}initAddedFont(){this.applyProperties()}async updateUserSettings(){let t={fontFamily:kt.fontFamilyValues[await this.userProperties?.getByRef(me.FONT_FAMILY_REF)?.value],fontSize:this.userProperties?.getByRef(me.FONT_SIZE_REF)?.value,appearance:kt.appearanceValues[await this.userProperties?.getByRef(me.APPEARANCE_REF)?.value],textAlignment:kt.textAlignmentValues[await this.userProperties?.getByRef(me.TEXT_ALIGNMENT_REF)?.value],columnCount:kt.columnCountValues[await this.userProperties?.getByRef(me.COLUMN_COUNT_REF)?.value],wordSpacing:this.userProperties?.getByRef(me.WORD_SPACING_REF)?.value,letterSpacing:this.userProperties?.getByRef(me.LETTER_SPACING_REF)?.value,verticalScroll:this.userProperties?.getByRef(me.SCROLL_REF)?.value};this.api?.updateSettings&&this.api?.updateSettings(t).then(n=>{_i.default.log("api updated user settings",JSON.stringify(t))})}getUserSettings(){let t=new Wr;return t.addSwitchable("readium-font-on","readium-font-off",this.fontOverride,me.FONT_OVERRIDE_REF,me.FONT_OVERRIDE_KEY),t.addEnumerable(this.columnCount,kt.columnCountValues,me.COLUMN_COUNT_REF,me.COLUMN_COUNT_KEY),t.addEnumerable(this.appearance,kt.appearanceValues,me.APPEARANCE_REF,me.APPEARANCE_KEY),t.addIncremental(this.pageMargins,.5,4,.25,"",me.PAGE_MARGINS_REF,me.PAGE_MARGINS_KEY),t.addEnumerable(this.textAlignment,kt.textAlignmentValues,me.TEXT_ALIGNMENT_REF,me.TEXT_ALIGNMENT_KEY),t.addEnumerable(this.fontFamily,kt.fontFamilyValues,me.FONT_FAMILY_REF,me.FONT_FAMILY_KEY),t.addIncremental(this.fontSize,100,300,25,"%",me.FONT_SIZE_REF,me.FONT_SIZE_KEY),t.addIncremental(this.lineHeight,1,2,.25,"em",me.LINE_HEIGHT_REF,me.LINE_HEIGHT_KEY),t.addIncremental(this.wordSpacing,0,1,.25,"rem",me.WORD_SPACING_REF,me.WORD_SPACING_KEY),t.addIncremental(this.letterSpacing,0,.5,.0625,"em",me.LETTER_SPACING_REF,me.LETTER_SPACING_KEY),t.addSwitchable("readium-scroll-on","readium-scroll-off",this.verticalScroll,me.SCROLL_REF,me.SCROLL_KEY),t}async saveProperty(t){let n=await this.store.get(this.USERSETTINGS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.name!==t.name),t.value!==void 0&&i.push(t),await this.store.set(this.USERSETTINGS,JSON.stringify(i))}else{let i=[];i.push(t),await this.store.set(this.USERSETTINGS,JSON.stringify(i))}return new Promise(i=>i(t))}async getProperty(t){let n=await this.store.get(this.USERSETTINGS);if(n){let i=JSON.parse(n);return i=i.filter(o=>o.name===t),i.length===0?null:i[0]}return null}async getPropertyAndFallback(t,n){return(await this.getProperty(n))?.value??this[t]}async resetUserSettings(){await this.store.remove(this.USERSETTINGS),await this.reset(),this.settingsChangeCallback()}get currentSettings(){return{appearance:kt.appearanceValues[this.userProperties?.getByRef(me.APPEARANCE_REF)?.value],fontFamily:kt.fontFamilyValues[this.userProperties?.getByRef(me.FONT_FAMILY_REF)?.value],textAlignment:kt.textAlignmentValues[this.userProperties?.getByRef(me.TEXT_ALIGNMENT_REF)?.value],columnCount:kt.columnCountValues[this.userProperties?.getByRef(me.COLUMN_COUNT_REF)?.value],verticalScroll:this.verticalScroll,fontSize:this.fontSize,wordSpacing:this.wordSpacing,letterSpacing:this.letterSpacing,pageMargins:this.pageMargins,lineHeight:this.lineHeight}}async applyUserSettings(t){if(t.appearance){let n;t.appearance==="day"||t.appearance==="readium-default-on"?n=kt.appearanceValues[0]:t.appearance==="sepia"||t.appearance==="readium-sepia-on"?n=kt.appearanceValues[1]:t.appearance==="night"||t.appearance==="readium-night-on"?n=kt.appearanceValues[2]:n=t.appearance,this.appearance=kt.appearanceValues.findIndex(o=>o===n);let i=this.userProperties?.getByRef(me.APPEARANCE_REF);i&&(i.value=this.appearance,await this.storeProperty(i))}if(t.fontSize){this.fontSize=t.fontSize;let n=this.userProperties?.getByRef(me.FONT_SIZE_REF);n&&(n.value=this.fontSize,await this.storeProperty(n))}if(t.fontFamily){this.fontFamily=kt.fontFamilyValues.findIndex(i=>i===t.fontFamily);let n=this.userProperties?.getByRef(me.FONT_FAMILY_REF);n&&(n.value=this.fontFamily,await this.storeProperty(n))}if(t.letterSpacing){this.letterSpacing=t.letterSpacing;let n=this.userProperties?.getByRef(me.LETTER_SPACING_REF);n&&(n.value=this.letterSpacing,await this.storeProperty(n))}if(t.wordSpacing){this.wordSpacing=t.wordSpacing;let n=this.userProperties?.getByRef(me.WORD_SPACING_REF);n&&(n.value=this.wordSpacing,await this.storeProperty(n))}if(t.columnCount){this.columnCount=kt.columnCountValues.findIndex(i=>i===t.columnCount);let n=this.userProperties?.getByRef(me.COLUMN_COUNT_REF);n&&(n.value=this.columnCount,await this.storeProperty(n)),this.settingsColumnsChangeCallback()}if(t.textAlignment){this.textAlignment=kt.textAlignmentValues.findIndex(i=>i===t.textAlignment);let n=this.userProperties?.getByRef(me.TEXT_ALIGNMENT_REF);n&&(n.value=this.textAlignment,await this.storeProperty(n))}if(t.lineHeight){this.lineHeight=t.lineHeight;let n=this.userProperties?.getByRef(me.LINE_HEIGHT_REF);n&&(n.value=this.lineHeight,await this.storeProperty(n))}if(t.pageMargins){this.pageMargins=t.pageMargins;let n=this.userProperties?.getByRef(me.PAGE_MARGINS_REF);n&&(n.value=this.pageMargins,await this.storeProperty(n))}if(t.verticalScroll!==void 0){let n=this.view?.getCurrentPosition();this.verticalScroll=kt.parseScrollSetting(t.verticalScroll);let i=this.userProperties?.getByRef(me.SCROLL_REF);i&&(i.value=this.verticalScroll,await this.saveProperty(i)),this.view?.setMode?.(this.verticalScroll),n&&this.view?.goToProgression(n),this.viewChangeCallback()}await this.applyProperties(),this.settingsChangeCallback()}static parseScrollSetting(t){switch(t){case!0:case"scroll":case"readium-scroll-on":return!0;case!1:case"paginated":case"readium-scroll-off":return!1;default:return!1}}async scroll(t){let n=this.view?.getCurrentPosition();this.verticalScroll=t;let i=this.userProperties?.getByRef(me.SCROLL_REF);i&&(i.value=this.verticalScroll,await this.saveProperty(i)),await this.applyProperties(),this.view?.setMode?.(this.verticalScroll),n&&this.view?.goToProgression(n),this.viewChangeCallback()}async increase(t){if(t==="fontSize"){(this.userProperties?.getByRef(me.FONT_SIZE_REF)).increment(),this.fontSize=this.userProperties?.getByRef(me.FONT_SIZE_REF)?.value;let n=this.userProperties?.getByRef(me.FONT_SIZE_REF);n&&await this.storeProperty(n)}else if(t==="letterSpacing"){(this.userProperties?.getByRef(me.LETTER_SPACING_REF)).increment(),this.letterSpacing=this.userProperties?.getByRef(me.LETTER_SPACING_REF)?.value;let n=this.userProperties?.getByRef(me.LETTER_SPACING_REF);n&&await this.storeProperty(n)}else if(t==="wordSpacing"){(this.userProperties?.getByRef(me.WORD_SPACING_REF)).increment(),this.wordSpacing=this.userProperties?.getByRef(me.WORD_SPACING_REF)?.value;let n=this.userProperties?.getByRef(me.WORD_SPACING_REF);n&&await this.storeProperty(n)}else if(t==="lineHeight"){(this.userProperties?.getByRef(me.LINE_HEIGHT_REF)).increment(),this.lineHeight=this.userProperties?.getByRef(me.LINE_HEIGHT_REF)?.value;let n=this.userProperties?.getByRef(me.LINE_HEIGHT_REF);n&&await this.storeProperty(n)}await this.applyProperties(),this.settingsChangeCallback()}async decrease(t){if(t==="fontSize"){(this.userProperties?.getByRef(me.FONT_SIZE_REF)).decrement(),this.fontSize=this.userProperties?.getByRef(me.FONT_SIZE_REF)?.value;let n=this.userProperties?.getByRef(me.FONT_SIZE_REF);n&&await this.storeProperty(n)}else if(t==="letterSpacing"){(this.userProperties?.getByRef(me.LETTER_SPACING_REF)).decrement(),this.letterSpacing=this.userProperties?.getByRef(me.LETTER_SPACING_REF)?.value;let n=this.userProperties?.getByRef(me.LETTER_SPACING_REF);n&&await this.storeProperty(n)}else if(t==="wordSpacing"){(this.userProperties?.getByRef(me.WORD_SPACING_REF)).decrement(),this.wordSpacing=this.userProperties?.getByRef(me.WORD_SPACING_REF)?.value;let n=this.userProperties?.getByRef(me.WORD_SPACING_REF);n&&await this.storeProperty(n)}else if(t==="lineHeight"){(this.userProperties?.getByRef(me.LINE_HEIGHT_REF)).decrement(),this.wordSpacing=this.userProperties?.getByRef(me.LINE_HEIGHT_REF)?.value;let n=this.userProperties?.getByRef(me.LINE_HEIGHT_REF);n&&await this.storeProperty(n)}await this.applyProperties(),this.settingsChangeCallback()}},Ao=kt;Ao.appearanceValues=["readium-default-on","readium-sepia-on","readium-night-on"],Ao.fontFamilyValues=["Original","serif","sans-serif"],Ao.textAlignmentValues=["auto","justify","start"],Ao.columnCountValues=["auto","1","2"];H();H();var Si;(function(n){n[n.Bookmark=0]="Bookmark",n[n.Annotation=1]="Annotation"})(Si||(Si={}));H();H();H();H();H();H();var m_={stringify(r){let t=r.nSigBytes,n=r.words,i=[];for(let o=0;o<t;o++){let a=n[o>>>2]>>>24-o%4*8&255;i.push((a>>>4).toString(16)),i.push((a&15).toString(16))}return i.join("")},parse(r){let t=r.length;if(t%2!=0)throw new Error("Hex string count must be even");if(!/^[a-fA-F0-9]+$/.test(r))throw new Error(`Invalid Hex string: ${r}`);let n=[];for(let i=0;i<t;i+=2)n[i>>>3]|=parseInt(r.substr(i,2),16)<<24-i%8*4;return new Ln(n,t/2)}};H();H();var y_=typeof navigator!="undefined"&&navigator.userAgent?navigator.userAgent.toLowerCase():"",ss=(()=>{let r=parseInt((/msie (\d+)/.exec(y_)||[])[1],10);return isNaN(r)?(r=parseInt((/trident\/.*; rv:(\d+)/.exec(y_)||[])[1],10),isNaN(r)?!1:r):r})();function b_(r,t){return ss===!1?!1:t?r==="<"?ss<t:r==="<="?ss<=t:r===">"?ss>t:r===">="?ss>=t:ss===t:!0}function w5(){if(typeof window!="undefined"){let r=window.crypto||window.msCrypto;if(!r){if(b_("<",11))return console.warn("IE <= 10 uses insecure random generator. Please consider to use IE11 or another modern browser"),function(){return Math.floor(Math.random()*512)%256};throw new Error("Crypto module not found")}return function(){return r.getRandomValues(new Uint32Array(1))[0]}}else{if(typeof globalThis!="undefined"&&globalThis.crypto)return function(){return globalThis.crypto.randomBytes(4).readInt32LE()};if(typeof Ha=="function")return function(){return __non_webpack_require__("crypto").randomBytes(4).readInt32LE()}}throw new Error("Unable to find crypto module")}var v_=w5();var Ln=class{constructor(t,n){if(Array.isArray(t)||!t){this._words=Array.isArray(t)?t:[],this._nSignificantBytes=typeof n=="number"?n:this._words.length*4;return}else if(t instanceof Ln){this._words=t.words.slice(),this._nSignificantBytes=t.nSigBytes;return}let i;try{t instanceof ArrayBuffer?i=new Uint8Array(t):(t instanceof Uint8Array||t instanceof Int8Array||t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array||t instanceof Float64Array)&&(i=new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}catch(l){throw new Error("Invalid argument")}if(!i)throw new Error("Invalid argument");let o=i.byteLength,a=[];for(let l=0;l<o;l++)a[l>>>2]|=i[l]<<24-l%4*8;this._words=a,this._nSignificantBytes=o}get nSigBytes(){return this._nSignificantBytes}set nSigBytes(t){this._nSignificantBytes=t}get words(){return this._words}toString(t){return t?t.stringify(this):m_.stringify(this)}toUint8Array(){let t=this._words,n=this._nSignificantBytes,i=new Uint8Array(n);for(let o=0;o<n;o++)i[o]=t[o>>>2]>>>24-o%4*8&255;return i}concat(t){let n=t.words.slice(),i=t.nSigBytes;if(this.clamp(),this._nSignificantBytes%4)for(let o=0;o<i;o++){let a=n[o>>>2]>>>24-o%4*8&255;this._words[this._nSignificantBytes+o>>>2]|=a<<24-(this._nSignificantBytes+o)%4*8}else for(let o=0;o<i;o+=4)this._words[this._nSignificantBytes+o>>>2]=n[o>>>2];return this._nSignificantBytes+=i,this}clamp(){let t=this._nSignificantBytes;this._words[t>>>2]&=4294967295<<32-t%4*8,this._words.length=Math.ceil(t/4)}clone(){return new Ln(this._words.slice(),this._nSignificantBytes)}static random(t){let n=[];for(let i=0;i<t;i+=4)n.push(v_());return new Ln(n,t)}};H();H();var S0={stringify(r){let t=r.nSigBytes,n=r.words,i=[];for(let o=0;o<t;o++){let a=n[o>>>2]>>>24-o%4*8&255;i.push(String.fromCharCode(a))}return i.join("")},parse(r){let t=r.length,n=[];for(let i=0;i<t;i++)n[i>>>2]|=(r.charCodeAt(i)&255)<<24-i%4*8;return new Ln(n,t)}};var w_={stringify(r){try{return decodeURIComponent(escape(S0.stringify(r)))}catch(t){throw new Error("Malformed UTF-8 data")}},parse(r){return S0.parse(unescape(encodeURIComponent(r)))}};var A0=class{constructor(t){this._minBufferSize=0,this._blockSize=0,this._props=t,this._data=t&&typeof t.data!="undefined"?t.data.clone():new Ln,this._nBytes=t&&typeof t.nBytes=="number"?t.nBytes:0}get blockSize(){return this._blockSize}reset(t,n){this._data=typeof t!="undefined"?t.clone():new Ln,this._nBytes=typeof n=="number"?n:0}_append(t){let n=typeof t=="string"?w_.parse(t):t;this._data.concat(n),this._nBytes+=n.nSigBytes}_process(t){let n,i=this._data.words,o=this._data.nSigBytes,a=this._blockSize,l=this._blockSize*4,u=o/l;t?u=Math.ceil(u):u=Math.max((u|0)-this._minBufferSize,0);let d=u*a,h=Math.min(d*4,o);if(d){for(let y=0;y<d;y+=a)this._doProcessBlock(i,y);n=i.splice(0,d),this._data.nSigBytes-=h}return new Ln(n,h)}_doProcessBlock(t,n){throw new Error("Not implemented")}};var x0=class extends A0{constructor(t){super(t);this._blockSize=512/32,this._props=t,t&&typeof t.blockSize=="number"&&(this._blockSize=t.blockSize),this.reset(t?t.data:void 0,t?t.nBytes:void 0)}get blockSize(){return this._blockSize}reset(t,n){super.reset.call(this,t,n),this._doReset()}update(t){return this._append(t),this._process(),this}finalize(t){return t&&this._append(t),this._doFinalize()}_doReset(){throw new Error("Not implemented")}_doFinalize(){throw new Error("Not implemented")}};var C0=[],E_=[];function E5(r){let t=Math.sqrt(r);for(let n=2;n<=t;n++)if(!(r%n))return!1;return!0}function __(r){return(r-(r|0))*4294967296|0}(function(){let t=2,n=0;for(;n<64;)E5(t)&&(n<8&&(C0[n]=__(Math.pow(t,1/2))),E_[n]=__(Math.pow(t,1/3)),n++),t++})();var as=[],Fi=class extends x0{constructor(t){super(t);this._hash=new Ln(C0.slice(0)),this._props=t,t&&typeof t.hash!="undefined"&&(this._hash=t.hash.clone())}_doReset(){this._hash=new Ln(C0.slice(0))}_doProcessBlock(t,n){let i=this._hash.words,o=i[0],a=i[1],l=i[2],u=i[3],d=i[4],h=i[5],y=i[6],b=i[7];for(let w=0;w<64;w++){if(w<16)as[w]=t[n+w]|0;else{let C=as[w-15],O=(C<<25|C>>>7)^(C<<14|C>>>18)^C>>>3,E=as[w-2],T=(E<<15|E>>>17)^(E<<13|E>>>19)^E>>>10;as[w]=O+as[w-7]+T+as[w-16]}let p=d&h^~d&y,m=o&a^o&l^a&l,f=(o<<30|o>>>2)^(o<<19|o>>>13)^(o<<10|o>>>22),g=(d<<26|d>>>6)^(d<<21|d>>>11)^(d<<7|d>>>25),v=b+g+p+E_[w]+as[w],A=f+m;b=y,y=h,h=d,d=u+v|0,u=l,l=a,a=o,o=v+A|0}i[0]=i[0]+o|0,i[1]=i[1]+a|0,i[2]=i[2]+l|0,i[3]=i[3]+u|0,i[4]=i[4]+d|0,i[5]=i[5]+h|0,i[6]=i[6]+y|0,i[7]=i[7]+b|0}_doFinalize(){let t=this._data.words,n=this._nBytes*8,i=this._data.nSigBytes*8;return t[i>>>5]|=128<<24-i%32,t[(i+64>>>9<<4)+14]=Math.floor(n/4294967296),t[(i+64>>>9<<4)+15]=n,this._data.nSigBytes=t.length*4,this._process(),this._hash}clone(){let t={hash:this._hash,blockSize:this._blockSize,data:this._data,nBytes:this._nBytes};return new Fi(t)}static hash(t,n){return new Fi(n).finalize(t)}};var _l=nt(So());H();var it;(function(u){u[u.Annotation=0]="Annotation",u[u.Search=1]="Search",u[u.ReadAloud=2]="ReadAloud",u[u.PageBreak=3]="PageBreak",u[u.Definition=4]="Definition",u[u.LineFocus=5]="LineFocus",u[u.Comment=6]="Comment"})(it||(it={}));H();var In=nt(Jt());function zd(r,t){let n=r.getClientRects();return T0(n,t)}function T0(r,t){let n=1,i=[];for(let d of r)i.push({bottom:d.bottom,height:d.height,left:d.left,right:d.right,top:d.top,width:d.width});let o=A_(i,n,t),a=T5(o,n),l=x_(a),u=2*2;for(let d=l.length-1;d>=0;d--){let h=l[d];if(!(h.width*h.height>u))if(l.length>1)In.default.log("CLIENT RECT: remove small"),l.splice(d,1);else{In.default.log("CLIENT RECT: remove small, but keep otherwise empty!");break}}return C_(l),In.default.log(`CLIENT RECT: reduced ${i.length} --> ${l.length}`),l}function Hi(r,t,n){return Math.abs(r-t)<=n}function _5(r,t){let n=Math.max(r.left,t.left),i=Math.min(r.right,t.right),o=Math.max(r.top,t.top),a=Math.min(r.bottom,t.bottom);return{bottom:a,height:Math.max(0,a-o),left:n,right:i,top:o,width:Math.max(0,i-n)}}function S_(r,t){let n=_5(t,r);if(n.height===0||n.width===0)return[r];let i=[];{let o={bottom:r.bottom,height:0,left:r.left,right:n.left,top:r.top,width:0};o.width=o.right-o.left,o.height=o.bottom-o.top,o.height!==0&&o.width!==0&&i.push(o)}{let o={bottom:n.top,height:0,left:n.left,right:n.right,top:r.top,width:0};o.width=o.right-o.left,o.height=o.bottom-o.top,o.height!==0&&o.width!==0&&i.push(o)}{let o={bottom:r.bottom,height:0,left:n.left,right:n.right,top:n.bottom,width:0};o.width=o.right-o.left,o.height=o.bottom-o.top,o.height!==0&&o.width!==0&&i.push(o)}{let o={bottom:r.bottom,height:0,left:n.right,right:r.right,top:r.top,width:0};o.width=o.right-o.left,o.height=o.bottom-o.top,o.height!==0&&o.width!==0&&i.push(o)}return i}function Vd(r,t,n,i){return(r.left<t||Hi(r.left,t,i))&&(r.right>t||Hi(r.right,t,i))&&(r.top<n||Hi(r.top,n,i))&&(r.bottom>n||Hi(r.bottom,n,i))}function S5(r,t,n){return Vd(r,t.left,t.top,n)&&Vd(r,t.right,t.top,n)&&Vd(r,t.left,t.bottom,n)&&Vd(r,t.right,t.bottom,n)}function A5(r,t){let n=Math.min(r.left,t.left),i=Math.max(r.right,t.right),o=Math.min(r.top,t.top),a=Math.max(r.bottom,t.bottom);return{bottom:a,height:a-o,left:n,right:i,top:o,width:i-n}}function O0(r,t,n){return(r.left<t.right||n>=0&&Hi(r.left,t.right,n))&&(t.left<r.right||n>=0&&Hi(t.left,r.right,n))&&(r.top<t.bottom||n>=0&&Hi(r.top,t.bottom,n))&&(t.top<r.bottom||n>=0&&Hi(t.top,r.bottom,n))}function A_(r,t,n){for(let i=0;i<r.length;i++)for(let o=i+1;o<r.length;o++){let a=r[i],l=r[o];if(a===l){In.default.log("mergeTouchingRects rect1 === rect2 ??!");continue}let u=Hi(a.top,l.top,t)&&Hi(a.bottom,l.bottom,t),d=Hi(a.left,l.left,t)&&Hi(a.right,l.right,t);if((d&&!n||u&&!d)&&O0(a,l,t)){In.default.log(`CLIENT RECT: merging two into one, VERTICAL: ${u} HORIZONTAL: ${d} (${n})`);let w=r.filter(m=>m!==a&&m!==l),p=A5(a,l);return w.push(p),A_(w,t,n)}}return r}function x_(r){for(let t=0;t<r.length;t++)for(let n=t+1;n<r.length;n++){let i=r[t],o=r[n];if(i===o){In.default.log("replaceOverlappingRects rect1 === rect2 ??!");continue}if(O0(i,o,-1)){let a=[],l,u,d=S_(i,o);if(d.length===1)a=d,l=i,u=o;else{let b=S_(o,i);d.length<b.length?(a=d,l=i,u=o):(a=b,l=o,u=i)}let h=[];h.push(u),Array.prototype.push.apply(h,a),C_(h),In.default.log(`CLIENT RECT: overlap, cut one rect into ${a.length}`);let y=r.filter(b=>b!==l);return Array.prototype.push.apply(y,a),x_(y)}}return r}function x5(r,t){return Math.max(0,Math.min(r.right,t.right)-Math.max(r.left,t.left))}function C5(r,t){return Math.max(0,Math.min(r.bottom,t.bottom)-Math.max(r.top,t.top))}function T5(r,t){let n=new Set(r);for(let i of r){if(!(i.width>1&&i.height>1)){In.default.log("CLIENT RECT: remove tiny"),n.delete(i);continue}for(let a of r)if(i!==a&&!!n.has(a)&&S5(a,i,t)){In.default.log("CLIENT RECT: remove contained"),n.delete(i);break}}return Array.from(n)}function C_(r){let t=[];for(let n of r)for(let i of r){if(n===i)continue;let o=t.indexOf(n)>=0,a=t.indexOf(i)>=0;if((!o||!a)&&O0(n,i,-1)){o||t.push(n),a||t.push(i),In.default.log("CLIENT RECT: overlap ---"),In.default.log(`#1 TOP:${n.top} BOTTOM:${n.bottom} LEFT:${n.left} RIGHT:${n.right} WIDTH:${n.width} HEIGHT:${n.height}`),In.default.log(`#2 TOP:${i.top} BOTTOM:${i.bottom} LEFT:${i.left} RIGHT:${i.right} WIDTH:${i.width} HEIGHT:${i.height}`);let l=x5(n,i);In.default.log(`xOverlap: ${l}`);let u=C5(n,i);In.default.log(`yOverlap: ${u}`)}}t.length&&In.default.log(`CLIENT RECT: overlaps ${t.length}`)}H();var Ht=nt(Jt());function Er(r,t){let n=r?r.getSelection():null;if(!n)return;if(n.isCollapsed){Ht.default.log("^^^ SELECTION COLLAPSED.");return}let i=n.toString(),o=i.trim().replace(/\n/g," ").replace(/\s\s+/g," ");if(o.length===0){Ht.default.log("^^^ SELECTION TEXT EMPTY.");return}if(!n.anchorNode||!n.focusNode)return;let a=n.rangeCount===1?n.getRangeAt(0):T_(n.anchorNode,n.anchorOffset,n.focusNode,n.focusOffset);if(!a||a.collapsed){Ht.default.log("$$$$$$$$$$$$$$$$$ CANNOT GET NON-COLLAPSED SELECTION RANGE?!");return}let l=R5(a);l.startContainer!==a.startContainer&&(Ht.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: startContainer"),Ht.default.log(l.startContainer),Ht.default.log(a.startContainer)),l.startOffset!==a.startOffset&&(Ht.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: startOffset"),Ht.default.log(`${l.startOffset} !== ${a.startOffset}`)),l.endContainer!==a.endContainer&&(Ht.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: endContainer"),Ht.default.log(l.endContainer),Ht.default.log(a.endContainer)),l.endOffset!==a.endOffset&&(Ht.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: endOffset"),Ht.default.log(`${l.endOffset} !== ${a.endOffset}`));let u=Xr(l,t);if(!u){Ht.default.log("^^^ SELECTION RANGE INFO FAIL?!");return}return{rangeInfo:u,cleanText:o,rawText:i,range:l}}function T_(r,t,n,i){try{let o=new Range;if(o.setStart(r,t),o.setEnd(n,i),!o.collapsed)return Ht.default.log(">>> createOrderedRange RANGE OK"),o;Ht.default.log(">>> createOrderedRange COLLAPSED ... RANGE REVERSE?");let a=new Range;if(a.setStart(n,i),a.setEnd(r,t),!a.collapsed)return Ht.default.log(">>> createOrderedRange RANGE REVERSE OK."),o;Ht.default.log(">>> createOrderedRange RANGE REVERSE ALSO COLLAPSED?!");return}catch(o){console.warn(o.message);return}}function Xr(r,t){let n=r.startContainer.nodeType===Node.ELEMENT_NODE,i=n?r.startContainer:r.startContainer.parentNode&&r.startContainer.parentNode.nodeType===Node.ELEMENT_NODE?r.startContainer.parentNode:void 0;if(!i)return;let o=n?-1:Array.from(i.childNodes).indexOf(r.startContainer);if(o<-1)return;let a=t(i),l=r.endContainer.nodeType===Node.ELEMENT_NODE,u=l?r.endContainer:r.endContainer.parentNode&&r.endContainer.parentNode.nodeType===Node.ELEMENT_NODE?r.endContainer.parentNode:void 0;if(!u)return;let d=l?-1:Array.from(u.childNodes).indexOf(r.endContainer);if(d<-1)return;let h=t(u),y=O5(r.startContainer,r.endContainer);if(!y){Ht.default.log("^^^ NO RANGE COMMON ANCESTOR?!");return}if(r.commonAncestorContainer){let b=r.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?r.commonAncestorContainer:r.commonAncestorContainer.parentNode;b&&b.nodeType===Node.ELEMENT_NODE&&y!==b&&(Ht.default.log(">>>>>> COMMON ANCESTOR CONTAINER DIFF??!"),Ht.default.log(t(y)),Ht.default.log(t(b)))}if(h&&a)return{endContainerChildTextNodeIndex:d,endContainerElementCssSelector:h,endOffset:r.endOffset,startContainerChildTextNodeIndex:o,startContainerElementCssSelector:a,startOffset:r.startOffset}}function Jd(r,t){let n=r.querySelector(t.startContainerElementCssSelector);if(!n){Ht.default.log("^^^ convertRangeInfo NO START ELEMENT CSS SELECTOR?!");return}let i=n;if(t.startContainerChildTextNodeIndex>=0){if(t.startContainerChildTextNodeIndex>=n.childNodes.length){Ht.default.log("^^^ convertRangeInfo rangeInfo.startContainerChildTextNodeIndex >= startElement.childNodes.length?!");return}if(i=n.childNodes[t.startContainerChildTextNodeIndex],i.nodeType!==Node.TEXT_NODE){Ht.default.log("^^^ convertRangeInfo startContainer.nodeType !== Node.TEXT_NODE?!");return}}let o=r.querySelector(t.endContainerElementCssSelector);if(!o){Ht.default.log("^^^ convertRangeInfo NO END ELEMENT CSS SELECTOR?!");return}let a=o;if(t.endContainerChildTextNodeIndex>=0){if(t.endContainerChildTextNodeIndex>=o.childNodes.length){Ht.default.log("^^^ convertRangeInfo rangeInfo.endContainerChildTextNodeIndex >= endElement.childNodes.length?!");return}if(a=o.childNodes[t.endContainerChildTextNodeIndex],a.nodeType!==Node.TEXT_NODE){Ht.default.log("^^^ convertRangeInfo endContainer.nodeType !== Node.TEXT_NODE?!");return}}return T_(i,t.startOffset,a,t.endOffset)}function O5(r,t){if(r.nodeType===Node.ELEMENT_NODE&&r===t||r.nodeType===Node.ELEMENT_NODE&&r.contains(t))return r;if(t.nodeType===Node.ELEMENT_NODE&&t.contains(r))return t;let n=[],i=r.parentNode;for(;i&&i.nodeType===Node.ELEMENT_NODE;)n.push(i),i=i.parentNode;let o=[];for(i=t.parentNode;i&&i.nodeType===Node.ELEMENT_NODE;)o.push(i),i=i.parentNode;let a=n.find(l=>o.indexOf(l)>=0);return a||(a=o.find(l=>n.indexOf(l)>=0)),a}function R5(r){let t=r.cloneRange(),n=t.startContainer,i=t.startOffset,o=t.endContainer,a=t.endOffset;n.childNodes.length&&i>0&&(n=R_(n.childNodes[i-1]),i=n.length||0),a<o.childNodes.length&&(o=O_(o.childNodes[a]),a=0);let l=O_(n),u=R_(o);function d(h){if(h.childNodes.length)return!1;let y=h.length||0;return h===n&&i===y?!1:!(h===o&&a===0)}for(;l&&!d(l)&&l!==u;)l=P5(l);for(l===n?t.setStart(n,i):l!==null&&(l.nodeType===3?t.setStart(l,0):t.setStartBefore(l));u&&!d(u)&&u!==l;)u=M5(u);return u===o?t.setEnd(o,a):u!==null&&(u.nodeType===3?t.setEnd(u,u.length):t.setEndAfter(u)),t}function P5(r){if(r.firstChild)return r.firstChild;let t=r;for(;!t.nextSibling;)if(t=t.parentNode,!t)return null;return t.nextSibling}function M5(r){if(r.lastChild)return r.lastChild;let t=r;for(;!t.previousSibling;)if(t=t.parentNode,!t)return null;return t.previousSibling}function O_(r){for(;r.firstChild;)r=r.firstChild;return r}function R_(r){for(;r.lastChild;)r=r.lastChild;return r}H();var P0=nt(M_()),xo;(function(i){i[i.All=0]="All",i[i.Two=1]="Two",i[i.One=2]="One"})(xo||(xo={}));var Zr,M0;function wn(r,t,n){if(r.nodeType!==Node.ELEMENT_NODE)throw new Error("Can't generate CSS selector for non-element node type.");if(r.tagName.toLowerCase()==="html")return r.tagName.toLowerCase();let i={className:a=>!0,idName:a=>!0,optimizedMinLength:2,root:t.body,seedMinLength:1,tagName:a=>!0,threshold:1e3};Zr=et(et({},i),n),M0=j5(Zr.root,i);let o=k0(r,0,()=>k0(r,1,()=>k0(r,2)));if(o){let a=N_(D_(o,r));return a.length>0&&(o=a[0]),Kd(o)}else throw new Error("Selector was not found.")}function j5(r,t){return r.nodeType===Node.DOCUMENT_NODE?r:r===t.root?r.ownerDocument:r}function k0(r,t,n){let i=null,o=[],a=r,l=0;for(;a&&a!==Zr.root.parentElement;){let u=B0(F5(a))||B0(...H5(a))||B0(U5(a))||[$5()],d=q5(a);if(t===0)d&&(u=u.concat(u.filter(I0).map(h=>L0(h,d))));else if(t===1)u=u.slice(0,1),d&&(u=u.concat(u.filter(I0).map(h=>L0(h,d))));else if(t===2){let[h]=u=u.slice(0,1);d&&I0(h)&&(u=[L0(h,d)])}for(let h of u)h.level=l;if(o.push(u),o.length>=Zr.seedMinLength&&(i=k_(o,n),i))break;a=a.parentElement,l++}return i||(i=k_(o,n)),i}function k_(r,t){let n=N_(B_(r));if(n.length>Zr.threshold)return t?t():null;for(let i of n)if(I_(i))return i;return null}function Kd(r){let t=r[0],n=t.name;for(let i=1;i<r.length;i++){let o=r[i].level||0;t.level===o-1?n=`${r[i].name} > ${n}`:n=`${r[i].name} ${n}`,t=r[i]}return n}function L_(r){return r.map(t=>t.penalty).reduce((t,n)=>t+n,0)}function I_(r){switch(M0.querySelectorAll(Kd(r)).length){case 0:throw new Error(`Can't select any node with this selector: ${Kd(r)}`);case 1:return!0;default:return!1}}function F5(r){let t=r.getAttribute("id");return t&&Zr.idName(t)?{name:"#"+(0,P0.default)(t,{isIdentifier:!0}),penalty:0}:null}function H5(r){return Array.from(r.classList).filter(Zr.className).map(n=>({name:"."+(0,P0.default)(n,{isIdentifier:!0}),penalty:1}))}function U5(r){let t=r.tagName.toLowerCase();return Zr.tagName(t)?{name:t,penalty:2}:null}function $5(){return{name:"*",penalty:3}}function q5(r){let t=r.parentNode;if(!t)return null;let n=t.firstChild;if(!n)return null;let i=0;for(;n&&(n.nodeType===Node.ELEMENT_NODE&&i++,n!==r);)n=n.nextSibling;return i}function L0(r,t){return{name:r.name+`:nth-child(${t})`,penalty:r.penalty+1}}function I0(r){return r.name!=="html"&&!r.name.startsWith("#")}function B0(...r){let t=r.filter(W5);return t.length>0?t:null}function W5(r){return r!=null}function*B_(r,t=[]){if(r.length>0)for(let n of r[0])yield*B_(r.slice(1,r.length),t.concat(n));else yield t}function N_(r){return Array.from(r).sort((t,n)=>L_(t)-L_(n))}function*D_(r,t){if(r.length>2&&r.length>Zr.optimizedMinLength)for(let n=1;n<r.length-1;n++){let i=[...r];i.splice(n,1),I_(i)&&G5(i,t)&&(yield i,yield*D_(i,t))}}function G5(r,t){return M0.querySelector(Kd(r))===t}H();var Ve;(function(a){a[a.Highlight=0]="Highlight",a[a.Underline=1]="Underline",a[a.Bookmark=2]="Bookmark",a[a.Custom=3]="Custom",a[a.Comment=4]="Comment"})(Ve||(Ve={}));H();var N0=24,z5=24,j_="0 0 24 24",ni=(r,t,n,i="icon")=>`<svg xmlns="http://www.w3.org/2000/svg" width="${N0}" height="${z5}" viewBox="${j_}" preserveAspectRatio="xMidYMid meet" role="img" class="${i}" aria-labelledBy="${r}">
|
|
70
|
+
`}setFont(E){let T=this.current,I=this.commonObjs.get(E[0]),M=E[1];T.font=I,this.embedFonts&&!I.missingFile&&!this.embeddedFonts[I.loadedName]&&(this.addFontStyle(I),this.embeddedFonts[I.loadedName]=I),T.fontMatrix=I.fontMatrix||i.FONT_IDENTITY_MATRIX;let j="normal";I.black?j="900":I.bold&&(j="bold");let U=I.italic?"italic":"normal";M<0?(M=-M,T.fontDirection=-1):T.fontDirection=1,T.fontSize=M,T.fontFamily=I.loadedName,T.fontWeight=j,T.fontStyle=U,T.tspan=this.svgFactory.createElement("svg:tspan"),T.tspan.setAttributeNS(null,"y",g(-T.y)),T.xcoords=[],T.ycoords=[]}endText(){let E=this.current;E.textRenderingMode&i.TextRenderingMode.ADD_TO_PATH_FLAG&&E.txtElement?.hasChildNodes()&&(E.element=E.txtElement,this.clip("nonzero"),this.endPath())}setLineWidth(E){E>0&&(this.current.lineWidth=E)}setLineCap(E){this.current.lineCap=y[E]}setLineJoin(E){this.current.lineJoin=b[E]}setMiterLimit(E){this.current.miterLimit=E}setStrokeAlpha(E){this.current.strokeAlpha=E}setStrokeRGBColor(E,T,I){this.current.strokeColor=i.Util.makeHexColor(E,T,I)}setFillAlpha(E){this.current.fillAlpha=E}setFillRGBColor(E,T,I){this.current.fillColor=i.Util.makeHexColor(E,T,I),this.current.tspan=this.svgFactory.createElement("svg:tspan"),this.current.xcoords=[],this.current.ycoords=[]}setStrokeColorN(E){this.current.strokeColor=this._makeColorN_Pattern(E)}setFillColorN(E){this.current.fillColor=this._makeColorN_Pattern(E)}shadingFill(E){let T=this.viewport.width,I=this.viewport.height,M=i.Util.inverseTransform(this.transformMatrix),j=i.Util.applyTransform([0,0],M),U=i.Util.applyTransform([0,I],M),B=i.Util.applyTransform([T,0],M),N=i.Util.applyTransform([T,I],M),q=Math.min(j[0],U[0],B[0],N[0]),z=Math.min(j[1],U[1],B[1],N[1]),ne=Math.max(j[0],U[0],B[0],N[0]),oe=Math.max(j[1],U[1],B[1],N[1]),ae=this.svgFactory.createElement("svg:rect");ae.setAttributeNS(null,"x",q),ae.setAttributeNS(null,"y",z),ae.setAttributeNS(null,"width",ne-q),ae.setAttributeNS(null,"height",oe-z),ae.setAttributeNS(null,"fill",this._makeShadingPattern(E)),this.current.fillAlpha<1&&ae.setAttributeNS(null,"fill-opacity",this.current.fillAlpha),this._ensureTransformGroup().appendChild(ae)}_makeColorN_Pattern(E){return E[0]==="TilingPattern"?this._makeTilingPattern(E):this._makeShadingPattern(E)}_makeTilingPattern(E){let T=E[1],I=E[2],M=E[3]||i.IDENTITY_MATRIX,[j,U,B,N]=E[4],q=E[5],z=E[6],ne=E[7],oe=`shading${O++}`,[ae,te,le,xe]=i.Util.normalizeRect([...i.Util.applyTransform([j,U],M),...i.Util.applyTransform([B,N],M)]),[fe,J]=i.Util.singularValueDecompose2dScale(M),D=q*fe,k=z*J,x=this.svgFactory.createElement("svg:pattern");x.setAttributeNS(null,"id",oe),x.setAttributeNS(null,"patternUnits","userSpaceOnUse"),x.setAttributeNS(null,"width",D),x.setAttributeNS(null,"height",k),x.setAttributeNS(null,"x",`${ae}`),x.setAttributeNS(null,"y",`${te}`);let R=this.svg,L=this.transformMatrix,F=this.current.fillColor,W=this.current.strokeColor,V=this.svgFactory.create(le-ae,xe-te);if(this.svg=V,this.transformMatrix=M,ne===2){let Z=i.Util.makeHexColor(...T);this.current.fillColor=Z,this.current.strokeColor=Z}return this.executeOpTree(this.convertOpList(I)),this.svg=R,this.transformMatrix=L,this.current.fillColor=F,this.current.strokeColor=W,x.appendChild(V.childNodes[0]),this.defs.appendChild(x),`url(#${oe})`}_makeShadingPattern(E){switch(typeof E=="string"&&(E=this.objs.get(E)),E[0]){case"RadialAxial":let T=`shading${O++}`,I=E[3],M;switch(E[1]){case"axial":let j=E[4],U=E[5];M=this.svgFactory.createElement("svg:linearGradient"),M.setAttributeNS(null,"id",T),M.setAttributeNS(null,"gradientUnits","userSpaceOnUse"),M.setAttributeNS(null,"x1",j[0]),M.setAttributeNS(null,"y1",j[1]),M.setAttributeNS(null,"x2",U[0]),M.setAttributeNS(null,"y2",U[1]);break;case"radial":let B=E[4],N=E[5],q=E[6],z=E[7];M=this.svgFactory.createElement("svg:radialGradient"),M.setAttributeNS(null,"id",T),M.setAttributeNS(null,"gradientUnits","userSpaceOnUse"),M.setAttributeNS(null,"cx",N[0]),M.setAttributeNS(null,"cy",N[1]),M.setAttributeNS(null,"r",z),M.setAttributeNS(null,"fx",B[0]),M.setAttributeNS(null,"fy",B[1]),M.setAttributeNS(null,"fr",q);break;default:throw new Error(`Unknown RadialAxial type: ${E[1]}`)}for(let j of I){let U=this.svgFactory.createElement("svg:stop");U.setAttributeNS(null,"offset",j[0]),U.setAttributeNS(null,"stop-color",j[1]),M.appendChild(U)}return this.defs.appendChild(M),`url(#${T})`;case"Mesh":return(0,i.warn)("Unimplemented pattern Mesh"),null;case"Dummy":return"hotpink";default:throw new Error(`Unknown IR type: ${E[0]}`)}}setDash(E,T){this.current.dashArray=E,this.current.dashPhase=T}constructPath(E,T){let I=this.current,M=I.x,j=I.y,U=[],B=0;for(let N of E)switch(N|0){case i.OPS.rectangle:M=T[B++],j=T[B++];let q=T[B++],z=T[B++],ne=M+q,oe=j+z;U.push("M",g(M),g(j),"L",g(ne),g(j),"L",g(ne),g(oe),"L",g(M),g(oe),"Z");break;case i.OPS.moveTo:M=T[B++],j=T[B++],U.push("M",g(M),g(j));break;case i.OPS.lineTo:M=T[B++],j=T[B++],U.push("L",g(M),g(j));break;case i.OPS.curveTo:M=T[B+4],j=T[B+5],U.push("C",g(T[B]),g(T[B+1]),g(T[B+2]),g(T[B+3]),g(M),g(j)),B+=6;break;case i.OPS.curveTo2:U.push("C",g(M),g(j),g(T[B]),g(T[B+1]),g(T[B+2]),g(T[B+3])),M=T[B+2],j=T[B+3],B+=4;break;case i.OPS.curveTo3:M=T[B+2],j=T[B+3],U.push("C",g(T[B]),g(T[B+1]),g(M),g(j),g(M),g(j)),B+=4;break;case i.OPS.closePath:U.push("Z");break}U=U.join(" "),I.path&&E.length>0&&E[0]!==i.OPS.rectangle&&E[0]!==i.OPS.moveTo?U=I.path.getAttributeNS(null,"d")+U:(I.path=this.svgFactory.createElement("svg:path"),this._ensureTransformGroup().appendChild(I.path)),I.path.setAttributeNS(null,"d",U),I.path.setAttributeNS(null,"fill","none"),I.element=I.path,I.setCurrentPoint(M,j)}endPath(){let E=this.current;if(E.path=null,!this.pendingClip)return;if(!E.element){this.pendingClip=null;return}let T=`clippath${A++}`,I=this.svgFactory.createElement("svg:clipPath");I.setAttributeNS(null,"id",T),I.setAttributeNS(null,"transform",v(this.transformMatrix));let M=E.element.cloneNode(!0);if(this.pendingClip==="evenodd"?M.setAttributeNS(null,"clip-rule","evenodd"):M.setAttributeNS(null,"clip-rule","nonzero"),this.pendingClip=null,I.appendChild(M),this.defs.appendChild(I),E.activeClipUrl){E.clipGroup=null;for(let j of this.extraStack)j.clipGroup=null;I.setAttributeNS(null,"clip-path",E.activeClipUrl)}E.activeClipUrl=`url(#${T})`,this.tgrp=null}clip(E){this.pendingClip=E}closePath(){let E=this.current;if(E.path){let T=`${E.path.getAttributeNS(null,"d")}Z`;E.path.setAttributeNS(null,"d",T)}}setLeading(E){this.current.leading=-E}setTextRise(E){this.current.textRise=E}setTextRenderingMode(E){this.current.textRenderingMode=E}setHScale(E){this.current.textHScale=E/100}setRenderingIntent(E){}setFlatness(E){}setGState(E){for(let[T,I]of E)switch(T){case"LW":this.setLineWidth(I);break;case"LC":this.setLineCap(I);break;case"LJ":this.setLineJoin(I);break;case"ML":this.setMiterLimit(I);break;case"D":this.setDash(I[0],I[1]);break;case"RI":this.setRenderingIntent(I);break;case"FL":this.setFlatness(I);break;case"Font":this.setFont(I);break;case"CA":this.setStrokeAlpha(I);break;case"ca":this.setFillAlpha(I);break;default:(0,i.warn)(`Unimplemented graphic state operator ${T}`);break}}fill(){let E=this.current;E.element&&(E.element.setAttributeNS(null,"fill",E.fillColor),E.element.setAttributeNS(null,"fill-opacity",E.fillAlpha),this.endPath())}stroke(){let E=this.current;E.element&&(this._setStrokeAttributes(E.element),E.element.setAttributeNS(null,"fill","none"),this.endPath())}_setStrokeAttributes(E,T=1){let I=this.current,M=I.dashArray;T!==1&&M.length>0&&(M=M.map(function(j){return T*j})),E.setAttributeNS(null,"stroke",I.strokeColor),E.setAttributeNS(null,"stroke-opacity",I.strokeAlpha),E.setAttributeNS(null,"stroke-miterlimit",g(I.miterLimit)),E.setAttributeNS(null,"stroke-linecap",I.lineCap),E.setAttributeNS(null,"stroke-linejoin",I.lineJoin),E.setAttributeNS(null,"stroke-width",g(T*I.lineWidth)+"px"),E.setAttributeNS(null,"stroke-dasharray",M.map(g).join(" ")),E.setAttributeNS(null,"stroke-dashoffset",g(T*I.dashPhase)+"px")}eoFill(){this.current.element&&this.current.element.setAttributeNS(null,"fill-rule","evenodd"),this.fill()}fillStroke(){this.stroke(),this.fill()}eoFillStroke(){this.current.element&&this.current.element.setAttributeNS(null,"fill-rule","evenodd"),this.fillStroke()}closeStroke(){this.closePath(),this.stroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.closePath(),this.eoFillStroke()}paintSolidColorImageMask(){let E=this.svgFactory.createElement("svg:rect");E.setAttributeNS(null,"x","0"),E.setAttributeNS(null,"y","0"),E.setAttributeNS(null,"width","1px"),E.setAttributeNS(null,"height","1px"),E.setAttributeNS(null,"fill",this.current.fillColor),this._ensureTransformGroup().appendChild(E)}paintImageXObject(E){let T=E.startsWith("g_")?this.commonObjs.get(E):this.objs.get(E);if(!T){(0,i.warn)(`Dependent image with object ID ${E} is not ready yet`);return}this.paintInlineImageXObject(T)}paintInlineImageXObject(E,T){let I=E.width,M=E.height,j=p(E,this.forceDataSchema,!!T),U=this.svgFactory.createElement("svg:rect");U.setAttributeNS(null,"x","0"),U.setAttributeNS(null,"y","0"),U.setAttributeNS(null,"width",g(I)),U.setAttributeNS(null,"height",g(M)),this.current.element=U,this.clip("nonzero");let B=this.svgFactory.createElement("svg:image");B.setAttributeNS(h,"xlink:href",j),B.setAttributeNS(null,"x","0"),B.setAttributeNS(null,"y",g(-M)),B.setAttributeNS(null,"width",g(I)+"px"),B.setAttributeNS(null,"height",g(M)+"px"),B.setAttributeNS(null,"transform",`scale(${g(1/I)} ${g(-1/M)})`),T?T.appendChild(B):this._ensureTransformGroup().appendChild(B)}paintImageMaskXObject(E){let T=this.current,I=E.width,M=E.height,j=T.fillColor;T.maskId=`mask${C++}`;let U=this.svgFactory.createElement("svg:mask");U.setAttributeNS(null,"id",T.maskId);let B=this.svgFactory.createElement("svg:rect");B.setAttributeNS(null,"x","0"),B.setAttributeNS(null,"y","0"),B.setAttributeNS(null,"width",g(I)),B.setAttributeNS(null,"height",g(M)),B.setAttributeNS(null,"fill",j),B.setAttributeNS(null,"mask",`url(#${T.maskId})`),this.defs.appendChild(U),this._ensureTransformGroup().appendChild(B),this.paintInlineImageXObject(E,U)}paintFormXObjectBegin(E,T){if(Array.isArray(E)&&E.length===6&&this.transform(E[0],E[1],E[2],E[3],E[4],E[5]),T){let I=T[2]-T[0],M=T[3]-T[1],j=this.svgFactory.createElement("svg:rect");j.setAttributeNS(null,"x",T[0]),j.setAttributeNS(null,"y",T[1]),j.setAttributeNS(null,"width",g(I)),j.setAttributeNS(null,"height",g(M)),this.current.element=j,this.clip("nonzero"),this.endPath()}}paintFormXObjectEnd(){}_initialize(E){let T=this.svgFactory.create(E.width,E.height),I=this.svgFactory.createElement("svg:defs");T.appendChild(I),this.defs=I;let M=this.svgFactory.createElement("svg:g");return M.setAttributeNS(null,"transform",v(E.transform)),T.appendChild(M),this.svg=M,T}_ensureClipGroup(){if(!this.current.clipGroup){let E=this.svgFactory.createElement("svg:g");E.setAttributeNS(null,"clip-path",this.current.activeClipUrl),this.svg.appendChild(E),this.current.clipGroup=E}return this.current.clipGroup}_ensureTransformGroup(){return this.tgrp||(this.tgrp=this.svgFactory.createElement("svg:g"),this.tgrp.setAttributeNS(null,"transform",v(this.transformMatrix)),this.current.activeClipUrl?this._ensureClipGroup().appendChild(this.tgrp):this.svg.appendChild(this.tgrp)),this.tgrp}}}},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PDFNodeStream=void 0;var i=n(1),o=n(26);let a=vd(),l=ox(),u=sx(),d=bd(),h=/^file:\/\/\/[a-zA-Z]:\//;function y(C){let O=d.parse(C);return O.protocol==="file:"||O.host?O:/^[a-z]:[/\\]/i.test(C)?d.parse(`file:///${C}`):(O.host||(O.protocol="file:"),O)}class b{constructor(O){this.source=O,this.url=y(O.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.httpHeaders=this.isHttp&&O.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return(0,i.assert)(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new v(this):new f(this),this._fullRequestReader}getRangeReader(O,E){if(E<=this._progressiveDataLength)return null;let T=this.isFsUrl?new A(this,O,E):new g(this,O,E);return this._rangeRequestReaders.push(T),T}cancelAllRequests(O){this._fullRequestReader&&this._fullRequestReader.cancel(O);for(let E of this._rangeRequestReaders.slice(0))E.cancel(O)}}t.PDFNodeStream=b;class w{constructor(O){this._url=O.url,this._done=!1,this._storedError=null,this.onProgress=null;let E=O.source;this._contentLength=E.length,this._loaded=0,this._filename=null,this._disableRange=E.disableRange||!1,this._rangeChunkSize=E.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!E.disableStream,this._isRangeSupported=!E.disableRange,this._readableStream=null,this._readCapability=(0,i.createPromiseCapability)(),this._headersCapability=(0,i.createPromiseCapability)()}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let O=this._readableStream.read();return O===null?(this._readCapability=(0,i.createPromiseCapability)(),this.read()):(this._loaded+=O.length,this.onProgress&&this.onProgress({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(O).buffer,done:!1})}cancel(O){if(!this._readableStream){this._error(O);return}this._readableStream.destroy(O)}_error(O){this._storedError=O,this._readCapability.resolve()}_setReadableStream(O){this._readableStream=O,O.on("readable",()=>{this._readCapability.resolve()}),O.on("end",()=>{O.destroy(),this._done=!0,this._readCapability.resolve()}),O.on("error",E=>{this._error(E)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new i.AbortException("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class p{constructor(O){this._url=O.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=(0,i.createPromiseCapability)();let E=O.source;this._isStreamingSupported=!E.disableStream}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let O=this._readableStream.read();return O===null?(this._readCapability=(0,i.createPromiseCapability)(),this.read()):(this._loaded+=O.length,this.onProgress&&this.onProgress({loaded:this._loaded}),{value:new Uint8Array(O).buffer,done:!1})}cancel(O){if(!this._readableStream){this._error(O);return}this._readableStream.destroy(O)}_error(O){this._storedError=O,this._readCapability.resolve()}_setReadableStream(O){this._readableStream=O,O.on("readable",()=>{this._readCapability.resolve()}),O.on("end",()=>{O.destroy(),this._done=!0,this._readCapability.resolve()}),O.on("error",E=>{this._error(E)}),this._storedError&&this._readableStream.destroy(this._storedError)}}function m(C,O){return{protocol:C.protocol,auth:C.auth,host:C.hostname,port:C.port,path:C.path,method:"GET",headers:O}}class f extends w{constructor(O){super(O);let E=T=>{if(T.statusCode===404){let U=new i.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=U,this._headersCapability.reject(U);return}this._headersCapability.resolve(),this._setReadableStream(T);let I=U=>this._readableStream.headers[U.toLowerCase()],{allowRangeRequests:M,suggestedLength:j}=(0,o.validateRangeRequestCapabilities)({getResponseHeader:I,isHttp:O.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=M,this._contentLength=j||this._contentLength,this._filename=(0,o.extractFilenameFromHeader)(I)};this._request=null,this._url.protocol==="http:"?this._request=l.request(m(this._url,O.httpHeaders),E):this._request=u.request(m(this._url,O.httpHeaders),E),this._request.on("error",T=>{this._storedError=T,this._headersCapability.reject(T)}),this._request.end()}}class g extends p{constructor(O,E,T){super(O);this._httpHeaders={};for(let M in O.httpHeaders){let j=O.httpHeaders[M];typeof j!="undefined"&&(this._httpHeaders[M]=j)}this._httpHeaders.Range=`bytes=${E}-${T-1}`;let I=M=>{if(M.statusCode===404){let j=new i.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=j;return}this._setReadableStream(M)};this._request=null,this._url.protocol==="http:"?this._request=l.request(m(this._url,this._httpHeaders),I):this._request=u.request(m(this._url,this._httpHeaders),I),this._request.on("error",M=>{this._storedError=M}),this._request.end()}}class v extends w{constructor(O){super(O);let E=decodeURIComponent(this._url.path);h.test(this._url.href)&&(E=E.replace(/^\//,"")),a.lstat(E,(T,I)=>{if(T){T.code==="ENOENT"&&(T=new i.MissingPDFException(`Missing PDF "${E}".`)),this._storedError=T,this._headersCapability.reject(T);return}this._contentLength=I.size,this._setReadableStream(a.createReadStream(E)),this._headersCapability.resolve()})}}class A extends p{constructor(O,E,T){super(O);let I=decodeURIComponent(this._url.path);h.test(this._url.href)&&(I=I.replace(/^\//,"")),this._setReadableStream(a.createReadStream(I,{start:E,end:T-1}))}}},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createResponseStatusError=d,t.extractFilenameFromHeader=u,t.validateRangeRequestCapabilities=l,t.validateResponseStatus=h;var i=n(1),o=n(27),a=n(5);function l({getResponseHeader:y,isHttp:b,rangeChunkSize:w,disableRange:p}){let m={allowRangeRequests:!1,suggestedLength:void 0},f=parseInt(y("Content-Length"),10);return!Number.isInteger(f)||(m.suggestedLength=f,f<=2*w)||p||!b||y("Accept-Ranges")!=="bytes"||(y("Content-Encoding")||"identity")!=="identity"||(m.allowRangeRequests=!0),m}function u(y){let b=y("Content-Disposition");if(b){let w=(0,o.getFilenameFromContentDispositionHeader)(b);if(w.includes("%"))try{w=decodeURIComponent(w)}catch(p){}if((0,a.isPdfFile)(w))return w}return null}function d(y,b){return y===404||y===0&&b.startsWith("file:")?new i.MissingPDFException('Missing PDF "'+b+'".'):new i.UnexpectedResponseException(`Unexpected server response (${y}) while retrieving PDF "${b}".`,y)}function h(y){return y===200||y===206}},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getFilenameFromContentDispositionHeader=o;var i=n(1);function o(a){let l=!0,u=d("filename\\*","i").exec(a);if(u){u=u[1];let f=w(u);return f=unescape(f),f=p(f),f=m(f),y(f)}if(u=b(a),u){let f=m(u);return y(f)}if(u=d("filename","i").exec(a),u){u=u[1];let f=w(u);return f=m(f),y(f)}function d(f,g){return new RegExp("(?:^|;)\\s*"+f+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',g)}function h(f,g){if(f){if(!/^[\x00-\xFF]+$/.test(g))return g;try{let v=new TextDecoder(f,{fatal:!0}),A=(0,i.stringToBytes)(g);g=v.decode(A),l=!1}catch(v){}}return g}function y(f){return l&&/[\x80-\xff]/.test(f)&&(f=h("utf-8",f),l&&(f=h("iso-8859-1",f))),f}function b(f){let g=[],v,A=d("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(v=A.exec(f))!==null;){let[,O,E,T]=v;if(O=parseInt(O,10),O in g){if(O===0)break;continue}g[O]=[E,T]}let C=[];for(let O=0;O<g.length&&O in g;++O){let[E,T]=g[O];T=w(T),E&&(T=unescape(T),O===0&&(T=p(T))),C.push(T)}return C.join("")}function w(f){if(f.startsWith('"')){let g=f.slice(1).split('\\"');for(let v=0;v<g.length;++v){let A=g[v].indexOf('"');A!==-1&&(g[v]=g[v].slice(0,A),g.length=v+1),g[v]=g[v].replace(/\\(.)/g,"$1")}f=g.join('"')}return f}function p(f){let g=f.indexOf("'");if(g===-1)return f;let v=f.slice(0,g),C=f.slice(g+1).replace(/^[^']*'/,"");return h(v,C)}function m(f){return!f.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(f)?f:f.replace(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(g,v,A,C){if(A==="q"||A==="Q")return C=C.replace(/_/g," "),C=C.replace(/=([0-9a-fA-F]{2})/g,function(O,E){return String.fromCharCode(parseInt(E,16))}),h(v,C);try{C=atob(C)}catch(O){}return h(v,C)})}return""}},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PDFNetworkStream=void 0;var i=n(1),o=n(26);let a=200,l=206;function u(w){let p=w.response;return typeof p!="string"?p:(0,i.stringToBytes)(p).buffer}class d{constructor(p,m={}){this.url=p,this.isHttp=/^https?:/i.test(p),this.httpHeaders=this.isHttp&&m.httpHeaders||Object.create(null),this.withCredentials=m.withCredentials||!1,this.getXhr=m.getXhr||function(){return new XMLHttpRequest},this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(p,m,f){let g={begin:p,end:m};for(let v in f)g[v]=f[v];return this.request(g)}requestFull(p){return this.request(p)}request(p){let m=this.getXhr(),f=this.currXhrId++,g=this.pendingRequests[f]={xhr:m};m.open("GET",this.url),m.withCredentials=this.withCredentials;for(let v in this.httpHeaders){let A=this.httpHeaders[v];typeof A!="undefined"&&m.setRequestHeader(v,A)}return this.isHttp&&"begin"in p&&"end"in p?(m.setRequestHeader("Range",`bytes=${p.begin}-${p.end-1}`),g.expectedStatus=l):g.expectedStatus=a,m.responseType="arraybuffer",p.onError&&(m.onerror=function(v){p.onError(m.status)}),m.onreadystatechange=this.onStateChange.bind(this,f),m.onprogress=this.onProgress.bind(this,f),g.onHeadersReceived=p.onHeadersReceived,g.onDone=p.onDone,g.onError=p.onError,g.onProgress=p.onProgress,m.send(null),f}onProgress(p,m){let f=this.pendingRequests[p];!f||f.onProgress?.(m)}onStateChange(p,m){let f=this.pendingRequests[p];if(!f)return;let g=f.xhr;if(g.readyState>=2&&f.onHeadersReceived&&(f.onHeadersReceived(),delete f.onHeadersReceived),g.readyState!==4||!(p in this.pendingRequests))return;if(delete this.pendingRequests[p],g.status===0&&this.isHttp){f.onError?.(g.status);return}let v=g.status||a;if(!(v===a&&f.expectedStatus===l)&&v!==f.expectedStatus){f.onError?.(g.status);return}let C=u(g);if(v===l){let O=g.getResponseHeader("Content-Range"),E=/bytes (\d+)-(\d+)\/(\d+)/.exec(O);f.onDone({begin:parseInt(E[1],10),chunk:C})}else C?f.onDone({begin:0,chunk:C}):f.onError?.(g.status)}getRequestXhr(p){return this.pendingRequests[p].xhr}isPendingRequest(p){return p in this.pendingRequests}abortRequest(p){let m=this.pendingRequests[p].xhr;delete this.pendingRequests[p],m.abort()}}class h{constructor(p){this._source=p,this._manager=new d(p.url,{httpHeaders:p.httpHeaders,withCredentials:p.withCredentials}),this._rangeChunkSize=p.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(p){let m=this._rangeRequestReaders.indexOf(p);m>=0&&this._rangeRequestReaders.splice(m,1)}getFullReader(){return(0,i.assert)(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new y(this._manager,this._source),this._fullRequestReader}getRangeReader(p,m){let f=new b(this._manager,p,m);return f.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(f),f}cancelAllRequests(p){this._fullRequestReader?.cancel(p);for(let m of this._rangeRequestReaders.slice(0))m.cancel(p)}}t.PDFNetworkStream=h;class y{constructor(p,m){this._manager=p;let f={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=m.url,this._fullRequestId=p.requestFull(f),this._headersReceivedCapability=(0,i.createPromiseCapability)(),this._disableRange=m.disableRange||!1,this._contentLength=m.length,this._rangeChunkSize=m.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){let p=this._fullRequestId,m=this._manager.getRequestXhr(p),f=A=>m.getResponseHeader(A),{allowRangeRequests:g,suggestedLength:v}=(0,o.validateRangeRequestCapabilities)({getResponseHeader:f,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});g&&(this._isRangeSupported=!0),this._contentLength=v||this._contentLength,this._filename=(0,o.extractFilenameFromHeader)(f),this._isRangeSupported&&this._manager.abortRequest(p),this._headersReceivedCapability.resolve()}_onDone(p){if(p&&(this._requests.length>0?this._requests.shift().resolve({value:p.chunk,done:!1}):this._cachedChunks.push(p.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(let m of this._requests)m.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(p){this._storedError=(0,o.createResponseStatusError)(p,this._url),this._headersReceivedCapability.reject(this._storedError);for(let m of this._requests)m.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(p){this.onProgress?.({loaded:p.loaded,total:p.lengthComputable?p.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersReceivedCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let p=(0,i.createPromiseCapability)();return this._requests.push(p),p.promise}cancel(p){this._done=!0,this._headersReceivedCapability.reject(p);for(let m of this._requests)m.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class b{constructor(p,m,f){this._manager=p;let g={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=p.url,this._requestId=p.requestRange(m,f,g),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_close(){this.onClosed?.(this)}_onDone(p){let m=p.chunk;this._requests.length>0?this._requests.shift().resolve({value:m,done:!1}):this._queuedChunk=m,this._done=!0;for(let f of this._requests)f.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(p){this._storedError=(0,o.createResponseStatusError)(p,this._url);for(let m of this._requests)m.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(p){this.isStreamingSupported||this.onProgress?.({loaded:p.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){let m=this._queuedChunk;return this._queuedChunk=null,{value:m,done:!1}}if(this._done)return{value:void 0,done:!0};let p=(0,i.createPromiseCapability)();return this._requests.push(p),p.promise}cancel(p){this._done=!0;for(let m of this._requests)m.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}},(r,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PDFFetchStream=void 0;var i=n(1),o=n(26);function a(y,b,w){return{method:"GET",headers:y,signal:w?.signal,mode:"cors",credentials:b?"include":"same-origin",redirect:"follow"}}function l(y){let b=new Headers;for(let w in y){let p=y[w];typeof p!="undefined"&&b.append(w,p)}return b}class u{constructor(b){this.source=b,this.isHttp=/^https?:/i.test(b.url),this.httpHeaders=this.isHttp&&b.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return(0,i.assert)(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new d(this),this._fullRequestReader}getRangeReader(b,w){if(w<=this._progressiveDataLength)return null;let p=new h(this,b,w);return this._rangeRequestReaders.push(p),p}cancelAllRequests(b){this._fullRequestReader&&this._fullRequestReader.cancel(b);for(let w of this._rangeRequestReaders.slice(0))w.cancel(b)}}t.PDFFetchStream=u;class d{constructor(b){this._stream=b,this._reader=null,this._loaded=0,this._filename=null;let w=b.source;this._withCredentials=w.withCredentials||!1,this._contentLength=w.length,this._headersCapability=(0,i.createPromiseCapability)(),this._disableRange=w.disableRange||!1,this._rangeChunkSize=w.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),typeof AbortController!="undefined"&&(this._abortController=new AbortController),this._isStreamingSupported=!w.disableStream,this._isRangeSupported=!w.disableRange,this._headers=l(this._stream.httpHeaders);let p=w.url;fetch(p,a(this._headers,this._withCredentials,this._abortController)).then(m=>{if(!(0,o.validateResponseStatus)(m.status))throw(0,o.createResponseStatusError)(m.status,p);this._reader=m.body.getReader(),this._headersCapability.resolve();let f=A=>m.headers.get(A),{allowRangeRequests:g,suggestedLength:v}=(0,o.validateRangeRequestCapabilities)({getResponseHeader:f,isHttp:this._stream.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=g,this._contentLength=v||this._contentLength,this._filename=(0,o.extractFilenameFromHeader)(f),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new i.AbortException("Streaming is disabled."))}).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;let{value:b,done:w}=await this._reader.read();return w?{value:b,done:w}:(this._loaded+=b.byteLength,this.onProgress&&this.onProgress({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(b).buffer,done:!1})}cancel(b){this._reader&&this._reader.cancel(b),this._abortController&&this._abortController.abort()}}class h{constructor(b,w,p){this._stream=b,this._reader=null,this._loaded=0;let m=b.source;this._withCredentials=m.withCredentials||!1,this._readCapability=(0,i.createPromiseCapability)(),this._isStreamingSupported=!m.disableStream,typeof AbortController!="undefined"&&(this._abortController=new AbortController),this._headers=l(this._stream.httpHeaders),this._headers.append("Range",`bytes=${w}-${p-1}`);let f=m.url;fetch(f,a(this._headers,this._withCredentials,this._abortController)).then(g=>{if(!(0,o.validateResponseStatus)(g.status))throw(0,o.createResponseStatusError)(g.status,f);this._readCapability.resolve(),this._reader=g.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;let{value:b,done:w}=await this._reader.read();return w?{value:b,done:w}:(this._loaded+=b.byteLength,this.onProgress&&this.onProgress({loaded:this._loaded}),{value:new Uint8Array(b).buffer,done:!1})}cancel(b){this._reader&&this._reader.cancel(b),this._abortController&&this._abortController.abort()}}}],__webpack_module_cache__={};function __w_pdfjs_require__(r){var t=__webpack_module_cache__[r];if(t!==void 0)return t.exports;var n=__webpack_module_cache__[r]={exports:{}};return __webpack_modules__[r](n,n.exports,__w_pdfjs_require__),n.exports}var __webpack_exports__={};return(()=>{var r=__webpack_exports__;Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"AnnotationLayer",{enumerable:!0,get:function(){return o.AnnotationLayer}}),Object.defineProperty(r,"AnnotationMode",{enumerable:!0,get:function(){return t.AnnotationMode}}),Object.defineProperty(r,"CMapCompressionType",{enumerable:!0,get:function(){return t.CMapCompressionType}}),Object.defineProperty(r,"GlobalWorkerOptions",{enumerable:!0,get:function(){return a.GlobalWorkerOptions}}),Object.defineProperty(r,"InvalidPDFException",{enumerable:!0,get:function(){return t.InvalidPDFException}}),Object.defineProperty(r,"LoopbackPort",{enumerable:!0,get:function(){return n.LoopbackPort}}),Object.defineProperty(r,"MissingPDFException",{enumerable:!0,get:function(){return t.MissingPDFException}}),Object.defineProperty(r,"OPS",{enumerable:!0,get:function(){return t.OPS}}),Object.defineProperty(r,"PDFDataRangeTransport",{enumerable:!0,get:function(){return n.PDFDataRangeTransport}}),Object.defineProperty(r,"PDFDateString",{enumerable:!0,get:function(){return i.PDFDateString}}),Object.defineProperty(r,"PDFWorker",{enumerable:!0,get:function(){return n.PDFWorker}}),Object.defineProperty(r,"PasswordResponses",{enumerable:!0,get:function(){return t.PasswordResponses}}),Object.defineProperty(r,"PermissionFlag",{enumerable:!0,get:function(){return t.PermissionFlag}}),Object.defineProperty(r,"PixelsPerInch",{enumerable:!0,get:function(){return i.PixelsPerInch}}),Object.defineProperty(r,"RenderingCancelledException",{enumerable:!0,get:function(){return i.RenderingCancelledException}}),Object.defineProperty(r,"SVGGraphics",{enumerable:!0,get:function(){return d.SVGGraphics}}),Object.defineProperty(r,"UNSUPPORTED_FEATURES",{enumerable:!0,get:function(){return t.UNSUPPORTED_FEATURES}}),Object.defineProperty(r,"UnexpectedResponseException",{enumerable:!0,get:function(){return t.UnexpectedResponseException}}),Object.defineProperty(r,"Util",{enumerable:!0,get:function(){return t.Util}}),Object.defineProperty(r,"VerbosityLevel",{enumerable:!0,get:function(){return t.VerbosityLevel}}),Object.defineProperty(r,"XfaLayer",{enumerable:!0,get:function(){return h.XfaLayer}}),Object.defineProperty(r,"build",{enumerable:!0,get:function(){return n.build}}),Object.defineProperty(r,"createPromiseCapability",{enumerable:!0,get:function(){return t.createPromiseCapability}}),Object.defineProperty(r,"createValidAbsoluteUrl",{enumerable:!0,get:function(){return t.createValidAbsoluteUrl}}),Object.defineProperty(r,"getDocument",{enumerable:!0,get:function(){return n.getDocument}}),Object.defineProperty(r,"getFilenameFromUrl",{enumerable:!0,get:function(){return i.getFilenameFromUrl}}),Object.defineProperty(r,"getPdfFilenameFromUrl",{enumerable:!0,get:function(){return i.getPdfFilenameFromUrl}}),Object.defineProperty(r,"getXfaPageViewport",{enumerable:!0,get:function(){return i.getXfaPageViewport}}),Object.defineProperty(r,"isPdfFile",{enumerable:!0,get:function(){return i.isPdfFile}}),Object.defineProperty(r,"loadScript",{enumerable:!0,get:function(){return i.loadScript}}),Object.defineProperty(r,"renderTextLayer",{enumerable:!0,get:function(){return u.renderTextLayer}}),Object.defineProperty(r,"shadow",{enumerable:!0,get:function(){return t.shadow}}),Object.defineProperty(r,"version",{enumerable:!0,get:function(){return n.version}});var t=__w_pdfjs_require__(1),n=__w_pdfjs_require__(4),i=__w_pdfjs_require__(5),o=__w_pdfjs_require__(20),a=__w_pdfjs_require__(13),l=__w_pdfjs_require__(3),u=__w_pdfjs_require__(23),d=__w_pdfjs_require__(24),h=__w_pdfjs_require__(22);let y="2.14.305",b="eaaa8b4ad";if(l.isNodeJS){let{PDFNodeStream:w}=__w_pdfjs_require__(25);(0,n.setPDFNetworkStreamFactory)(p=>new w(p))}else{let{PDFNetworkStream:w}=__w_pdfjs_require__(28),{PDFFetchStream:p}=__w_pdfjs_require__(29);(0,n.setPDFNetworkStreamFactory)(m=>(0,i.isValidFetchUrl)(m.url)?new p(m):new w(m))}})(),__webpack_exports__})())});var U8={};BP(U8,{Link:()=>Ul,default:()=>F8,load:()=>H8});H();H();H();var dw=nt(cw()),hw=nt(Un());H();var uw=nt(Un());function Ks(r,t){return uw.TaJson.deserialize(r,t)}var bo=class extends dw.Publication{static async fromUrl(t,n){let o=await(await fetch(t.href,n)).json(),a=Ks(o,bo);return a.manifestUrl=t,a}get readingOrder(){return this.Spine??[]}get resources(){return this.Resources??[]}get tableOfContents(){return this.sample?.isSampleRead&&this.positions?.length>0?this.limitedTOC():this.TOC}limitedTOC(){function t(i){for(let o=0;o<i.Children.length;o++){let a=i.Children[o];a.Href=void 0,a.Children&&t(a)}}return this.TOC.map(i=>{if(i.Href){let o=this.positionsByHref(this.getRelativeHref(i.Href));if(o?.length>0){let a=o[0],l=Math.round((a.locations.totalProgression?a.locations.totalProgression:0)*100);this.sample?.limit&&(l<=this.sample?.limit||(i.Href=void 0,i.Children&&t(i)))}}return i})}get landmarks(){return this.Landmarks}get pageList(){return this.PageList}get isFixedLayout(){return this.Metadata.Rendition?.Layout==="fixed"}get isReflowable(){return!this.isFixedLayout}get layout(){return this.isFixedLayout?"fixed":"reflowable"}get hasMediaOverlays(){return this.readingOrder?this.readingOrder.filter(t=>t.Properties?.MediaOverlay).length>0:!1}getStartLink(){if(this.readingOrder!==void 0&&this.readingOrder.length>0)return this.readingOrder[0]}getPreviousSpineItem(t){let n=this.getSpineIndex(t);if(n!==void 0&&this.readingOrder!==void 0&&n>0)return this.readingOrder[n-1]}getNextSpineItem(t){let n=this.getSpineIndex(t);if(n!==void 0&&this.readingOrder!==void 0&&n<this.readingOrder.length-1)return this.readingOrder[n+1]}getSpineItem(t){let n=this.getSpineIndex(t);if(n!==void 0&&this.readingOrder!==void 0)return this.readingOrder[n]}getSpineIndex(t){return this.readingOrder?.findIndex(n=>n.Href&&this.getAbsoluteHref(n.Href)===t)}getAbsoluteHref(t){return new URL(t,this.manifestUrl.href).href}getRelativeHref(t){let n=this.manifestUrl.href.replace("/manifest.json",""),i=t.replace(n,"");return i.indexOf("#")>0&&(i=i.slice(0,i.indexOf("#"))),i.charAt(0)==="/"&&(i=i.substring(1)),i}getTOCItemAbsolute(t){let n=this.getAbsoluteHref(t),i=(a,l)=>{for(let u=0;u<l.length;u++){let d=l[u];if(d.Href){let h=d.Href.indexOf("#")!==-1?d.Href.slice(0,d.Href.indexOf("#")):d.Href;if(this.getAbsoluteHref(h)===a)return d}if(d.Children){let h=i(a,d.Children);if(h!==void 0)return h}}},o=i(n,this.tableOfContents);return o===void 0&&this.readingOrder!==void 0&&(o=i(n,this.readingOrder)),o}getTOCItem(t){let n=(o,a)=>{for(let l=0;l<a.length;l++){let u=a[l];if(u.Href&&this.getAbsoluteHref(u.Href)===o)return u;if(u.Children){let d=n(o,u.Children);if(d!==void 0)return d}}},i=n(t,this.tableOfContents);if(i===void 0&&this.readingOrder!==void 0&&(i=n(t,this.readingOrder)),i===void 0&&t.indexOf("#")!==-1){let o=t.slice(0,t.indexOf("#"));i=n(o,this.tableOfContents),i===void 0&&this.readingOrder!==void 0&&(i=n(o,this.readingOrder))}return i}positionsByHref(t){let n=decodeURI(t)??"";return this.positions?.filter(i=>n.includes(i.href))}async autoGeneratePositions(t,n=ZL){let i=0,o=0,a=[];if(this.readingOrder!==void 0)for(let u of this.readingOrder)if(this.isFixedLayout){let d={href:u.Href,locations:{progression:0,position:i+1},type:u.TypeLink};a.push(d),i=i+1}else{let d=this.getAbsoluteHref(u.Href),h=await n(d,t);u.contentLength=h,o+=h;let b=Math.max(1,Math.ceil(h/1024));for(let w=0;w<b;w++){let p={href:u.Href,locations:{progression:w/b,position:i+(w+1)},type:u.TypeLink};a.push(p)}i=i+b}var l=0;if(this.isReflowable&&this.readingOrder!==void 0)for(let u of this.readingOrder){if(!u.contentLength){console.error("Link is missing contentLength",u);return}u.contentWeight=100/o*u.contentLength,l=l+u.contentWeight}for(let u of a){let d=a.filter(y=>y.href===decodeURI(u.href)),h=Math.ceil((u.locations.progression?u.locations.progression:0)*(d.length-1));u.locations.position&&(u.locations.totalProgression=(u.locations.position-1)/a.length),u.locations.remainingPositions=Math.abs(h-(d.length-1)),u.locations.position&&(u.locations.totalRemainingPositions=Math.abs(u.locations.position-1-(a.length-1)))}this.positions=a}async fetchPositionsFromService(t,n){let o=await(await fetch(t,n)).json();this.positions=o.positions}async fetchWeightsFromService(t,n){if(this.isFixedLayout){console.warn("Not fetching weights from service for fixed layout publication.");return}let o=await(await fetch(t,n)).json();this.readingOrder!==void 0&&this.readingOrder.forEach(a=>{a.contentWeight=o[a.Href]})}};bo=Lc([(0,hw.JsonObject)()],bo);var ZL=async(r,t)=>(await(await fetch(r,t)).blob()).size;H();H();var Ys=class{json(){return JSON.stringify(this)}},fw=class extends Ys{constructor(t,n,i){super();this.value=t,this.ref=n,this.name=i}toString(){return this.value}},pw=class extends Ys{constructor(t,n,i){super();this.value=t,this.ref=n,this.name=i}toString(){return this.value}toJson(){return JSON.parse(this.value)}},gw=class extends Ys{constructor(t,n,i,o){super();this.value=t,this.values=n,this.ref=i,this.name=o}toString(){return this.values[this.value]}},mw=class extends Ys{constructor(t,n,i,o,a,l,u){super();this.countDecimals=function(t){return t%1!=0?t.toString().split(".")[1].length:1};this.value=t,this.min=n,this.max=i,this.step=o,this.suffix=a,this.ref=l,this.name=u}toString(){return this.value.toString()+this.suffix}increment(){let t=this.countDecimals(this.max);parseFloat(this.value.toFixed(t))<this.max&&(this.value=parseFloat(this.value.toFixed(t))+this.step)}decrement(){let t=this.countDecimals(this.min);parseFloat(this.value.toFixed(t))>this.min&&(this.value=parseFloat(this.value.toFixed(t))-this.step)}},Xa=class extends Ys{constructor(t,n,i,o,a){super();this.value=i,this.onValue=t,this.offValue=n,this.ref=o,this.name=a}toString(){return this.value?this.onValue:this.offValue}switch(){this.value=!this.value}},Wr=class{constructor(){this.properties=[]}addIncremental(t,n,i,o,a,l,u){this.properties.push(new mw(t,n,i,o,a,l,u))}addStringable(t,n,i){this.properties.push(new fw(t,n,i))}addJSONable(t,n,i){this.properties.push(new pw(t,n,i))}addSwitchable(t,n,i,o,a){this.properties.push(new Xa(t,n,i,o,a))}addEnumerable(t,n,i,o){this.properties.push(new gw(t,n,i,o))}getByRef(t){let n=this.properties.filter(i=>i.ref===t);return n.length>0?n[0]:null}getByKey(t){let n=this.properties.filter(i=>i.key===t);return n.length>0?n[0]:null}};H();var wi=class{},me=wi;me.FONT_SIZE_REF="fontSize",me.FONT_FAMILY_REF="fontFamily",me.FONT_OVERRIDE_REF="fontOverride",me.APPEARANCE_REF="appearance",me.SCROLL_REF="scroll",me.TEXT_ALIGNMENT_REF="textAlign",me.COLUMN_COUNT_REF="colCount",me.WORD_SPACING_REF="wordSpacing",me.LETTER_SPACING_REF="letterSpacing",me.PAGE_MARGINS_REF="pageMargins",me.LINE_HEIGHT_REF="lineHeight",me.FONT_SIZE_KEY="--USER__"+wi.FONT_SIZE_REF,me.FONT_FAMILY_KEY="--USER__"+wi.FONT_FAMILY_REF,me.FONT_OVERRIDE_KEY="--USER__"+wi.FONT_OVERRIDE_REF,me.APPEARANCE_KEY="--USER__"+wi.APPEARANCE_REF,me.SCROLL_KEY="--USER__"+wi.SCROLL_REF,me.TEXT_ALIGNMENT_KEY="--USER__"+wi.TEXT_ALIGNMENT_REF,me.COLUMN_COUNT_KEY="--USER__"+wi.COLUMN_COUNT_REF,me.WORD_SPACING_KEY="--USER__"+wi.WORD_SPACING_REF,me.LETTER_SPACING_KEY="--USER__"+wi.LETTER_SPACING_REF,me.PAGE_MARGINS_KEY="--USER__"+wi.PAGE_MARGINS_REF,me.LINE_HEIGHT_KEY="--USER__"+wi.LINE_HEIGHT_REF;H();function Ie(r,t){return r.querySelector(t)}function mt(r,t){let n=Ie(r,t);if(n&&n instanceof HTMLElement)return n;throw new Error("required element "+t+" not found")}function un(r,t){if(r===null)throw new Error("parent element is null");return r.querySelector(t)}function Gr(r,t){let n=un(r,t);if(n)return n;throw new Error("required element "+t+" not found in iframe")}function Cn(r,t,n){r.setAttribute(t,n)}H();H();var d_=nt(E0());var wl=class{constructor(t){this.getScrollingElement=t=>t.scrollingElement?t.scrollingElement:t.body;this.navigator=t}async handleFootnote(t,n){let i=t.getAttribute("href");if(i&&i.indexOf("#")>0){let a=function(u){let d=document.location.href;return new URL(u,d).href},o=i.substring(i.indexOf("#")+1),l=a(i);l&&(l=l.substring(0,l.indexOf("#")),n.preventDefault(),n.stopPropagation(),this.navigator.api?.getContent?await this.navigator.api?.getContent(i).then(u=>{let y=new DOMParser().parseFromString(u,"text/html").querySelector("#"+o);y&&(n.preventDefault(),n.stopPropagation(),this.showPopup(y,n))}):await fetch(l,this.navigator.requestConfig).then(u=>u.text()).then(async u=>{let y=new DOMParser().parseFromString(u,"text/html").querySelector("#"+o);y&&(n.preventDefault(),n.stopPropagation(),this.showPopup(y,n))}))}}async hidePopover(){let t=this.navigator.iframes[0].contentDocument?.getElementById("d2-popover");t&&t.parentElement?.removeChild(t);let n=mt(document,"#iframe-wrapper");n.style.overflow="auto"}async showPopover(t,n){let i=t.getAttribute("href"),o=t.getAttribute("src");function a(l){let u=document.location.href;return new URL(l,u).href}if(i){let l=a(i);if(l){n.preventDefault(),n.stopPropagation();let u=this.navigator.iframes[0].contentDocument?.getElementById("d2-popover");u&&u.parentElement?.removeChild(u);let d=document.createElement("div");d.id="d2-popover",d.className="d2-popover is-active";let h=mt(document,"#iframe-wrapper");h.style.overflow="hidden",d.style.top=h.scrollTop+"px",d.style.height=h.clientHeight*.9+"px";let y=document.createElement("div");y.className="d2-popover-wrapper",d.appendChild(y);let b=document.createElement("div");b.className="d2-popover-content",y.appendChild(b),this.navigator.api?.getContent?await this.navigator.api?.getContent(i).then(m=>{b.innerHTML=m;let f=this.navigator.iframes[0].contentDocument;f&&f.body.appendChild(d)}):await fetch(l,this.navigator.requestConfig).then(m=>m.text()).then(async m=>{b.innerHTML=m;let f=this.navigator.iframes[0].contentDocument;f&&f.body.appendChild(d)});let w=this.navigator.iframes[0].contentWindow;if(!w)return;let p=this;w.onclick=function(m){n.target!==m.target&&d.parentElement&&(p.hidePopover(),w&&(w.onclick=null))}}}else if(o&&a(o)){n.preventDefault(),n.stopPropagation();let u=this.navigator.iframes[0].contentDocument?.getElementById("d2-popover");u&&u.parentElement?.removeChild(u);let d=document.createElement("div");d.id="d2-popover",d.className="d2-popover is-active";let h=mt(document,"#iframe-wrapper");h.style.overflow="hidden",d.style.top=h.scrollTop+"px",d.style.height=h.clientHeight*.9+"px";let y=document.createElement("div");y.className="d2-popover-wrapper",d.appendChild(y);let b=document.createElement("img");b.className="d2-popover-content",y.appendChild(b),b.src=o;let w=this.navigator.iframes[0].contentDocument;w&&w.body.appendChild(d);let p=this.navigator.iframes[0].contentWindow;if(!p)return;let m=this;p.onclick=function(f){n.target!==f.target&&d.parentElement&&(m.hidePopover(),p&&(p.onclick=null))}}}showPopup(t,n){let i=this.navigator.iframes[0].contentDocument?.getElementById("d2-popup");i&&i.parentElement?.removeChild(i);let o=document.createElement("aside");o.id="d2-popup",o.className="d2-popup is-active";let a=document.createElement("div");a.className="d2-popup-wrapper",o.appendChild(a);let l=document.createElement("div");l.className="d2-popup-content",a.appendChild(l);let u=document.createElement("p");l.appendChild(u),typeof t=="string"?u.innerHTML=t:u.innerHTML=(0,d_.default)(t.innerHTML,{allowedTags:[],allowedAttributes:{}});let d=this.navigator.view?.isPaginated(),h=this.navigator.iframes[0].contentDocument;if(!h)return;let y=this.getScrollingElement(h),b=d?y.scrollLeft:0,w=d?y.scrollTop:0,p=n.x+b,m=n.y+w;o.style.top=m+"px",d&&(o.style.left=p+"px"),h.body.appendChild(o);let f=this.navigator.iframes[0].contentWindow;!f||(f.onclick=function(g){n.target!==g.target&&o.parentElement&&(o.style.display="none",o.parentElement.removeChild(o),f&&(f.onclick=null))})}};var $d=nt(Jt());function Ee(r,t,n){r&&r.addEventListener(t,n,!0)}function je(r,t,n){r&&r.removeEventListener(t,n,!0)}var qd=class{constructor(t){this.onInternalLink=()=>{};this.onClickThrough=()=>{};this.checkForLink=t=>{let n=t.target;for(;n&&n.tagName.toLowerCase()!=="body";){if(n.tagName.toLowerCase()==="a"&&n.href)return n;n=n.parentElement}return null};this.linkInPublication=(t,n)=>t.some(i=>!i.Rel?.includes("external")&&this.navigator.publication.getRelativeHref(n).includes(i.Href));this.isReadingOrderInternal=t=>($d.default.log("clickedLink: ",t),this.linkInPublication(this.navigator.publication.readingOrder,t.href));this.isResourceInternal=t=>($d.default.log("clickedLink: ",t),this.linkInPublication(this.navigator.publication.resources,t.href));this.handleLinks=async t=>{$d.default.log("R2 Click Handler");let n=this.checkForLink(t);if(n){let i=window.location.protocol===n.protocol&&window.location.port===n.port&&window.location.hostname===n.hostname,o=this.isReadingOrderInternal(n),a=this.isResourceInternal(n);a||await this.popup.hidePopover();let l=n.href.indexOf("#");if(!o&&!a)window.open(n.href,n.target??"_blank"),t.preventDefault(),t.stopPropagation();else if(t.target.href=n.href,(i||o)&&l!==-1){let u=t.target;u?u.getAttribute("epub:type")==="noteref"?await this.popup.handleFootnote(u,t):a&&!o?await this.popup.showPopover(u,t):this.onInternalLink(t):this.onInternalLink(t)}else(i||o)&&l===-1&&this.onInternalLink(t)}else this.onClickThrough(t)};this.navigator=t,this.popup=new wl(this.navigator)}setupEvents(t){if(t!==null)t.addEventListener("dblclick",async n=>{let i=n.target;n.target&&i.tagName.toLowerCase()==="img"&&await this.popup.showPopover(i,n)},!0),t.addEventListener("click",this.handleLinks.bind(this));else throw"cannot setup events for null"}};H();H();function f_(){return mt(document,"#iframe-wrapper").clientWidth}function tr(){return mt(document,"#iframe-wrapper").clientHeight}var g_=nt(So()),Wd=class{constructor(t){this.layout="reflowable";this.USERSETTINGS="userSetting";this.sideMargin=20;this.height=0;this.attributes={margin:0};this.hasFixedScrollWidth=!1;this.store=t,this.scrollMode?(this.name="readium-scroll-on",this.label="Scrolling"):(this.name="readium-scroll-off",this.label="Paginated")}setMode(t){if(this.scrollMode=t,t){this.name="readium-scroll-on",this.label="Scrolling";let n=this.iframe.contentDocument;if(n){let i=un(n,"head");if(i){let a=Ie(i,"meta[name=viewport]");a&&a.remove()}let o=un(n,"html");o&&o.style.setProperty("--USER__scroll","readium-scroll-on")}this.setSize(),this.setIframeHeight(this.iframe)}else{this.height=tr()-40-this.attributes.margin,this.name="readium-scroll-off",this.label="Paginated",this.checkForFixedScrollWidth();let n=this.iframe.contentDocument;if(n){let i=un(n,"html");i&&i.style.setProperty("--USER__scroll","readium-scroll-off")}this.setSize()}this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate()}start(){if(this.scrollMode){let t=this.iframe.contentDocument;if(t){let n=un(t,"head");if(n){let i=Ie(n,"meta[name=viewport]");i&&i.remove()}}this.setSize(),this.setIframeHeight(this.iframe)}else{this.iframe.height="0",this.iframe.width="0",this.setSize();let t=document.createElement("meta");t.name="viewport",t.content="width=device-width, initial-scale=1, maximum-scale=1",this.checkForFixedScrollWidth()}}stop(){if(this.iframe.height="0",this.iframe.width="0",this.iframe.contentDocument){let n=un(this.iframe.contentDocument,"body"),i=Array.prototype.slice.call(n.querySelectorAll("img"));for(let o of i)o.style.maxWidth=""}}getCurrentPosition(){let t=mt(document,"#iframe-wrapper");if(this.scrollMode)return t.scrollTop/this.scrollingElement.scrollHeight;{let n=this.getColumnWidth(),i=this.getLeftColumnsWidth(),o=this.getRightColumnsWidth(),a=i+n+o;return i/a}}goToProgression(t){let n=mt(document,"#iframe-wrapper");if(this.scrollMode)n.scrollTop=this.scrollingElement.scrollHeight*t;else{let i=this.getColumnWidth(),o=this.getLeftColumnsWidth(),a=this.getRightColumnsWidth(),l=o+i+a,u=t*l,d=Math.round(u/i)*i;d>=l&&(d=d-i),this.setLeftColumnsWidth(d)}}goToCssSelector(t,n){let i=this.iframe.contentDocument;if(i){let o=i.querySelector(t);this.goToElement(o,n)}}goToFragment(t,n){let i=this.iframe.contentDocument;if(i){let o=i.getElementById(t);this.goToElement(o,n)}}snap(t,n){if(t&&!this.scrollMode){let i=t.style.height;t.style.height="0";let o=this.getColumnWidth(),a=this.getLeftColumnsWidth()+t.getBoundingClientRect().left,l=Math.floor(a/o)*o;t.style.height=i,this.setLeftColumnsWidth(l),this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(0)}}goToElement(t,n){if(this.scrollMode)t&&t.scrollIntoView({block:"center"});else if(t){let i=t.style.height;t.style.height="0";let o=t.getBoundingClientRect().left,a=this.getColumnWidth(),l=this.scrollingElement.scrollLeft-a,u=Math.ceil(o/a)*a+l;if(n){let d=this.getLeftColumnsWidth();u=Math.ceil(o/a)*a+d}t.style.height=i,this.setLeftColumnsWidth(u),this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)}}atStart(){return this.scrollMode?mt(document,"#iframe-wrapper").scrollTop===0:this.getLeftColumnsWidth()<=0}atEnd(){if(this.scrollMode){let t=mt(document,"#iframe-wrapper");return Math.ceil(this.scrollingElement.scrollHeight-t.scrollTop)-1<=tr()}else return Math.floor(this.getRightColumnsWidth())<=0||Math.ceil(this.getCurrentPage())===this.getPageCount()}goToPreviousPage(){let t=mt(document,"#iframe-wrapper");if(this.scrollMode){let n=t.scrollTop,i=this.getScreenHeight()-40,o=n-i;o>=0?t.scrollTop=o:t.scrollTop=0}else{let n=this.getLeftColumnsWidth(),i=this.getColumnWidth(),o=n-i;o>=0?this.setLeftColumnsWidth(o):this.setLeftColumnsWidth(0),this.navigator.checkResourcePosition()}this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate()}goToNextPage(){let t=mt(document,"#iframe-wrapper");if(this.scrollMode){let n=t.scrollTop,i=this.getScreenHeight()-40,o=this.scrollingElement.scrollHeight,a=n+i;a<o?t.scrollTop=a:t.scrollTop=o}else{let n=this.getLeftColumnsWidth(),i=this.getColumnWidth(),o=this.scrollWidth,a=n+i;a<o?this.setLeftColumnsWidth(a):this.setLeftColumnsWidth(o),this.navigator.checkResourcePosition()}this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate()}getCurrentPage(){return this.scrollMode?0:this.getCurrentPosition()*this.getPageCount()+1}getPageCount(){if(this.scrollMode)return 0;{let t=this.getColumnWidth();return this.scrollWidth/t}}isPaginated(){if(this.iframe){let t=this.iframe.contentDocument;if(t){let n=un(t,"html");if(n)return!(n.style.getPropertyValue("--USER__scroll")==="readium-scroll-on")}}return!this.scrollMode}isScrollMode(){if(this.iframe){let t=this.iframe.contentDocument;if(t){let n=un(t,"html");if(n)return n.style.getPropertyValue("--USER__scroll")==="readium-scroll-on"}}return this.scrollMode}async getProperty(t){let n=await this.store.get(this.USERSETTINGS);if(n){let i=JSON.parse(n);return i=i.filter(o=>o.name===t),i.length===0?null:i[0]}return null}getScreenHeight(){return mt(document,"#iframe-wrapper").clientHeight}setIframeHeight(t){(0,g_.debounce)(i=>{if(i){let o=i.contentWindow.document.body,a=i.contentWindow.document.documentElement,l=Math.max(o?.scrollHeight,o?.offsetHeight,a?.clientHeight,a?.scrollHeight,a?.offsetHeight);if(l){let u=tr()-this.attributes.margin;i.height=Math.max(u,l)+"px"}}},200)(t)}checkForFixedScrollWidth(){let t=this.iframe.contentDocument;if(t){let n=un(t,"body"),i=n?.scrollWidth;this.hasFixedScrollWidth=n?.scrollWidth===i}}setSize(){if(this.iframe.width=f_()+"px",this.scrollMode){let t=this.iframe.contentWindow?.document?.documentElement;this.iframe.height=t?.offsetHeight+"px"}else{let t=this.iframe.contentDocument;t&&t.documentElement&&(t.documentElement.style.height=this.height+"px"),this.iframe.height=this.height+"px"}}getLeftColumnsWidth(){return Math.ceil(this.scrollingElement.scrollLeft)}getRightColumnsWidth(){let t=this.getColumnWidth(),n=this.scrollWidth-t;if(this.hasFixedScrollWidth){let i=this.getLeftColumnsWidth();n=Math.max(0,n-i)}return n}getColumnWidth(){return this.scrollingElement.clientWidth}setLeftColumnsWidth(t){this.scrollingElement.scrollLeft=t}get scrollingElement(){return this.iframe.contentDocument?.scrollingElement?this.iframe.contentDocument?.scrollingElement:this.iframe.contentDocument?.body?this.iframe.contentDocument?.body:document.createElement("body")}get scrollWidth(){let t=this.scrollingElement?.scrollWidth,n=this.getColumnWidth();return Math.ceil(t/n)*n}};H();var Gd=class{constructor(){this.layout="fixed";this.sideMargin=20;this.height=0;this.attributes={margin:0}}start(){}stop(){}getCurrentPosition(){return 0}getScreenHeight(){return mt(document,"#iframe-wrapper").clientHeight}goToProgression(t){}goToCssSelector(t,n){}goToFragment(t,n){}snap(t,n){}getCurrentPage(){return 0}getPageCount(){return 1}setSize(){}isPaginated(){return!0}isScrollMode(){return!1}atEnd(){return!0}atStart(){return!0}};var _i=nt(Jt()),kt=class{constructor(t,n,i,o,a){this.USERSETTINGS="userSetting";this.fontSize=100;this.fontOverride=!1;this.fontFamily=0;this.appearance=0;this.verticalScroll=!0;this.textAlignment=0;this.columnCount=0;this.wordSpacing=0;this.letterSpacing=0;this.pageMargins=2;this.lineHeight=1;this.settingsChangeCallback=()=>{};this.settingsColumnsChangeCallback=()=>{};this.viewChangeCallback=()=>{};this.store=t,this.view=a==="fixed"?new Gd:new Wd(this.store),this.headerMenu=n,this.api=i,this.injectables=o,this.injectables?.forEach(l=>{l.type==="style"&&(l.fontFamily&&this.addFont(l.fontFamily),l.appearance&&this.addAppearance(l.appearance))})}async isPaginated(){return!await this.getPropertyAndFallback("verticalScroll",me.SCROLL_KEY)}async isScrollMode(){return!await this.isPaginated()}static async create(t){let n=new this(t.store,t.headerMenu,t.api,t.injectables,t.layout);if(await n.initialise(),t.initialUserSettings){n.userProperties||(n.userProperties=n.getUserSettings());let i=t.initialUserSettings;if(i.verticalScroll!==void 0){n.verticalScroll=this.parseScrollSetting(i.verticalScroll);let o=n.userProperties.getByRef(me.SCROLL_REF);o&&(o.value=n.verticalScroll,await n.saveProperty(o)),_i.default.log(n.verticalScroll)}if(i.appearance){n.appearance=kt.appearanceValues.findIndex(a=>a===i.appearance);let o=n.userProperties.getByRef(me.APPEARANCE_REF);o&&(o.value=n.appearance,await n.saveProperty(o)),_i.default.log(n.appearance)}if(i.fontSize){n.fontSize=i.fontSize;let o=n.userProperties.getByRef(me.FONT_SIZE_REF);o&&(o.value=n.fontSize,await n.saveProperty(o)),_i.default.log(n.fontSize)}if(i.fontFamily){n.fontFamily=kt.fontFamilyValues.findIndex(a=>a===i.fontFamily);let o=n.userProperties.getByRef(me.FONT_FAMILY_REF);o&&(o.value=n.fontFamily,await n.saveProperty(o)),_i.default.log(n.fontFamily),n.fontFamily!==0&&(n.fontOverride=!0)}if(i.textAlignment){n.textAlignment=kt.textAlignmentValues.findIndex(a=>a===i.textAlignment);let o=n.userProperties.getByRef(me.TEXT_ALIGNMENT_REF);o&&(o.value=n.textAlignment,await n.saveProperty(o)),_i.default.log(n.textAlignment)}if(i.columnCount){n.columnCount=kt.columnCountValues.findIndex(a=>a===i.columnCount);let o=n.userProperties.getByRef(me.COLUMN_COUNT_REF);o&&(o.value=n.columnCount,await n.saveProperty(o)),_i.default.log(n.columnCount)}if(i.wordSpacing){n.wordSpacing=i.wordSpacing;let o=n.userProperties.getByRef(me.WORD_SPACING_REF);o&&(o.value=n.wordSpacing,await n.saveProperty(o)),_i.default.log(n.wordSpacing)}if(i.letterSpacing){n.letterSpacing=i.letterSpacing;let o=n.userProperties.getByRef(me.LETTER_SPACING_REF);o&&(o.value=n.letterSpacing,await n.saveProperty(o)),_i.default.log(n.letterSpacing)}if(i.pageMargins){n.pageMargins=i.pageMargins;let o=n.userProperties.getByRef(me.PAGE_MARGINS_REF);o&&(o.value=n.pageMargins,await n.saveProperty(o)),_i.default.log(n.pageMargins)}if(i.lineHeight){n.lineHeight=i.lineHeight;let o=n.userProperties.getByRef(me.LINE_HEIGHT_REF);o&&(o.value=n.lineHeight,await n.saveProperty(o)),_i.default.log(n.lineHeight)}n.userProperties=n.getUserSettings(),await n.initialise()}return await n.initializeSelections(),new Promise(i=>i(n))}stop(){_i.default.log("book settings stop")}async initialise(){this.appearance=await this.getPropertyAndFallback("appearance",me.APPEARANCE_KEY),this.verticalScroll=await this.getPropertyAndFallback("verticalScroll",me.SCROLL_KEY),this.fontFamily=await this.getPropertyAndFallback("fontFamily",me.FONT_FAMILY_KEY),this.fontFamily!==0&&(this.fontOverride=!0),this.textAlignment=await this.getPropertyAndFallback("textAlignment",me.TEXT_ALIGNMENT_KEY),this.columnCount=await this.getPropertyAndFallback("columnCount",me.COLUMN_COUNT_KEY),this.fontSize=await this.getPropertyAndFallback("fontSize",me.FONT_SIZE_KEY),this.wordSpacing=await this.getPropertyAndFallback("wordSpacing",me.WORD_SPACING_KEY),this.letterSpacing=await this.getPropertyAndFallback("letterSpacing",me.LETTER_SPACING_KEY),this.pageMargins=await this.getPropertyAndFallback("pageMargins",me.PAGE_MARGINS_KEY),this.lineHeight=await this.getPropertyAndFallback("lineHeight",me.LINE_HEIGHT_KEY),this.userProperties=this.getUserSettings()}async reset(){this.appearance=0,this.verticalScroll=!0,this.fontSize=100,this.fontOverride=!1,this.fontFamily=0,this.textAlignment=0,this.columnCount=0,this.wordSpacing=0,this.letterSpacing=0,this.pageMargins=2,this.lineHeight=1,this.userProperties=this.getUserSettings();let t=this.iframe.contentDocument;if(t){let n=un(t,"html");if(n){let i=document.documentElement,o=mt(i,"body");n.style.removeProperty(me.FONT_SIZE_KEY),n.style.removeProperty(me.WORD_SPACING_KEY),n.style.removeProperty(me.LETTER_SPACING_KEY),n.style.removeProperty(me.COLUMN_COUNT_KEY),n.style.removeProperty(me.TEXT_ALIGNMENT_KEY),n.style.removeProperty(me.LINE_HEIGHT_KEY),n.style.removeProperty(me.PAGE_MARGINS_KEY),n.style.removeProperty(me.APPEARANCE_KEY),Cn(i,"data-viewer-theme","day"),Cn(o,"data-viewer-theme","day"),n.style.removeProperty(me.FONT_FAMILY_KEY),Cn(n,"data-viewer-font","publisher"),n.style.setProperty(me.FONT_OVERRIDE_KEY,"readium-font-off")}}}async initializeSelections(){this.headerMenu&&(this.settingsView=Ie(this.headerMenu,"#container-view-settings"))}async applyProperties(){this.userProperties=this.getUserSettings();let t=this.iframe.contentDocument;if(t){let n=un(t,"html");if(n){let i=document.documentElement,o=mt(i,"body");if(this.view?.navigator.publication.isReflowable&&(await this.getProperty(me.FONT_SIZE_KEY)&&n.style.setProperty(me.FONT_SIZE_KEY,this.userProperties.getByRef(me.FONT_SIZE_REF)?.toString()??null),await this.getProperty(me.WORD_SPACING_KEY)&&n.style.setProperty(me.WORD_SPACING_KEY,this.userProperties.getByRef(me.WORD_SPACING_REF)?.toString()??null),await this.getProperty(me.LETTER_SPACING_KEY)&&n.style.setProperty(me.LETTER_SPACING_KEY,this.userProperties.getByRef(me.LETTER_SPACING_REF)?.toString()??null)),await this.getProperty(me.COLUMN_COUNT_KEY)&&n.style.setProperty(me.COLUMN_COUNT_KEY,this.userProperties.getByRef(me.COLUMN_COUNT_REF)?.toString()??null),this.view?.navigator.publication.isReflowable&&(await this.getProperty(me.TEXT_ALIGNMENT_KEY)&&(this.userProperties.getByRef(me.TEXT_ALIGNMENT_REF)?.toString()==="auto"?n.style.removeProperty(me.TEXT_ALIGNMENT_KEY):n.style.setProperty(me.TEXT_ALIGNMENT_KEY,this.userProperties.getByRef(me.TEXT_ALIGNMENT_REF)?.toString()??null)),await this.getProperty(me.LINE_HEIGHT_KEY)&&n.style.setProperty(me.LINE_HEIGHT_KEY,this.userProperties.getByRef(me.LINE_HEIGHT_REF)?.toString()??null),await this.getProperty(me.PAGE_MARGINS_KEY)&&n.style.setProperty(me.PAGE_MARGINS_KEY,this.userProperties.getByRef(me.PAGE_MARGINS_REF)?.toString()??null)),await this.getProperty(me.APPEARANCE_KEY)?(n.style.setProperty(me.APPEARANCE_KEY,this.userProperties.getByRef(me.APPEARANCE_REF)?.toString()??null),this.userProperties.getByRef(me.APPEARANCE_REF)?.value===0?(Cn(i,"data-viewer-theme","day"),Cn(o,"data-viewer-theme","day")):this.userProperties.getByRef(me.APPEARANCE_REF)?.value===1?(Cn(i,"data-viewer-theme","sepia"),Cn(o,"data-viewer-theme","sepia")):this.userProperties.getByRef(me.APPEARANCE_REF)?.value===2&&(Cn(i,"data-viewer-theme","night"),Cn(o,"data-viewer-theme","night"))):(n.style.setProperty(me.APPEARANCE_KEY,this.userProperties.getByRef(me.APPEARANCE_REF)?.toString()??null),Cn(i,"data-viewer-theme","day"),Cn(o,"data-viewer-theme","day")),this.view?.navigator.publication.isReflowable){if(await this.getProperty(me.FONT_FAMILY_KEY))if(n.style.setProperty(me.FONT_FAMILY_KEY,this.userProperties.getByRef(me.FONT_FAMILY_REF)?.toString()??null),this.userProperties.getByRef(me.FONT_FAMILY_REF)?.value===0)Cn(n,"data-viewer-font","publisher"),n.style.setProperty(me.FONT_OVERRIDE_KEY,"readium-font-off");else if(this.userProperties.getByRef(me.FONT_FAMILY_REF)?.value===1)Cn(n,"data-viewer-font","serif"),n.style.setProperty(me.FONT_OVERRIDE_KEY,"readium-font-on");else if(this.userProperties.getByRef(me.FONT_FAMILY_REF)?.value===2)Cn(n,"data-viewer-font","sans"),n.style.setProperty(me.FONT_OVERRIDE_KEY,"readium-font-on");else{let a=this.userProperties.getByRef(me.FONT_FAMILY_REF);a&&Cn(n,"data-viewer-font",a.toString()),n.style.setProperty(me.FONT_OVERRIDE_KEY,"readium-font-on")}else n.style.setProperty(me.FONT_FAMILY_KEY,this.userProperties.getByRef(me.FONT_FAMILY_REF)?.toString()??null),Cn(n,"data-viewer-font","publisher"),n.style.setProperty(me.FONT_OVERRIDE_KEY,"readium-font-off");await this.getProperty(me.SCROLL_KEY)?this.userProperties.getByRef(me.SCROLL_REF)?.value===!0?n.style.setProperty("--USER__scroll","readium-scroll-on"):n.style.setProperty("--USER__scroll","readium-scroll-off"):n.style.setProperty("--USER__scroll","readium-scroll-on"),n.style.setProperty("--USER__advancedSettings","readium-advanced-on"),this.isScrollMode().then(a=>{this.view?.setMode?.(a)})}}}}setIframe(t){this.iframe=t,this.view&&(this.view.iframe=t),this.settingsView&&kt.renderControls(this.settingsView)}static renderControls(t){Ee(Ie(t,"ul"),"click",n=>{n.stopPropagation()})}onSettingsChange(t){this.settingsChangeCallback=t}onColumnSettingsChange(t){this.settingsColumnsChangeCallback=t}onViewChange(t){this.viewChangeCallback=t}async storeProperty(t){await this.updateUserSettings(),await this.saveProperty(t)}addAppearance(t){kt.appearanceValues.includes(t)||kt.appearanceValues.push(t)}initAddedAppearance(){this.applyProperties()}addFont(t){kt.fontFamilyValues.includes(t)||kt.fontFamilyValues.push(t)}initAddedFont(){this.applyProperties()}async updateUserSettings(){let t={fontFamily:kt.fontFamilyValues[await this.userProperties?.getByRef(me.FONT_FAMILY_REF)?.value],fontSize:this.userProperties?.getByRef(me.FONT_SIZE_REF)?.value,appearance:kt.appearanceValues[await this.userProperties?.getByRef(me.APPEARANCE_REF)?.value],textAlignment:kt.textAlignmentValues[await this.userProperties?.getByRef(me.TEXT_ALIGNMENT_REF)?.value],columnCount:kt.columnCountValues[await this.userProperties?.getByRef(me.COLUMN_COUNT_REF)?.value],wordSpacing:this.userProperties?.getByRef(me.WORD_SPACING_REF)?.value,letterSpacing:this.userProperties?.getByRef(me.LETTER_SPACING_REF)?.value,verticalScroll:this.userProperties?.getByRef(me.SCROLL_REF)?.value};this.api?.updateSettings&&this.api?.updateSettings(t).then(n=>{_i.default.log("api updated user settings",JSON.stringify(t))})}getUserSettings(){let t=new Wr;return t.addSwitchable("readium-font-on","readium-font-off",this.fontOverride,me.FONT_OVERRIDE_REF,me.FONT_OVERRIDE_KEY),t.addEnumerable(this.columnCount,kt.columnCountValues,me.COLUMN_COUNT_REF,me.COLUMN_COUNT_KEY),t.addEnumerable(this.appearance,kt.appearanceValues,me.APPEARANCE_REF,me.APPEARANCE_KEY),t.addIncremental(this.pageMargins,.5,4,.25,"",me.PAGE_MARGINS_REF,me.PAGE_MARGINS_KEY),t.addEnumerable(this.textAlignment,kt.textAlignmentValues,me.TEXT_ALIGNMENT_REF,me.TEXT_ALIGNMENT_KEY),t.addEnumerable(this.fontFamily,kt.fontFamilyValues,me.FONT_FAMILY_REF,me.FONT_FAMILY_KEY),t.addIncremental(this.fontSize,100,300,25,"%",me.FONT_SIZE_REF,me.FONT_SIZE_KEY),t.addIncremental(this.lineHeight,1,2,.25,"em",me.LINE_HEIGHT_REF,me.LINE_HEIGHT_KEY),t.addIncremental(this.wordSpacing,0,1,.25,"rem",me.WORD_SPACING_REF,me.WORD_SPACING_KEY),t.addIncremental(this.letterSpacing,0,.5,.0625,"em",me.LETTER_SPACING_REF,me.LETTER_SPACING_KEY),t.addSwitchable("readium-scroll-on","readium-scroll-off",this.verticalScroll,me.SCROLL_REF,me.SCROLL_KEY),t}async saveProperty(t){let n=await this.store.get(this.USERSETTINGS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.name!==t.name),t.value!==void 0&&i.push(t),await this.store.set(this.USERSETTINGS,JSON.stringify(i))}else{let i=[];i.push(t),await this.store.set(this.USERSETTINGS,JSON.stringify(i))}return new Promise(i=>i(t))}async getProperty(t){let n=await this.store.get(this.USERSETTINGS);if(n){let i=JSON.parse(n);return i=i.filter(o=>o.name===t),i.length===0?null:i[0]}return null}async getPropertyAndFallback(t,n){return(await this.getProperty(n))?.value??this[t]}async resetUserSettings(){await this.store.remove(this.USERSETTINGS),await this.reset(),this.settingsChangeCallback()}get currentSettings(){return{appearance:kt.appearanceValues[this.userProperties?.getByRef(me.APPEARANCE_REF)?.value],fontFamily:kt.fontFamilyValues[this.userProperties?.getByRef(me.FONT_FAMILY_REF)?.value],textAlignment:kt.textAlignmentValues[this.userProperties?.getByRef(me.TEXT_ALIGNMENT_REF)?.value],columnCount:kt.columnCountValues[this.userProperties?.getByRef(me.COLUMN_COUNT_REF)?.value],verticalScroll:this.verticalScroll,fontSize:this.fontSize,wordSpacing:this.wordSpacing,letterSpacing:this.letterSpacing,pageMargins:this.pageMargins,lineHeight:this.lineHeight}}async applyUserSettings(t){if(t.appearance){let n;t.appearance==="day"||t.appearance==="readium-default-on"?n=kt.appearanceValues[0]:t.appearance==="sepia"||t.appearance==="readium-sepia-on"?n=kt.appearanceValues[1]:t.appearance==="night"||t.appearance==="readium-night-on"?n=kt.appearanceValues[2]:n=t.appearance,this.appearance=kt.appearanceValues.findIndex(o=>o===n);let i=this.userProperties?.getByRef(me.APPEARANCE_REF);i&&(i.value=this.appearance,await this.storeProperty(i))}if(t.fontSize){this.fontSize=t.fontSize;let n=this.userProperties?.getByRef(me.FONT_SIZE_REF);n&&(n.value=this.fontSize,await this.storeProperty(n))}if(t.fontFamily){this.fontFamily=kt.fontFamilyValues.findIndex(i=>i===t.fontFamily);let n=this.userProperties?.getByRef(me.FONT_FAMILY_REF);n&&(n.value=this.fontFamily,await this.storeProperty(n))}if(t.letterSpacing){this.letterSpacing=t.letterSpacing;let n=this.userProperties?.getByRef(me.LETTER_SPACING_REF);n&&(n.value=this.letterSpacing,await this.storeProperty(n))}if(t.wordSpacing){this.wordSpacing=t.wordSpacing;let n=this.userProperties?.getByRef(me.WORD_SPACING_REF);n&&(n.value=this.wordSpacing,await this.storeProperty(n))}if(t.columnCount){this.columnCount=kt.columnCountValues.findIndex(i=>i===t.columnCount);let n=this.userProperties?.getByRef(me.COLUMN_COUNT_REF);n&&(n.value=this.columnCount,await this.storeProperty(n)),this.settingsColumnsChangeCallback()}if(t.textAlignment){this.textAlignment=kt.textAlignmentValues.findIndex(i=>i===t.textAlignment);let n=this.userProperties?.getByRef(me.TEXT_ALIGNMENT_REF);n&&(n.value=this.textAlignment,await this.storeProperty(n))}if(t.lineHeight){this.lineHeight=t.lineHeight;let n=this.userProperties?.getByRef(me.LINE_HEIGHT_REF);n&&(n.value=this.lineHeight,await this.storeProperty(n))}if(t.pageMargins){this.pageMargins=t.pageMargins;let n=this.userProperties?.getByRef(me.PAGE_MARGINS_REF);n&&(n.value=this.pageMargins,await this.storeProperty(n))}if(t.verticalScroll!==void 0){let n=this.view?.getCurrentPosition();this.verticalScroll=kt.parseScrollSetting(t.verticalScroll);let i=this.userProperties?.getByRef(me.SCROLL_REF);i&&(i.value=this.verticalScroll,await this.saveProperty(i)),this.view?.setMode?.(this.verticalScroll),n&&this.view?.goToProgression(n),this.viewChangeCallback()}await this.applyProperties(),this.settingsChangeCallback()}static parseScrollSetting(t){switch(t){case!0:case"scroll":case"readium-scroll-on":return!0;case!1:case"paginated":case"readium-scroll-off":return!1;default:return!1}}async scroll(t){let n=this.view?.getCurrentPosition();this.verticalScroll=t;let i=this.userProperties?.getByRef(me.SCROLL_REF);i&&(i.value=this.verticalScroll,await this.saveProperty(i)),await this.applyProperties(),this.view?.setMode?.(this.verticalScroll),n&&this.view?.goToProgression(n),this.viewChangeCallback()}async increase(t){if(t==="fontSize"){(this.userProperties?.getByRef(me.FONT_SIZE_REF)).increment(),this.fontSize=this.userProperties?.getByRef(me.FONT_SIZE_REF)?.value;let n=this.userProperties?.getByRef(me.FONT_SIZE_REF);n&&await this.storeProperty(n)}else if(t==="letterSpacing"){(this.userProperties?.getByRef(me.LETTER_SPACING_REF)).increment(),this.letterSpacing=this.userProperties?.getByRef(me.LETTER_SPACING_REF)?.value;let n=this.userProperties?.getByRef(me.LETTER_SPACING_REF);n&&await this.storeProperty(n)}else if(t==="wordSpacing"){(this.userProperties?.getByRef(me.WORD_SPACING_REF)).increment(),this.wordSpacing=this.userProperties?.getByRef(me.WORD_SPACING_REF)?.value;let n=this.userProperties?.getByRef(me.WORD_SPACING_REF);n&&await this.storeProperty(n)}else if(t==="lineHeight"){(this.userProperties?.getByRef(me.LINE_HEIGHT_REF)).increment(),this.lineHeight=this.userProperties?.getByRef(me.LINE_HEIGHT_REF)?.value;let n=this.userProperties?.getByRef(me.LINE_HEIGHT_REF);n&&await this.storeProperty(n)}await this.applyProperties(),this.settingsChangeCallback()}async decrease(t){if(t==="fontSize"){(this.userProperties?.getByRef(me.FONT_SIZE_REF)).decrement(),this.fontSize=this.userProperties?.getByRef(me.FONT_SIZE_REF)?.value;let n=this.userProperties?.getByRef(me.FONT_SIZE_REF);n&&await this.storeProperty(n)}else if(t==="letterSpacing"){(this.userProperties?.getByRef(me.LETTER_SPACING_REF)).decrement(),this.letterSpacing=this.userProperties?.getByRef(me.LETTER_SPACING_REF)?.value;let n=this.userProperties?.getByRef(me.LETTER_SPACING_REF);n&&await this.storeProperty(n)}else if(t==="wordSpacing"){(this.userProperties?.getByRef(me.WORD_SPACING_REF)).decrement(),this.wordSpacing=this.userProperties?.getByRef(me.WORD_SPACING_REF)?.value;let n=this.userProperties?.getByRef(me.WORD_SPACING_REF);n&&await this.storeProperty(n)}else if(t==="lineHeight"){(this.userProperties?.getByRef(me.LINE_HEIGHT_REF)).decrement(),this.wordSpacing=this.userProperties?.getByRef(me.LINE_HEIGHT_REF)?.value;let n=this.userProperties?.getByRef(me.LINE_HEIGHT_REF);n&&await this.storeProperty(n)}await this.applyProperties(),this.settingsChangeCallback()}},Ao=kt;Ao.appearanceValues=["readium-default-on","readium-sepia-on","readium-night-on"],Ao.fontFamilyValues=["Original","serif","sans-serif"],Ao.textAlignmentValues=["auto","justify","start"],Ao.columnCountValues=["auto","1","2"];H();H();var Si;(function(n){n[n.Bookmark=0]="Bookmark",n[n.Annotation=1]="Annotation"})(Si||(Si={}));H();H();H();H();H();H();var m_={stringify(r){let t=r.nSigBytes,n=r.words,i=[];for(let o=0;o<t;o++){let a=n[o>>>2]>>>24-o%4*8&255;i.push((a>>>4).toString(16)),i.push((a&15).toString(16))}return i.join("")},parse(r){let t=r.length;if(t%2!=0)throw new Error("Hex string count must be even");if(!/^[a-fA-F0-9]+$/.test(r))throw new Error(`Invalid Hex string: ${r}`);let n=[];for(let i=0;i<t;i+=2)n[i>>>3]|=parseInt(r.substr(i,2),16)<<24-i%8*4;return new Ln(n,t/2)}};H();H();var y_=typeof navigator!="undefined"&&navigator.userAgent?navigator.userAgent.toLowerCase():"",ss=(()=>{let r=parseInt((/msie (\d+)/.exec(y_)||[])[1],10);return isNaN(r)?(r=parseInt((/trident\/.*; rv:(\d+)/.exec(y_)||[])[1],10),isNaN(r)?!1:r):r})();function b_(r,t){return ss===!1?!1:t?r==="<"?ss<t:r==="<="?ss<=t:r===">"?ss>t:r===">="?ss>=t:ss===t:!0}function w5(){if(typeof window!="undefined"){let r=window.crypto||window.msCrypto;if(!r){if(b_("<",11))return console.warn("IE <= 10 uses insecure random generator. Please consider to use IE11 or another modern browser"),function(){return Math.floor(Math.random()*512)%256};throw new Error("Crypto module not found")}return function(){return r.getRandomValues(new Uint32Array(1))[0]}}else{if(typeof globalThis!="undefined"&&globalThis.crypto)return function(){return globalThis.crypto.randomBytes(4).readInt32LE()};if(typeof Ha=="function")return function(){return __non_webpack_require__("crypto").randomBytes(4).readInt32LE()}}throw new Error("Unable to find crypto module")}var v_=w5();var Ln=class{constructor(t,n){if(Array.isArray(t)||!t){this._words=Array.isArray(t)?t:[],this._nSignificantBytes=typeof n=="number"?n:this._words.length*4;return}else if(t instanceof Ln){this._words=t.words.slice(),this._nSignificantBytes=t.nSigBytes;return}let i;try{t instanceof ArrayBuffer?i=new Uint8Array(t):(t instanceof Uint8Array||t instanceof Int8Array||t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array||t instanceof Float64Array)&&(i=new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}catch(l){throw new Error("Invalid argument")}if(!i)throw new Error("Invalid argument");let o=i.byteLength,a=[];for(let l=0;l<o;l++)a[l>>>2]|=i[l]<<24-l%4*8;this._words=a,this._nSignificantBytes=o}get nSigBytes(){return this._nSignificantBytes}set nSigBytes(t){this._nSignificantBytes=t}get words(){return this._words}toString(t){return t?t.stringify(this):m_.stringify(this)}toUint8Array(){let t=this._words,n=this._nSignificantBytes,i=new Uint8Array(n);for(let o=0;o<n;o++)i[o]=t[o>>>2]>>>24-o%4*8&255;return i}concat(t){let n=t.words.slice(),i=t.nSigBytes;if(this.clamp(),this._nSignificantBytes%4)for(let o=0;o<i;o++){let a=n[o>>>2]>>>24-o%4*8&255;this._words[this._nSignificantBytes+o>>>2]|=a<<24-(this._nSignificantBytes+o)%4*8}else for(let o=0;o<i;o+=4)this._words[this._nSignificantBytes+o>>>2]=n[o>>>2];return this._nSignificantBytes+=i,this}clamp(){let t=this._nSignificantBytes;this._words[t>>>2]&=4294967295<<32-t%4*8,this._words.length=Math.ceil(t/4)}clone(){return new Ln(this._words.slice(),this._nSignificantBytes)}static random(t){let n=[];for(let i=0;i<t;i+=4)n.push(v_());return new Ln(n,t)}};H();H();var S0={stringify(r){let t=r.nSigBytes,n=r.words,i=[];for(let o=0;o<t;o++){let a=n[o>>>2]>>>24-o%4*8&255;i.push(String.fromCharCode(a))}return i.join("")},parse(r){let t=r.length,n=[];for(let i=0;i<t;i++)n[i>>>2]|=(r.charCodeAt(i)&255)<<24-i%4*8;return new Ln(n,t)}};var w_={stringify(r){try{return decodeURIComponent(escape(S0.stringify(r)))}catch(t){throw new Error("Malformed UTF-8 data")}},parse(r){return S0.parse(unescape(encodeURIComponent(r)))}};var A0=class{constructor(t){this._minBufferSize=0,this._blockSize=0,this._props=t,this._data=t&&typeof t.data!="undefined"?t.data.clone():new Ln,this._nBytes=t&&typeof t.nBytes=="number"?t.nBytes:0}get blockSize(){return this._blockSize}reset(t,n){this._data=typeof t!="undefined"?t.clone():new Ln,this._nBytes=typeof n=="number"?n:0}_append(t){let n=typeof t=="string"?w_.parse(t):t;this._data.concat(n),this._nBytes+=n.nSigBytes}_process(t){let n,i=this._data.words,o=this._data.nSigBytes,a=this._blockSize,l=this._blockSize*4,u=o/l;t?u=Math.ceil(u):u=Math.max((u|0)-this._minBufferSize,0);let d=u*a,h=Math.min(d*4,o);if(d){for(let y=0;y<d;y+=a)this._doProcessBlock(i,y);n=i.splice(0,d),this._data.nSigBytes-=h}return new Ln(n,h)}_doProcessBlock(t,n){throw new Error("Not implemented")}};var x0=class extends A0{constructor(t){super(t);this._blockSize=512/32,this._props=t,t&&typeof t.blockSize=="number"&&(this._blockSize=t.blockSize),this.reset(t?t.data:void 0,t?t.nBytes:void 0)}get blockSize(){return this._blockSize}reset(t,n){super.reset.call(this,t,n),this._doReset()}update(t){return this._append(t),this._process(),this}finalize(t){return t&&this._append(t),this._doFinalize()}_doReset(){throw new Error("Not implemented")}_doFinalize(){throw new Error("Not implemented")}};var C0=[],E_=[];function E5(r){let t=Math.sqrt(r);for(let n=2;n<=t;n++)if(!(r%n))return!1;return!0}function __(r){return(r-(r|0))*4294967296|0}(function(){let t=2,n=0;for(;n<64;)E5(t)&&(n<8&&(C0[n]=__(Math.pow(t,1/2))),E_[n]=__(Math.pow(t,1/3)),n++),t++})();var as=[],Fi=class extends x0{constructor(t){super(t);this._hash=new Ln(C0.slice(0)),this._props=t,t&&typeof t.hash!="undefined"&&(this._hash=t.hash.clone())}_doReset(){this._hash=new Ln(C0.slice(0))}_doProcessBlock(t,n){let i=this._hash.words,o=i[0],a=i[1],l=i[2],u=i[3],d=i[4],h=i[5],y=i[6],b=i[7];for(let w=0;w<64;w++){if(w<16)as[w]=t[n+w]|0;else{let C=as[w-15],O=(C<<25|C>>>7)^(C<<14|C>>>18)^C>>>3,E=as[w-2],T=(E<<15|E>>>17)^(E<<13|E>>>19)^E>>>10;as[w]=O+as[w-7]+T+as[w-16]}let p=d&h^~d&y,m=o&a^o&l^a&l,f=(o<<30|o>>>2)^(o<<19|o>>>13)^(o<<10|o>>>22),g=(d<<26|d>>>6)^(d<<21|d>>>11)^(d<<7|d>>>25),v=b+g+p+E_[w]+as[w],A=f+m;b=y,y=h,h=d,d=u+v|0,u=l,l=a,a=o,o=v+A|0}i[0]=i[0]+o|0,i[1]=i[1]+a|0,i[2]=i[2]+l|0,i[3]=i[3]+u|0,i[4]=i[4]+d|0,i[5]=i[5]+h|0,i[6]=i[6]+y|0,i[7]=i[7]+b|0}_doFinalize(){let t=this._data.words,n=this._nBytes*8,i=this._data.nSigBytes*8;return t[i>>>5]|=128<<24-i%32,t[(i+64>>>9<<4)+14]=Math.floor(n/4294967296),t[(i+64>>>9<<4)+15]=n,this._data.nSigBytes=t.length*4,this._process(),this._hash}clone(){let t={hash:this._hash,blockSize:this._blockSize,data:this._data,nBytes:this._nBytes};return new Fi(t)}static hash(t,n){return new Fi(n).finalize(t)}};var _l=nt(So());H();var it;(function(u){u[u.Annotation=0]="Annotation",u[u.Search=1]="Search",u[u.ReadAloud=2]="ReadAloud",u[u.PageBreak=3]="PageBreak",u[u.Definition=4]="Definition",u[u.LineFocus=5]="LineFocus",u[u.Comment=6]="Comment"})(it||(it={}));H();var In=nt(Jt());function zd(r,t){let n=r.getClientRects();return T0(n,t)}function T0(r,t){let n=1,i=[];for(let d of r)i.push({bottom:d.bottom,height:d.height,left:d.left,right:d.right,top:d.top,width:d.width});let o=A_(i,n,t),a=T5(o,n),l=x_(a),u=2*2;for(let d=l.length-1;d>=0;d--){let h=l[d];if(!(h.width*h.height>u))if(l.length>1)In.default.log("CLIENT RECT: remove small"),l.splice(d,1);else{In.default.log("CLIENT RECT: remove small, but keep otherwise empty!");break}}return C_(l),In.default.log(`CLIENT RECT: reduced ${i.length} --> ${l.length}`),l}function Hi(r,t,n){return Math.abs(r-t)<=n}function _5(r,t){let n=Math.max(r.left,t.left),i=Math.min(r.right,t.right),o=Math.max(r.top,t.top),a=Math.min(r.bottom,t.bottom);return{bottom:a,height:Math.max(0,a-o),left:n,right:i,top:o,width:Math.max(0,i-n)}}function S_(r,t){let n=_5(t,r);if(n.height===0||n.width===0)return[r];let i=[];{let o={bottom:r.bottom,height:0,left:r.left,right:n.left,top:r.top,width:0};o.width=o.right-o.left,o.height=o.bottom-o.top,o.height!==0&&o.width!==0&&i.push(o)}{let o={bottom:n.top,height:0,left:n.left,right:n.right,top:r.top,width:0};o.width=o.right-o.left,o.height=o.bottom-o.top,o.height!==0&&o.width!==0&&i.push(o)}{let o={bottom:r.bottom,height:0,left:n.left,right:n.right,top:n.bottom,width:0};o.width=o.right-o.left,o.height=o.bottom-o.top,o.height!==0&&o.width!==0&&i.push(o)}{let o={bottom:r.bottom,height:0,left:n.right,right:r.right,top:r.top,width:0};o.width=o.right-o.left,o.height=o.bottom-o.top,o.height!==0&&o.width!==0&&i.push(o)}return i}function Vd(r,t,n,i){return(r.left<t||Hi(r.left,t,i))&&(r.right>t||Hi(r.right,t,i))&&(r.top<n||Hi(r.top,n,i))&&(r.bottom>n||Hi(r.bottom,n,i))}function S5(r,t,n){return Vd(r,t.left,t.top,n)&&Vd(r,t.right,t.top,n)&&Vd(r,t.left,t.bottom,n)&&Vd(r,t.right,t.bottom,n)}function A5(r,t){let n=Math.min(r.left,t.left),i=Math.max(r.right,t.right),o=Math.min(r.top,t.top),a=Math.max(r.bottom,t.bottom);return{bottom:a,height:a-o,left:n,right:i,top:o,width:i-n}}function O0(r,t,n){return(r.left<t.right||n>=0&&Hi(r.left,t.right,n))&&(t.left<r.right||n>=0&&Hi(t.left,r.right,n))&&(r.top<t.bottom||n>=0&&Hi(r.top,t.bottom,n))&&(t.top<r.bottom||n>=0&&Hi(t.top,r.bottom,n))}function A_(r,t,n){for(let i=0;i<r.length;i++)for(let o=i+1;o<r.length;o++){let a=r[i],l=r[o];if(a===l){In.default.log("mergeTouchingRects rect1 === rect2 ??!");continue}let u=Hi(a.top,l.top,t)&&Hi(a.bottom,l.bottom,t),d=Hi(a.left,l.left,t)&&Hi(a.right,l.right,t);if((d&&!n||u&&!d)&&O0(a,l,t)){In.default.log(`CLIENT RECT: merging two into one, VERTICAL: ${u} HORIZONTAL: ${d} (${n})`);let w=r.filter(m=>m!==a&&m!==l),p=A5(a,l);return w.push(p),A_(w,t,n)}}return r}function x_(r){for(let t=0;t<r.length;t++)for(let n=t+1;n<r.length;n++){let i=r[t],o=r[n];if(i===o){In.default.log("replaceOverlappingRects rect1 === rect2 ??!");continue}if(O0(i,o,-1)){let a=[],l,u,d=S_(i,o);if(d.length===1)a=d,l=i,u=o;else{let b=S_(o,i);d.length<b.length?(a=d,l=i,u=o):(a=b,l=o,u=i)}let h=[];h.push(u),Array.prototype.push.apply(h,a),C_(h),In.default.log(`CLIENT RECT: overlap, cut one rect into ${a.length}`);let y=r.filter(b=>b!==l);return Array.prototype.push.apply(y,a),x_(y)}}return r}function x5(r,t){return Math.max(0,Math.min(r.right,t.right)-Math.max(r.left,t.left))}function C5(r,t){return Math.max(0,Math.min(r.bottom,t.bottom)-Math.max(r.top,t.top))}function T5(r,t){let n=new Set(r);for(let i of r){if(!(i.width>1&&i.height>1)){In.default.log("CLIENT RECT: remove tiny"),n.delete(i);continue}for(let a of r)if(i!==a&&!!n.has(a)&&S5(a,i,t)){In.default.log("CLIENT RECT: remove contained"),n.delete(i);break}}return Array.from(n)}function C_(r){let t=[];for(let n of r)for(let i of r){if(n===i)continue;let o=t.indexOf(n)>=0,a=t.indexOf(i)>=0;if((!o||!a)&&O0(n,i,-1)){o||t.push(n),a||t.push(i),In.default.log("CLIENT RECT: overlap ---"),In.default.log(`#1 TOP:${n.top} BOTTOM:${n.bottom} LEFT:${n.left} RIGHT:${n.right} WIDTH:${n.width} HEIGHT:${n.height}`),In.default.log(`#2 TOP:${i.top} BOTTOM:${i.bottom} LEFT:${i.left} RIGHT:${i.right} WIDTH:${i.width} HEIGHT:${i.height}`);let l=x5(n,i);In.default.log(`xOverlap: ${l}`);let u=C5(n,i);In.default.log(`yOverlap: ${u}`)}}t.length&&In.default.log(`CLIENT RECT: overlaps ${t.length}`)}H();var Ht=nt(Jt());function Er(r,t){let n=r?r.getSelection():null;if(!n)return;if(n.isCollapsed){Ht.default.log("^^^ SELECTION COLLAPSED.");return}let i=n.toString(),o=i.trim().replace(/\n/g," ").replace(/\s\s+/g," ");if(o.length===0){Ht.default.log("^^^ SELECTION TEXT EMPTY.");return}if(!n.anchorNode||!n.focusNode)return;let a=n.rangeCount===1?n.getRangeAt(0):T_(n.anchorNode,n.anchorOffset,n.focusNode,n.focusOffset);if(!a||a.collapsed){Ht.default.log("$$$$$$$$$$$$$$$$$ CANNOT GET NON-COLLAPSED SELECTION RANGE?!");return}let l=R5(a);l.startContainer!==a.startContainer&&(Ht.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: startContainer"),Ht.default.log(l.startContainer),Ht.default.log(a.startContainer)),l.startOffset!==a.startOffset&&(Ht.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: startOffset"),Ht.default.log(`${l.startOffset} !== ${a.startOffset}`)),l.endContainer!==a.endContainer&&(Ht.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: endContainer"),Ht.default.log(l.endContainer),Ht.default.log(a.endContainer)),l.endOffset!==a.endOffset&&(Ht.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: endOffset"),Ht.default.log(`${l.endOffset} !== ${a.endOffset}`));let u=Xr(l,t);if(!u){Ht.default.log("^^^ SELECTION RANGE INFO FAIL?!");return}return{rangeInfo:u,cleanText:o,rawText:i,range:l}}function T_(r,t,n,i){try{let o=new Range;if(o.setStart(r,t),o.setEnd(n,i),!o.collapsed)return Ht.default.log(">>> createOrderedRange RANGE OK"),o;Ht.default.log(">>> createOrderedRange COLLAPSED ... RANGE REVERSE?");let a=new Range;if(a.setStart(n,i),a.setEnd(r,t),!a.collapsed)return Ht.default.log(">>> createOrderedRange RANGE REVERSE OK."),o;Ht.default.log(">>> createOrderedRange RANGE REVERSE ALSO COLLAPSED?!");return}catch(o){console.warn(o.message);return}}function Xr(r,t){let n=r.startContainer.nodeType===Node.ELEMENT_NODE,i=n?r.startContainer:r.startContainer.parentNode&&r.startContainer.parentNode.nodeType===Node.ELEMENT_NODE?r.startContainer.parentNode:void 0;if(!i)return;let o=n?-1:Array.from(i.childNodes).indexOf(r.startContainer);if(o<-1)return;let a=t(i),l=r.endContainer.nodeType===Node.ELEMENT_NODE,u=l?r.endContainer:r.endContainer.parentNode&&r.endContainer.parentNode.nodeType===Node.ELEMENT_NODE?r.endContainer.parentNode:void 0;if(!u)return;let d=l?-1:Array.from(u.childNodes).indexOf(r.endContainer);if(d<-1)return;let h=t(u),y=O5(r.startContainer,r.endContainer);if(!y){Ht.default.log("^^^ NO RANGE COMMON ANCESTOR?!");return}if(r.commonAncestorContainer){let b=r.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?r.commonAncestorContainer:r.commonAncestorContainer.parentNode;b&&b.nodeType===Node.ELEMENT_NODE&&y!==b&&(Ht.default.log(">>>>>> COMMON ANCESTOR CONTAINER DIFF??!"),Ht.default.log(t(y)),Ht.default.log(t(b)))}if(h&&a)return{endContainerChildTextNodeIndex:d,endContainerElementCssSelector:h,endOffset:r.endOffset,startContainerChildTextNodeIndex:o,startContainerElementCssSelector:a,startOffset:r.startOffset}}function Jd(r,t){let n=r.querySelector(t.startContainerElementCssSelector);if(!n){Ht.default.log("^^^ convertRangeInfo NO START ELEMENT CSS SELECTOR?!");return}let i=n;if(t.startContainerChildTextNodeIndex>=0){if(t.startContainerChildTextNodeIndex>=n.childNodes.length){Ht.default.log("^^^ convertRangeInfo rangeInfo.startContainerChildTextNodeIndex >= startElement.childNodes.length?!");return}if(i=n.childNodes[t.startContainerChildTextNodeIndex],i.nodeType!==Node.TEXT_NODE){Ht.default.log("^^^ convertRangeInfo startContainer.nodeType !== Node.TEXT_NODE?!");return}}let o=r.querySelector(t.endContainerElementCssSelector);if(!o){Ht.default.log("^^^ convertRangeInfo NO END ELEMENT CSS SELECTOR?!");return}let a=o;if(t.endContainerChildTextNodeIndex>=0){if(t.endContainerChildTextNodeIndex>=o.childNodes.length){Ht.default.log("^^^ convertRangeInfo rangeInfo.endContainerChildTextNodeIndex >= endElement.childNodes.length?!");return}if(a=o.childNodes[t.endContainerChildTextNodeIndex],a.nodeType!==Node.TEXT_NODE){Ht.default.log("^^^ convertRangeInfo endContainer.nodeType !== Node.TEXT_NODE?!");return}}return T_(i,t.startOffset,a,t.endOffset)}function O5(r,t){if(r.nodeType===Node.ELEMENT_NODE&&r===t||r.nodeType===Node.ELEMENT_NODE&&r.contains(t))return r;if(t.nodeType===Node.ELEMENT_NODE&&t.contains(r))return t;let n=[],i=r.parentNode;for(;i&&i.nodeType===Node.ELEMENT_NODE;)n.push(i),i=i.parentNode;let o=[];for(i=t.parentNode;i&&i.nodeType===Node.ELEMENT_NODE;)o.push(i),i=i.parentNode;let a=n.find(l=>o.indexOf(l)>=0);return a||(a=o.find(l=>n.indexOf(l)>=0)),a}function R5(r){let t=r.cloneRange(),n=t.startContainer,i=t.startOffset,o=t.endContainer,a=t.endOffset;n.childNodes.length&&i>0&&(n=R_(n.childNodes[i-1]),i=n.length||0),a<o.childNodes.length&&(o=O_(o.childNodes[a]),a=0);let l=O_(n),u=R_(o);function d(h){if(h.childNodes.length)return!1;let y=h.length||0;return h===n&&i===y?!1:!(h===o&&a===0)}for(;l&&!d(l)&&l!==u;)l=P5(l);for(l===n?t.setStart(n,i):l!==null&&(l.nodeType===3?t.setStart(l,0):t.setStartBefore(l));u&&!d(u)&&u!==l;)u=M5(u);return u===o?t.setEnd(o,a):u!==null&&(u.nodeType===3?t.setEnd(u,u.length):t.setEndAfter(u)),t}function P5(r){if(r.firstChild)return r.firstChild;let t=r;for(;!t.nextSibling;)if(t=t.parentNode,!t)return null;return t.nextSibling}function M5(r){if(r.lastChild)return r.lastChild;let t=r;for(;!t.previousSibling;)if(t=t.parentNode,!t)return null;return t.previousSibling}function O_(r){for(;r.firstChild;)r=r.firstChild;return r}function R_(r){for(;r.lastChild;)r=r.lastChild;return r}H();var P0=nt(M_()),xo;(function(i){i[i.All=0]="All",i[i.Two=1]="Two",i[i.One=2]="One"})(xo||(xo={}));var Zr,M0;function wn(r,t,n){if(r.nodeType!==Node.ELEMENT_NODE)throw new Error("Can't generate CSS selector for non-element node type.");if(r.tagName.toLowerCase()==="html")return r.tagName.toLowerCase();let i={className:a=>!0,idName:a=>!0,optimizedMinLength:2,root:t.body,seedMinLength:1,tagName:a=>!0,threshold:1e3};Zr=et(et({},i),n),M0=j5(Zr.root,i);let o=k0(r,0,()=>k0(r,1,()=>k0(r,2)));if(o){let a=N_(D_(o,r));return a.length>0&&(o=a[0]),Kd(o)}else throw new Error("Selector was not found.")}function j5(r,t){return r.nodeType===Node.DOCUMENT_NODE?r:r===t.root?r.ownerDocument:r}function k0(r,t,n){let i=null,o=[],a=r,l=0;for(;a&&a!==Zr.root.parentElement;){let u=B0(F5(a))||B0(...H5(a))||B0(U5(a))||[$5()],d=q5(a);if(t===0)d&&(u=u.concat(u.filter(I0).map(h=>L0(h,d))));else if(t===1)u=u.slice(0,1),d&&(u=u.concat(u.filter(I0).map(h=>L0(h,d))));else if(t===2){let[h]=u=u.slice(0,1);d&&I0(h)&&(u=[L0(h,d)])}for(let h of u)h.level=l;if(o.push(u),o.length>=Zr.seedMinLength&&(i=k_(o,n),i))break;a=a.parentElement,l++}return i||(i=k_(o,n)),i}function k_(r,t){let n=N_(B_(r));if(n.length>Zr.threshold)return t?t():null;for(let i of n)if(I_(i))return i;return null}function Kd(r){let t=r[0],n=t.name;for(let i=1;i<r.length;i++){let o=r[i].level||0;t.level===o-1?n=`${r[i].name} > ${n}`:n=`${r[i].name} ${n}`,t=r[i]}return n}function L_(r){return r.map(t=>t.penalty).reduce((t,n)=>t+n,0)}function I_(r){switch(M0.querySelectorAll(Kd(r)).length){case 0:throw new Error(`Can't select any node with this selector: ${Kd(r)}`);case 1:return!0;default:return!1}}function F5(r){let t=r.getAttribute("id");return t&&Zr.idName(t)?{name:"#"+(0,P0.default)(t,{isIdentifier:!0}),penalty:0}:null}function H5(r){return Array.from(r.classList).filter(Zr.className).map(n=>({name:"."+(0,P0.default)(n,{isIdentifier:!0}),penalty:1}))}function U5(r){let t=r.tagName.toLowerCase();return Zr.tagName(t)?{name:t,penalty:2}:null}function $5(){return{name:"*",penalty:3}}function q5(r){let t=r.parentNode;if(!t)return null;let n=t.firstChild;if(!n)return null;let i=0;for(;n&&(n.nodeType===Node.ELEMENT_NODE&&i++,n!==r);)n=n.nextSibling;return i}function L0(r,t){return{name:r.name+`:nth-child(${t})`,penalty:r.penalty+1}}function I0(r){return r.name!=="html"&&!r.name.startsWith("#")}function B0(...r){let t=r.filter(W5);return t.length>0?t:null}function W5(r){return r!=null}function*B_(r,t=[]){if(r.length>0)for(let n of r[0])yield*B_(r.slice(1,r.length),t.concat(n));else yield t}function N_(r){return Array.from(r).sort((t,n)=>L_(t)-L_(n))}function*D_(r,t){if(r.length>2&&r.length>Zr.optimizedMinLength)for(let n=1;n<r.length-1;n++){let i=[...r];i.splice(n,1),I_(i)&&G5(i,t)&&(yield i,yield*D_(i,t))}}function G5(r,t){return M0.querySelector(Kd(r))===t}H();var Ve;(function(a){a[a.Highlight=0]="Highlight",a[a.Underline=1]="Underline",a[a.Bookmark=2]="Bookmark",a[a.Custom=3]="Custom",a[a.Comment=4]="Comment"})(Ve||(Ve={}));H();var N0=24,z5=24,j_="0 0 24 24",ni=(r,t,n,i="icon")=>`<svg xmlns="http://www.w3.org/2000/svg" width="${N0}" height="${z5}" viewBox="${j_}" preserveAspectRatio="xMidYMid meet" role="img" class="${i}" aria-labelledBy="${r}">
|
|
71
71
|
<title id="${r}">${t}</title>
|
|
72
72
|
${n}
|
|
73
73
|
</svg>`,V5=(r,t,n,i,o="icon")=>`<svg xmlns="http://www.w3.org/2000/svg" width="${N0}" height="${N0}" viewBox="${i}" preserveAspectRatio="xMidYMid meet" role="img" class="${o}" aria-labelledBy="${r}">
|
|
@@ -76,14 +76,14 @@ function print() { __p += __j.call(arguments, '') }
|
|
|
76
76
|
</svg>`,ua=(r,t,n,i="icon",o,a)=>`<svg xmlns="http://www.w3.org/2000/svg" width="${o}" height="${o}" viewBox="${j_}" style="fill:${a}" preserveAspectRatio="xMidYMid meet" role="img" class="${i}" aria-labelledBy="${r}">
|
|
77
77
|
<title id="${r}">${t}</title>
|
|
78
78
|
${n}
|
|
79
|
-
</svg>`,nr={error:ni("error-icon","Warning",'<path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/>'),home:'<path d="M12 5.69l5 4.5V18h-2v-6H9v6H7v-7.81l5-4.5M12 3L2 12h3v8h6v-6h2v6h6v-8h3L12 3z"/>',expand:ni("expand-icon","Enter fullscreen",'<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>',"icon active-icon"),loading:V5("loading-icon","Loading",'<path fill="#BBBBBB" d="M145,241.6c-53.3,0-96.6-43.2-96.6-96.6c0-53.3,43.2-96.6,96.6-96.6c53.3,0,96.6,43.2,96.6,96.6 c0,26.7-10.8,50.9-28.3,68.3l7.6,7.6c19.4-19.4,31.5-46.3,31.5-75.9c0-59.3-48-107.3-107.3-107.3S37.7,85.7,37.7,145 c0,59.3,48,107.3,107.3,107.3V241.6z"/>',"0 0 290 290"),next:ni("next-icon","Next Chapter",'<path d="M6.49 20.13l1.77 1.77 9.9-9.9-9.9-9.9-1.77 1.77L14.62 12l-8.13 8.13z"/>'),previous:ni("previous-icon","Previous Chapter",'<path d="M17.51 3.87L15.73 2.1 5.84 12l9.9 9.9 1.77-1.77L9.38 12l8.13-8.13z"/>'),settings:ni("settings-icon","Settings",'<path d="M19.43 12.98c.04-.32.07-.64.07-.98 0-.34-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46c-.09-.16-.26-.25-.44-.25-.06 0-.12.01-.17.03l-2.49 1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65C14.46 2.18 14.25 2 14 2h-4c-.25 0-.46.18-.49.42l-.38 2.65c-.61.25-1.17.59-1.69.98l-2.49-1c-.06-.02-.12-.03-.18-.03-.17 0-.34.09-.43.25l-2 3.46c-.13.22-.07.49.12.64l2.11 1.65c-.04.32-.07.65-.07.98 0 .33.03.66.07.98l-2.11 1.65c-.19.15-.24.42-.12.64l2 3.46c.09.16.26.25.44.25.06 0 .12-.01.17-.03l2.49-1c.52.4 1.08.73 1.69.98l.38 2.65c.03.24.24.42.49.42h4c.25 0 .46-.18.49-.42l.38-2.65c.61-.25 1.17-.59 1.69-.98l2.49 1c.06.02.12.03.18.03.17 0 .34-.09.43-.25l2-3.46c.12-.22.07-.49-.12-.64l-2.11-1.65zm-1.98-1.71c.04.31.05.52.05.73 0 .21-.02.43-.05.73l-.14 1.13.89.7 1.08.84-.7 1.21-1.27-.51-1.04-.42-.9.68c-.43.32-.84.56-1.25.73l-1.06.43-.16 1.13-.2 1.35h-1.4l-.19-1.35-.16-1.13-1.06-.43c-.43-.18-.83-.41-1.23-.71l-.91-.7-1.06.43-1.27.51-.7-1.21 1.08-.84.89-.7-.14-1.13c-.03-.31-.05-.54-.05-.74s.02-.43.05-.73l.14-1.13-.89-.7-1.08-.84.7-1.21 1.27.51 1.04.42.9-.68c.43-.32.84-.56 1.25-.73l1.06-.43.16-1.13.2-1.35h1.39l.19 1.35.16 1.13 1.06.43c.43.18.83.41 1.23.71l.91.7 1.06-.43 1.27-.51.7 1.21-1.07.85-.89.7.14 1.13zM12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/>',"icon open"),toc:ni("toc-icon","Table of Contents",'<path d="M3 9h14V7H3v2zm0 4h14v-2H3v2zm0 4h14v-2H3v2zm16 0h2v-2h-2v2zm0-10v2h2V7h-2zm0 6h2v-2h-2v2z"/>',"icon open"),bookmarks:ni("toc-icon","Bookmarks",'<path d="M4,6H2v16h16v-2H4V6z"/><path d="M22,2H6v16h16V2z M20,12l-2.5-1.5L15,12V4h5V12z"/>',"icon open"),bookmark:ni("toc-icon","Bookmark",'<path d="M19,3H5v18l7-3l7,3V3z"/>',"icon open"),delete:ni("delete-icon","Delete",'<path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>',"icon open"),close:ni("close-icon","Close",'<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>',"icon open"),text:ni("text-icon","Text",'<path d="M5 4v3h5.5v12h3V7H19V4z"/>',"icon open"),speak:ni("speak-icon","Speak",'<circle cx="9" cy="9" r="4"/><path d="M9 15c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4zm7.76-9.64l-1.68 1.69c.84 1.18.84 2.71 0 3.89l1.68 1.69c2.02-2.02 2.02-5.07 0-7.27zM20.07 2l-1.63 1.63c2.77 3.02 2.77 7.56 0 10.74L20.07 16c3.9-3.89 3.91-9.95 0-14z"/><path d="M0 0h24v24H0z" fill="none"/>',"icon open"),note:ni("note-icon","Note",'<polygon points="17.71 24.66 22.3 20.07 17.71 20.07 17.71 24.66" fill="none"/><path d="M22.42.07H5.58A3.28,3.28,0,0,0,2.29,3.35V24.79a3.28,3.28,0,0,0,3.29,3.28H16.71a1,1,0,0,0,.71-.29l8-8a1,1,0,0,0,.29-.71V3.35A3.28,3.28,0,0,0,22.42.07Zm-8.17,15h-7v-2h7Zm-7-6v-2h13v2ZM16.5,25.86v-6a1,1,0,0,1,1-1h6Z" />',"icon open"),highlight:ni("highlight-icon","Highlight",'<path d="M27.71,7.78,21.12,1.19a1,1,0,0,0-1.38,0L4.32,15A1,1,0,0,0,4,15.7a1,1,0,0,0,.3.73c1.22,1.22,1.2,2.37,0,3.62a1,1,0,0,0,0,1.41l3.2,3.2a1,1,0,0,0,1.41,0c1.28-1.28,2.36-1.29,3.62,0a1,1,0,0,0,1.45,0L27.74,9.16A1,1,0,0,0,27.71,7.78Z" /><path d="M3.09,22.59l-2.8,2.8a1,1,0,0,0-.21,1.09A1,1,0,0,0,1,27.1H4.6a1,1,0,0,0,.71-.29l1-1Z" />',"icon open")};var D0=nt(Yd());var $n=nt(Jt()),qe;(function(d){d.R2_ID_HIGHLIGHTS_CONTAINER="R2_ID_HIGHLIGHTS_CONTAINER",d.R2_ID_BOOKMAKRS_CONTAINER="R2_ID_BOOKMAKRS_CONTAINER",d.R2_ID_READALOUD_CONTAINER="R2_ID_READALOUD_CONTAINER",d.R2_ID_PAGEBREAK_CONTAINER="R2_ID_PAGEBREAK_CONTAINER",d.R2_ID_SEARCH_CONTAINER="R2_ID_SEARCH_CONTAINER",d.R2_ID_DEFINITIONS_CONTAINER="R2_ID_DEFINITIONS_CONTAINER",d.R2_ID_LINEFOCUS_CONTAINER="R2_ID_LINEFOCUS_CONTAINER",d.R2_ID_GUTTER_RIGHT_CONTAINER="R2_ID_GUTTER_RIGHT_CONTAINER"})(qe||(qe={}));var F_="R2_CLASS_HIGHLIGHT_CONTAINER",Sl="R2_CLASS_HIGHLIGHT_BOUNDING_AREA",Tn="R2_CLASS_HIGHLIGHT_AREA",Al="R2_CLASS_HIGHLIGHT_ICON",_r=.5,H_=.75,ls={blue:100,green:50,red:230},tn=[],J5="data-highlighted",K5="data-timestamp",ha={ELEMENT_NODE:1,TEXT_NODE:3},xl;(function(i){i.INLINE="inline",i.TOP="top",i.BOTTOM="bottom"})(xl||(xl={}));var Ai=[qe.R2_ID_HIGHLIGHTS_CONTAINER,qe.R2_ID_PAGEBREAK_CONTAINER,qe.R2_ID_SEARCH_CONTAINER,qe.R2_ID_READALOUD_CONTAINER,qe.R2_ID_BOOKMAKRS_CONTAINER,qe.R2_ID_DEFINITIONS_CONTAINER,qe.R2_ID_LINEFOCUS_CONTAINER,qe.R2_ID_GUTTER_RIGHT_CONTAINER,F_,Tn,Sl],j0=-1,F0=-1,Qe=class{constructor(t,n,i,o,a){this.lastSelectedHighlight=void 0;this.activeAnnotationMarkerId=void 0;this.showTool=(0,_l.debounce)(t=>{this.isAndroid()||this.snapSelectionToWord(t),this.toolboxShow()},navigator.userAgent.toLowerCase().indexOf("firefox")>-1?200:100);this.isSelectionMenuOpen=!1;this.selectionMenuOpened=(0,_l.debounce)(()=>{this.isSelectionMenuOpen||(this.isSelectionMenuOpen=!0,this.api?.selectionMenuOpen&&this.api?.selectionMenuOpen(),this.navigator.emit("toolbox.opened","opened"))},100);this.selectionMenuClosed=(0,_l.debounce)(()=>{this.isSelectionMenuOpen&&(this.isSelectionMenuOpen=!1,this.api?.selectionMenuClose&&this.api?.selectionMenuClose(),this.navigator.emit("toolbox.closed","closed"))},100);this.selection=(0,_l.debounce)((t,n)=>{this.api?.selection&&this.api?.selection(t,n)},100);this.getScrollingElement=t=>t?.scrollingElement?t?.scrollingElement:t?.body?t?.body:document.createElement("body");this.layerSettings=t,this.properties=n,this.properties.menuPosition==null&&(this.properties.menuPosition=xl.INLINE),this.api=a,this.hasEventListener=i,this.options=this.defaults(o,{color:"#fce300",highlightedClass:"highlighted",contextClass:"highlighter-context",onBeforeHighlight:function(){return!0},onAfterHighlight:function(){}})}static async create(t){let n=new this(t.layerSettings,t,!1,{},t.api);return new Promise(i=>i(n))}async initialize(){let t=this.navigator.iframes[0].contentDocument;t&&this.dom(t.body).addClass(this.options.contextClass),this.bindEvents(this.navigator.iframes[0].contentDocument?.body,this,this.hasEventListener),this.initializeToolbox(),j0=-1,F0=-1;let n=this;async function i(){n.lastSelectedHighlight===void 0||(n.lastSelectedHighlight=void 0)}setTimeout(async()=>{let o=this.navigator.iframes[0].contentDocument;o&&await o.body?.addEventListener("click",i)},100)}haveSameColor(t,n){return this.dom(t).color()===this.dom(n).color()}defaults(t,n){t=t||{};for(let i in n)n.hasOwnProperty(i)&&t[i]===void 0&&(t[i]=n[i]);return t}unique(t){return t.filter(function(n,i,o){return o.indexOf(n)===i})}refineRangeBoundaries(t){let n=t.startContainer,i=t.endContainer,o=t.commonAncestorContainer,a=!0;if(t.endOffset===0){for(;!i.previousSibling&&i.parentNode!==o;)i=i.parentNode;i=i.previousSibling}else i.nodeType===ha.TEXT_NODE?t.endOffset<i.nodeValue.length&&i.splitText(t.endOffset):t.endOffset>0&&(i=i.childNodes.item(t.endOffset-1));return n.nodeType===ha.TEXT_NODE?t.startOffset===n.nodeValue.length?a=!1:t.startOffset>0&&(n=n.splitText(t.startOffset),i===n.previousSibling&&(i=n)):t.startOffset<n.childNodes.length?n=n.childNodes.item(t.startOffset):n=n.nextSibling,{startContainer:n,endContainer:i,goDeeper:a}}sortByDepth(t,n){let i=this;t.sort(function(o,a){return i.dom(n?a:o).parents().length-i.dom(n?o:a).parents().length})}groupHighlights(t){let n=[],i={},o=[];return t.forEach(function(a){let l=a.getAttribute(K5);typeof i[l]=="undefined"&&(i[l]=[],n.push(l)),i[l].push(a)}),n.forEach(function(a){let l=i[a];o.push({chunks:l,timestamp:a,toString:function(){return l.map(function(u){return u.textContent}).join("")}})}),o}dom(t){let n=this;return{addClass:function(i){t.classList?t.classList.add(i):t.className+=" "+i},removeClass:function(i){t.classList?t.classList.remove(i):t.className=t.className.replace(new RegExp("(^|\\b)"+i+"(\\b|$)","gi")," ")},prepend:function(i){let o=Array.prototype.slice.call(i),a=o.length;for(;a--;)t.insertBefore(o[a],t.firstChild)},append:function(i){let o=Array.prototype.slice.call(i);for(let a=0,l=o.length;a<l;++a)t.appendChild(o[a])},insertAfter:function(i){return i.parentNode?.insertBefore(t,i.nextSibling)},insertBefore:function(i){return i.parentNode?.insertBefore(t,i)},remove:function(){t.parentNode.removeChild(t),t=null},contains:function(i){return t!==i&&t.contains(i)},wrap:function(i){return t.parentNode&&t.parentNode.insertBefore(i,t),i.appendChild(t),i},unwrap:function(){let i=Array.prototype.slice.call(t.childNodes),o;return i.forEach(function(a){o=a.parentNode,n.dom(a).insertBefore(a.parentNode),n.dom(o).remove()}),i},parents:function(){let i,o=[];for(;i=t.parentNode;)o.push(i),t=i;return o},normalizeTextNodes:function(){if(!!t){if(t.nodeType===ha.TEXT_NODE)for(;t.nextSibling&&t.nextSibling.nodeType===ha.TEXT_NODE;)t.nodeValue+=t.nextSibling.nodeValue,t.parentNode.removeChild(t.nextSibling);else n.dom(t.firstChild).normalizeTextNodes();n.dom(t.nextSibling).normalizeTextNodes()}},color:function(){return t.style.backgroundColor},fromHTML:function(i){let o=document.createElement("div");return o.innerHTML=i,o.childNodes},getRange:function(){let i=n.dom(t)?.getSelection(),o;return i?.rangeCount>0&&(o=i?.getRangeAt(0)),o},removeAllRanges:function(){n.dom(t)?.getSelection()?.removeAllRanges(),n.toolboxHide()},getSelection:function(){return n.dom(t).getWindow()?.getSelection()},getWindow:function(){return n.dom(t).getDocument()?.defaultView},getDocument:function(){return t?.ownerDocument||t}}}disableContext(t){return t.preventDefault(),t.stopPropagation(),!1}bindEvents(t,n,i){let o=t.ownerDocument;t.addEventListener("mouseup",this.toolboxShowDelayed.bind(this)),t.addEventListener("touchend",this.toolboxShowDelayed.bind(this)),o.addEventListener("mouseup",this.toolboxShowDelayed.bind(this)),o.addEventListener("touchend",this.toolboxShowDelayed.bind(this)),i||window.addEventListener("resize",this.toolboxPlacement.bind(this)),o.addEventListener("selectionchange",this.toolboxPlacement.bind(this)),o.addEventListener("selectionchange",this.toolboxShowDelayed.bind(this)),t.addEventListener("mousedown",this.toolboxHide.bind(this)),t.addEventListener("touchstart",this.toolboxHide.bind(this)),this.isAndroid()&&t.addEventListener("contextmenu",this.disableContext),t.addEventListener("mousedown",this.mousedown.bind(this)),t.addEventListener("mouseup",this.mouseup.bind(this)),t.addEventListener("mousemove",this.mousemove.bind(this)),t.addEventListener("touchstart",this.mousedown.bind(this)),t.addEventListener("touchend",this.mouseup.bind(this)),t.addEventListener("touchmove",this.mousemove.bind(this)),this.hasEventListener=!0}async mousedown(t){j0=t.clientX,F0=t.clientY}async mouseup(t){Math.abs(j0-t.clientX)<3&&Math.abs(F0-t.clientY)<3&&await this.processMouseEvent(t)}async mousemove(t){await this.processMouseEvent(t)}unbindEvents(t,n){let i=t.ownerDocument;t.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),t.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),i.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),i.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),window.removeEventListener("resize",this.toolboxPlacement.bind(this)),i.removeEventListener("selectionchange",this.toolboxPlacement.bind(this)),t.removeEventListener("mousedown",this.toolboxHide.bind(this)),t.removeEventListener("touchstart",this.toolboxHide.bind(this)),this.isAndroid()&&t.removeEventListener("contextmenu",this.disableContext),t.removeEventListener("mousedown",this.mousedown.bind(this)),t.removeEventListener("mouseup",this.mouseup.bind(this)),t.removeEventListener("mousemove",this.mousemove.bind(this)),t.removeEventListener("touchstart",this.mousedown.bind(this)),t.removeEventListener("touchend",this.mouseup.bind(this)),t.removeEventListener("touchmove",this.mousemove.bind(this)),this.hasEventListener=!1}destroy(){this.toolboxHide();let t=this.navigator.iframes[0].contentDocument;t&&(this.unbindEvents(t.body,this),this.dom(t.body).removeClass(this.options.contextClass))}initializeToolbox(){let t=document.getElementById("highlight-toolbox-mode-colors"),n=document.getElementById("highlight-toolbox-mode-add"),i=["#fce300","#48e200","#00bae5","#157cf9","#6a39b7","#ea426a","#ff8500"],o=document.getElementById("colorIcon"),a=document.getElementById("actionIcon"),l=document.getElementById("dismissIcon"),u=document.getElementById("collapseIcon"),d=document.getElementById("highlightIcon"),h=this;if(l&&(l.innerHTML=nr.close,l.addEventListener("click",function(){h.toolboxMode("add")})),u&&(u.innerHTML=nr.close,u.addEventListener("click",function(){h.toolboxMode("add")})),o){o.style.position="relative",o.style.zIndex="20",i.forEach(w=>{let p=document.getElementById(w),m=document.getElementById(`c${w}`);p&&t?.contains(p)&&t.removeChild(p),n&&m&&n.contains(m)&&n.removeChild(m)});let y=[],b=[];if(o.addEventListener("click",function(){h.toolboxMode("colors")}),this.navigator.rights.enableAnnotations){let w=10;i.forEach(p=>{w--;let m=o?.cloneNode(!0),f=m.lastChild,g=Qe.hexToRgbChannels(p);f.style.backgroundColor="rgba("+[g.red,g.green,g.blue].join(",")+",.5)",m.id=`c${p}`,m.style.display="unset",m.style.position="relative",m.style.zIndex=`${w}`,m.style.marginLeft="-30px",b.push(m),n?.insertBefore(m,d)})}i.forEach(w=>{let p=o?.cloneNode(!0),m=p.lastChild;m.style.backgroundColor=w,p.id=w,p.style.position="relative",p.style.display="unset",y.push(p),o&&p.addEventListener("click",function(){h.setColor(w);let f=o?.lastChild;f&&(f.style.backgroundColor=w);let g=document.getElementById("highlightIcon"),v=document.getElementById("underlineIcon"),A=document.getElementById("noteIcon");(g?.getElementsByTagName?.("span").length??0)>0&&((g?.getElementsByTagName("span")[0]).style.background=h.getColor()),(v?.getElementsByTagName?.("span").length??0)>0&&((v?.getElementsByTagName("span")[0]).style.borderBottomColor=h.getColor()),(A?.getElementsByTagName?.("span").length??0)>0&&((A?.getElementsByTagName("span")[0]).style.borderBottomColor=h.getColor()),h.toolboxMode("add")}),t?.insertBefore(p,l)})}a&&a.addEventListener("click",function(){h.toolboxMode("action")}),h.toolboxMode("add")}toolboxMode(t){let n=document.getElementById("highlight-toolbox-mode-colors"),i=document.getElementById("highlight-toolbox-mode-add"),o=document.getElementById("highlight-toolbox-mode-edit"),a=document.getElementById("highlight-toolbox-mode-action");switch(t){case"colors":n&&(n.style.display="unset"),i&&(i.style.display="none"),o&&(o.style.display="none"),a&&(a.style.display="none");break;case"edit":n&&(n.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="unset"),a&&(a.style.display="none");break;case"action":n&&(n.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="none"),a&&(a.style.display="unset");break;default:n&&(n.style.display="none"),i&&(i.style.display="unset"),o&&(o.style.display="none"),a&&(a.style.display="none");break}}toolboxHide(){let t=document.getElementById("highlight-toolbox");t&&(t.style.display="none"),this.selectionMenuClosed()}toolboxShowDelayed(t){this.showTool(t.detail===1)}snapSelectionToWord(t=!1){let n=this,i=this.navigator.iframes[0].contentDocument;if(i){let a=n.dom(i.body)?.getSelection();if(n.dom(i.body)&&a&&!a?.isCollapsed){let h=function(g){let v=g.match(new RegExp("[^a-zA-Z0-9]+$"));return!v||!v.index?g:g.slice(0,v.index)},l=a.toString(),u=l.length-l.trimStart().length,d=l.length-l.trimEnd().length,y=l.length;var o=/[-!$%^&*()_+|~=`{}[\]:/;<>?,.@#]/;l=l.replace(o,""),u=y-l.trimStart().length,l=h(l),d=y-l.trimEnd().length;let b=document.createRange();t?(b.setStart(a.anchorNode,a.anchorOffset+u),b.setEnd(a.focusNode,a.focusOffset-d)):(b.setStart(a.anchorNode,a.anchorOffset),b.setEnd(a.focusNode,a.focusOffset));let w=b.collapsed;b.detach();let p=a.focusNode,m;t?(m=a.focusOffset-d,a.collapse(a.anchorNode,a.anchorOffset+u)):(m=a.focusOffset,a.collapse(a.anchorNode,a.anchorOffset));let f=["forward","backward"];w&&(f=["backward","forward"]),t?(a.modify("move",f[0],"character"),a.modify("move",f[1],"word"),a.extend(p,m),a.modify("extend",f[1],"character"),a.modify("extend",f[0],"word")):a.extend(p,m),this.selection(a.toString(),a)}return a}}toolboxShow(){if(this.activeAnnotationMarkerId===void 0){let t=this,n=document.getElementById("highlight-toolbox-mode-add"),i=this.dom(this.navigator.iframes[0].contentDocument?.body).getRange();if((!i||i.collapsed)&&n){getComputedStyle(n).display!=="none"&&t.toolboxHide();return}this.isIOS()&&setTimeout(function(){let o=t.navigator.iframes[0].contentDocument;if(o){let a=t.dom(o.body).getSelection();a.removeAllRanges(),setTimeout(function(){a.addRange(i);function l(h){let y={className:w=>Ai.indexOf(w)<0,idName:w=>Ai.indexOf(w)<0},b=t.navigator.iframes[0].contentDocument;if(b)return wn(h,b,y)}let u=t.navigator.iframes[0].contentWindow,d=Er(u,l);t.navigator.annotationModule?.annotator?.saveTemporarySelectionInfo(d)},5)}},100),this.toolboxPlacement(),this.toolboxHandler()}}toolboxPlacement(){let t=this.dom(this.navigator.iframes[0].contentDocument?.body).getRange();if(!t||t.collapsed)return;let n=t.getBoundingClientRect(),i=document.getElementById("highlight-toolbox");i&&(this.properties?.menuPosition===xl.TOP?(i.style.left="0px",i.style.transform="revert",i.style.width="100%",i.style.textAlign="center"):this.properties?.menuPosition===xl.BOTTOM?(i.style.bottom="0px",i.style.left="0px",i.style.transform="revert",i.style.width="100%",i.style.textAlign="center",i.style.position="absolute"):(this.navigator.view?.isPaginated()?i.style.top=n.top+(this.navigator.attributes?.navHeight??0)+"px":i.style.top=n.top+"px",i.style.left=(n.right-n.left)/2+n.left+"px"))}toolboxHandler(){let t=document.getElementById("highlight-toolbox");if(t&&getComputedStyle(t).display==="none"){t.style.display="block",this.navigator.view?.isPaginated()?t.style.position="absolute":t.style.position="relative",this.selectionMenuOpened();let i=this;i.toolboxMode("add");let o=document.getElementById("highlightIcon"),a=document.getElementById("collapseIcon"),l=document.getElementById("underlineIcon"),u=document.getElementById("noteIcon"),d=document.getElementById("colorIcon"),h=document.getElementById("speakIcon");if(this.navigator.rights.enableAnnotations){if(o&&(o.style.display="unset",d&&o.getElementsByTagName("span").length>0&&(o.getElementsByTagName("span")[0].style.background=this.getColor())),l&&(l.style.display="unset",d&&l.getElementsByTagName("span").length>0&&(l.getElementsByTagName("span")[0].style.borderBottomColor=this.getColor())),u&&(u.style.display="unset",d&&u.getElementsByTagName("span").length>0&&(u.getElementsByTagName("span")[0].style.borderBottomColor=this.getColor())),d){d.style.display="unset";let y=d.lastChild;y.style.backgroundColor=this.getColor()}if(o){let y=function(){i.doHighlight(!1,Ve.Highlight),i.toolboxHide(),o?.removeEventListener("click",y)},b=o.cloneNode(!0);o?.parentNode?.replaceChild(b,o),o=document.getElementById("highlightIcon"),o?.addEventListener("click",y)}if(l){let y=function(){i.doHighlight(!1,Ve.Underline),i.toolboxHide(),l?.removeEventListener("click",y)},b=l.cloneNode(!0);l?.parentNode?.replaceChild(b,l),l=document.getElementById("underlineIcon"),l?.addEventListener("click",y)}if(u){let y=function(){i.doHighlight(!1,Ve.Comment),i.toolboxHide(),u?.removeEventListener("click",y)},b=u.cloneNode(!0);u?.parentNode?.replaceChild(b,u),u=document.getElementById("noteIcon"),u?.addEventListener("click",y)}}else o&&o.style.setProperty("display","none"),l&&l.style.setProperty("display","none"),u&&u.style.setProperty("display","none"),d&&d.style.setProperty("display","none"),a&&a.style.setProperty("display","none");if(this.navigator.rights.enableTTS){if(h){let y=function(){h?.removeEventListener("click",y),i.speak()},b=h.cloneNode(!0);h?.parentNode?.replaceChild(b,h),h=document.getElementById("speakIcon"),h?.addEventListener("click",y)}}else h&&h.style.setProperty("display","none");(this.properties?.selectionMenuItems??[])&&(this.properties?.selectionMenuItems??[]).forEach(y=>{y.icon&&(y.icon.id=y.id);let b=document.getElementById(y.id),w=this;function p(){b?.removeEventListener("click",p);function m(g){let v={className:C=>Ai.indexOf(C)<0,idName:C=>Ai.indexOf(C)<0},A=w.navigator.iframes[0].contentDocument;if(A)return wn(g,A,v)}let f=w.navigator.iframes[0].contentWindow;if(f){let g=Er(f,m);if(g===void 0){let v=w.navigator.iframes[0].contentDocument;g=w.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(v)}if(g!==void 0)if(y.callback)y.callback(g.cleanText,g.range?.startContainer.parentElement);else{let v=y.highlight?.style,A=y.marker?y.marker:Ve.Custom;if(A===Ve.Custom&&w.navigator.rights.enableAnnotations||A===Ve.Bookmark&&w.navigator.rights.enableBookmarks){let C=w.navigator.iframes[0].contentDocument;if(C){let O=w.createHighlight(w.dom(C.body).getWindow(),g,y.highlight?.color,!0,A,y.icon,y.popup,v);w.options.onAfterHighlight(O,A),w.navigator.rights.enableAnnotations?w.navigator.annotationModule?.saveAnnotation(O[0]).then(E=>{y?.note&&E.highlight&&w.navigator.annotationModule?.api?.addCommentToAnnotation(E).then(T=>{w.navigator.annotationModule?.updateAnnotation(T).then(async()=>{$n.default.log("update highlight "+T.id)})})}):w.navigator.rights.enableBookmarks&&w.navigator.bookmarkModule?.saveAnnotation(O[0])}}}}w.callbackComplete()}if(b){let m=b.cloneNode(!0);b?.parentNode?.replaceChild(m,b),b=document.getElementById(y.id),b?.addEventListener("click",p)}})}}doHighlight(t,n){let i=this;function o(l){let u={className:h=>Ai.indexOf(h)<0,idName:h=>Ai.indexOf(h)<0},d=i.navigator.iframes[0].contentDocument;if(d)return wn(l,d,u)}let a=i.navigator.iframes[0].contentWindow;if(a){let l=Er(a,o);if(l===void 0){let u=i.navigator.iframes[0].contentDocument;l=this.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(u)}if(l){if(this.options.onBeforeHighlight(l)===!0){let u;u=this.getColor(),Qe.isHexColor(u)&&(u=Qe.hexToRgbChannels(u));let d=i.navigator.iframes[0].contentDocument;if(d){let h=this.createHighlight(i.dom(d.body).getWindow(),l,u,!0,n??Ve.Highlight);this.options.onAfterHighlight(h,n),this.navigator.rights.enableAnnotations&&n!==Ve.Bookmark?this.navigator.annotationModule?.saveAnnotation(h[0]):this.navigator.rights.enableBookmarks&&n===Ve.Bookmark&&this.navigator.bookmarkModule?.saveAnnotation(h[0])}}t||this.dom(this.navigator.iframes[0].contentDocument?.body).removeAllRanges()}else t||this.dom(this.navigator.iframes[0].contentDocument?.body).removeAllRanges()}}speak(){if(this.navigator.rights.enableTTS){let n=function(l){let u={className:h=>Ai.indexOf(h)<0,idName:h=>Ai.indexOf(h)<0},d=t.navigator.iframes[0].contentDocument;if(d)return wn(l,d,u)},t=this,i=t.navigator.iframes[0].contentWindow;if(i){let l=Er(i,n);if(l===void 0){let u=t.navigator.iframes[0].contentDocument;l=t.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(u)}l!==void 0&&this.navigator.ttsModule.speak(l,!0,()=>{})}let o=t.navigator.iframes[0].contentDocument;o&&t.dom(o.body).getSelection().removeAllRanges();let a=document.getElementById("highlight-toolbox");a&&(a.style.display="none"),this.selectionMenuClosed()}}stopReadAloud(){this.navigator.rights.enableTTS&&this.doneSpeaking()}callbackComplete(){this.toolboxHide();let t=this.navigator.iframes[0].contentDocument;t&&this.dom(t.body).removeAllRanges()}isOutsideViewport(t){let n=mt(document,"#iframe-wrapper"),i=n.scrollLeft,o=i+n.clientWidth,a=t.left+t.width,l=t.top+t.height,u=n.scrollTop,d=u+n.clientHeight,h=l<u,y=t.top>d,b=a<i,w=t.left>o;return h||y||b||w}isInsideViewport(t){let n=mt(document,"#iframe-wrapper"),i=n.scrollTop,o=i+n.clientHeight,a=t.top+20>=i,l=t.top<=o,u=n.scrollLeft,d=u+n.clientWidth,h=t.left+t.width,y=t.left>u,b=h<d;return a&&l&&y&&b}get visibleTextRects(){let t=this.navigator.iframes[0].contentDocument;if(t){let i=function(u,d=[]){let h=u.firstChild;for(;h;)h.nodeType===1&&i(h,d),h.nodeType===3&&h.textContent?.trim()&&d.push(h),h=h.nextSibling;return d},o=function(u){return i(u).map(h=>{let{top:y,height:b,left:w,width:p}=a(h);return{top:y,height:b,width:p,left:w,node:h,textContent:h.textContent??""}})},a=function(u){try{let d=document.createRange();d.selectNode(u);let h=d.getBoundingClientRect();return d.detach(),h}catch(d){$n.default.log("measureTextNode "+d),$n.default.log("measureTextNode "+u),$n.default.log(`${u.textContent}`)}},n=Gr(t,"body");return o(n).filter(u=>this.isInsideViewport(u))}return[]}doneSpeaking(t=!1){if(this.navigator.rights.enableTTS){this.toolboxHide();let n=this.navigator.iframes[0].contentDocument;n&&this.dom(n.body).removeAllRanges(),this.navigator.ttsModule.cancel(),t&&this.navigator.reload()}}normalizeHighlights(t){var n;return n=t.filter(function(i){return i.parentElement?i:null}),n=this.unique(n),n.sort(function(i,o){return i.offsetTop-o.offsetTop||i.offsetLeft-o.offsetLeft}),n}flattenNestedHighlights(t){let n,i=this;i.sortByDepth(t,!0);function o(){let a=!1;return t.forEach(function(l,u){let d=l.parentElement,h=d.previousSibling,y=d.nextSibling;i.isHighlight(d)&&(i.haveSameColor(d,l)?(d.replaceChild(l.firstChild,l),t[u]=d,a=!0):(l.nextSibling||(i.dom(l).insertBefore(y||d),a=!0),l.previousSibling||(i.dom(l).insertAfter(h||d),a=!0),d.hasChildNodes()||i.dom(d).remove()))}),a}do n=o();while(n)}mergeSiblingHighlights(t){let n=this;function i(o,a){return a&&a.nodeType===ha.ELEMENT_NODE&&n.haveSameColor(o,a)&&n.isHighlight(a)}t.forEach(function(o){let a=o.previousSibling,l=o.nextSibling;i(o,a)&&(n.dom(o).prepend(a.childNodes),n.dom(a).remove()),i(o,l)&&(n.dom(o).append(l.childNodes),n.dom(l).remove()),n.dom(o).normalizeTextNodes()})}setColor(t){this.options.color=t}getColor(){return this.options.color}isHighlight(t){return t&&t.nodeType===ha.ELEMENT_NODE&&t.hasAttribute(J5)}createWrapper(){let t=document.createElement("mark");return t.style.background="linear-gradient("+Qe.hexToRgbA(this.options.color)+", "+Qe.hexToRgbA(this.options.color)+")",t.className=this.options.highlightedClass,t}static isHexColor(t){return/^#([A-Fa-f0-9]{3}){1,2}$/.test(t)}static hexToRgbString(t){let n;return n=t.substring(1).split(""),n.length===3&&(n=[n[0],n[0],n[1],n[1],n[2],n[2]]),n="0x"+n.join(""),n}static hexToRgbChannels(t){let n;if(this.isHexColor(t))return n=this.hexToRgbString(t),{red:n>>16&255,green:n>>8&255,blue:n&255};throw new Error("Bad Hex")}static hexToRgbA(t){let n;if(this.isHexColor(t))return n=this.hexToRgbChannels(t),"rgba("+[n.red,n.green,n.blue].join(",")+",.5)";if(typeof t=="object"){let i=t;return"rgba("+[i.red,i.green,i.blue].join(",")+",.5)"}throw new Error("Bad Hex")}static hexToRgbAWithOpacity(t,n){let i;if(this.isHexColor(t))return i=this.hexToRgbChannels(t),"rgba("+[i.red,i.green,i.blue].join(",")+","+n+")";if(typeof t=="object"){let o=t;return"rgba("+[o.red,o.green,o.blue].join(",")+","+n+")"}throw new Error("Bad Hex")}resetHighlightBoundingStyle(t){t.style.outline="none",t.style.setProperty("background-color","transparent","important")}resetHighlightAreaStyle(t,n){let i=this.navigator.iframes[0].contentWindow?.document,o=t.parentNode&&t.parentNode.nodeType===Node.ELEMENT_NODE&&t.parentNode.getAttribute?t.parentNode.getAttribute("id"):void 0;if(o){let a=tn.find(l=>l.id===o);if(a){if(a.marker===Ve.Custom||a.marker===Ve.Bookmark)if(a.style?.hover){if(a.style?.hover)for(let d=0;d<a.style?.hover?.length;d++){let h=a.style?.hover[d];t.style.removeProperty(h.property)}let u="";if(a.style?.default)for(let d=0;d<a.style?.default?.length;d++){let h=a.style?.default[d];t.style.removeProperty(h.property),u+=`${h.property}: ${h.value} !${h.priority};`}t.setAttribute("style",`${t.getAttribute("style")}; ${u}`)}else if(a.style?.hoverClass){a.style?.hoverClass&&t.classList.remove(a.style?.hoverClass);let u="";a.style?.defaultClass&&t.classList.add(a.style?.defaultClass),t.setAttribute("style",`${t.getAttribute("style")}; ${u}`)}else if(Qe.isHexColor(a.color)){let u=Qe.hexToRgbChannels(a.color);t.style.setProperty("background-color",`rgba(${u.red}, ${u.green}, ${u.blue}, ${0})`,"important")}else t.classList.remove("hover");else if(a.marker===Ve.Underline||a.marker===Ve.Comment)if(typeof a.color=="object"){let u=a.color;t.style.setProperty("background-color",`rgba(${u.red}, ${u.green}, ${u.blue}, ${0})`,"important"),t.style.setProperty("border-bottom",`2px solid rgba(${u.red}, ${u.green}, ${u.blue}, ${1})`,"important")}else if(Qe.isHexColor(a.color)){let u=Qe.hexToRgbChannels(a.color);t.style.setProperty("background-color",`rgba(${u.red}, ${u.green}, ${u.blue}, ${0})`,"important"),t.style.setProperty("border-bottom",`2px solid rgba(${u.red}, ${u.green}, ${u.blue}, ${1})`,"important")}else t.classList.remove("hover");else if(typeof a.color=="object"){let u=a.color;t.style.setProperty("background-color",`rgba(${u.red}, ${u.green}, ${u.blue}, ${_r})`,"important")}else if(Qe.isHexColor(a.color)){let u=Qe.hexToRgbChannels(a.color);t.style.setProperty("background-color",`rgba(${u.red}, ${u.green}, ${u.blue}, ${_r})`,"important")}else t.classList.remove("hover");let l;if(i){let u=i.getElementById(n);u&&(l=u.querySelector(`#${a.id}`))}if(l){let u=l.getElementsByClassName(Al);if(u.length>0){let d=u.item(0).getElementsByClassName("icon-tooltip");d.length>0&&d.item(0).style.removeProperty("display")}}}}}setHighlightAreaStyle(t,n,i){for(let o of n){if(i.marker===Ve.Custom||i.marker===Ve.Bookmark)if(i.style?.hover){if(i.style?.default)for(let l=0;l<i.style?.default?.length;l++){let u=i.style?.default[l];o.style.removeProperty(u.property)}let a="";for(let l=0;l<i.style?.hover?.length;l++){let u=i.style?.hover[l];o.style.removeProperty(u.property),a+=`${u.property}: ${u.value} !${u.priority};`}o.setAttribute("style",`${o.getAttribute("style")}; ${a}`)}else if(i.style?.hoverClass){i.style?.defaultClass&&o.classList.remove(i.style?.defaultClass);let a="";o.classList.add(i.style?.hoverClass),o.setAttribute("style",`${o.getAttribute("style")}; ${a}`)}else if(Qe.isHexColor(i.color)){let a=Qe.hexToRgbChannels(i.color);o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${.1})`,"important")}else o.classList.add("hover");else if(i.marker===Ve.Underline||i.marker===Ve.Comment)if(typeof i.color=="object"){let a=i.color;o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${.1})`,"important"),o.style.setProperty("border-bottom",`2px solid rgba(${a.red}, ${a.green}, ${a.blue}, ${1})`,"important")}else if(Qe.isHexColor(i.color)){let a=Qe.hexToRgbChannels(i.color);o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${.1})`,"important"),o.style.setProperty("border-bottom",`2px solid rgba(${a.red}, ${a.green}, ${a.blue}, ${1})`,"important")}else o.classList.add("hover");else if(typeof i.color=="object"){let a=i.color;o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${H_})`,"important")}else if(Qe.isHexColor(i.color)){let a=Qe.hexToRgbChannels(i.color);o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${H_})`,"important")}else o.classList.add("hover");if(i.type!==it.Definition){let l=t.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER).querySelector(`#${i.id}`).getElementsByClassName(Al);if(l.length>0){let u=l.item(0).getElementsByClassName("icon-tooltip");u.length>0&&u.item(0).style.setProperty("display","block")}}}}setAndResetSearchHighlight(t,n){let i=this.navigator.iframes[0].contentWindow?.document,o=Array.from(i.getElementById(qe.R2_ID_SEARCH_CONTAINER).querySelectorAll(`.${Tn}`));for(let a of o){let l=a,u=l.parentNode&&l.parentNode.nodeType===Node.ELEMENT_NODE&&l.parentNode.getAttribute?l.parentNode.getAttribute("id"):void 0;if(n.forEach(d=>{if(u===d.id&&d){if(typeof d.color=="object"){let b=d.color;l.style.setProperty("background-color",`rgba(${b.red}, ${b.green}, ${b.blue}, ${_r})`,"important")}else if(Qe.isHexColor(d.color)){let b=Qe.hexToRgbChannels(d.color);l.style.setProperty("background-color",`rgba(${b.red}, ${b.green}, ${b.blue}, ${_r})`,"important")}else l.classList.remove("hover");let y=i.getElementById(qe.R2_ID_SEARCH_CONTAINER).querySelector(`#${d.id}`).getElementsByClassName(Al);if(y.length>0){let b=y.item(0).getElementsByClassName("icon-tooltip");b.length>0&&b.item(0).style.removeProperty("display")}}}),u===t.id&&t){if(typeof t.color=="object"){let y=t.color;l.style.setProperty("background-color",`rgba(${y.red}, ${y.green}, ${y.blue}, ${_r})`,"important")}else if(Qe.isHexColor(t.color)){let y=Qe.hexToRgbChannels(t.color);l.style.setProperty("background-color",`rgba(${y.red}, ${y.green}, ${y.blue}, ${_r})`,"important")}else l.classList.remove("hover");let h=i.getElementById(qe.R2_ID_SEARCH_CONTAINER).querySelector(`#${t.id}`).getElementsByClassName(Al);if(h.length>0){let y=h.item(0).getElementsByClassName("icon-tooltip");y.length>0&&y.item(0).style.removeProperty("display")}}}}isIOS(){return navigator.userAgent.match(/iPhone|iPad|iPod/i)!=null||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}isAndroid(){return navigator.userAgent.match(/Android/i)!=null}async processMouseEvent(t){let n=this.navigator.iframes[0].contentWindow?.document,i=t.clientX,o=t.clientY;if(!n||!n.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER)&&!n.getElementById(qe.R2_ID_SEARCH_CONTAINER)&&!n.getElementById(qe.R2_ID_PAGEBREAK_CONTAINER)&&!n.getElementById(qe.R2_ID_READALOUD_CONTAINER)&&!n.getElementById(qe.R2_ID_DEFINITIONS_CONTAINER))return;let a=this.navigator.view?.isPaginated(),l=n.body.getBoundingClientRect(),u=this.getScrollingElement(n),d=a?-u.scrollLeft:l.left,h=a?-u.scrollTop:l.top,y,b;for(let w=tn.length-1;w>=0;w--){let p=tn[w],m=n.getElementById(`${p.id}`);if(!m){let v=n.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER);v&&(m=v.querySelector(`#${p.id}`))}if(!m)continue;let f=!1,g=m.querySelectorAll(`.${Tn}`);for(let v of g){let A=v,C=A.rect.left+d,O=A.rect.top+h;if(i>=C&&i<C+A.rect.width&&o>=O&&o<O+A.rect.height){f=!0;break}}if(f){y=p,b=m;break}}if(!y||!b){for(let w in qe){let p=n.getElementById(w);if(p){let m=p.querySelectorAll(`.${Sl}`);for(let g of m)this.resetHighlightBoundingStyle(g);let f=Array.from(p.querySelectorAll(`.${Tn}`));for(let g of f)this.resetHighlightAreaStyle(g,w)}}return}if(b.getAttribute("data-click")){if((t.type==="mousemove"||t.type==="touchmove")&&b.parentElement?.style.display!=="none"){let w=Array.from(b.querySelectorAll(`.${Tn}`));for(let m in qe){let f=n.getElementById(m);if(f){let g=f.querySelectorAll(`.${Tn}`);for(let v of g)w.indexOf(v)<0&&this.resetHighlightAreaStyle(v,m)}}this.setHighlightAreaStyle(n,w,y);let p=b.querySelector(`.${Sl}`);for(let m in qe){let f=n.getElementById(m);if(f){let g=f.querySelectorAll(`.${Sl}`);for(let v of g)(!p||v!==p)&&this.resetHighlightBoundingStyle(v)}}}else if((t.type==="mouseup"||t.type==="click"||t.type==="touchup")&&b.parentElement?.style.display!=="none"){let w={highlight:y};$n.default.log(JSON.stringify(w));let p=this,m;if(p.navigator.rights.enableAnnotations?m=await this.navigator.annotationModule?.getAnnotation(w.highlight):p.navigator.rights.enableBookmarks&&(m=await this.navigator.bookmarkModule?.getAnnotation(w.highlight)),w.highlight.type===it.Annotation&&this.navigator.annotationModule?.api?.selectedAnnotation(m).then(async()=>{}),m?.id){$n.default.log("selected highlight "+m.id),p.lastSelectedHighlight=m.id;let f=document.getElementById("highlight-toolbox");if(f)if(f.style.top=t.clientY+(this.navigator.attributes?.navHeight??0)+"px",f.style.left=t.clientX+"px",getComputedStyle(f).display==="none"){let A=function(){p.navigator.annotationModule?.api?.addCommentToAnnotation(m).then(M=>{p.navigator.annotationModule?.updateAnnotation(M).then(async()=>{$n.default.log("update highlight "+M.id),f&&(f.style.display="none"),p.selectionMenuClosed()}),f&&(f.style.display="none"),p.selectionMenuClosed(),C?.removeEventListener("click",A,!1)})},E=function(){p.navigator.rights.enableAnnotations?p.navigator.annotationModule?.deleteSelectedHighlight(m).then(async()=>{$n.default.log("delete highlight "+m.id),f&&(f.style.display="none"),p.selectionMenuClosed()}):p.navigator.rights.enableBookmarks&&p.navigator.bookmarkModule?.deleteSelectedHighlight(m).then(async()=>{$n.default.log("delete highlight "+m.id),f&&(f.style.display="none"),p.selectionMenuClosed()})};f.style.display="block",this.toolboxMode("edit");let g=document.getElementById("colorIcon"),v=document.getElementById("highlightIcon");g&&(g.style.display="none"),v&&(v.style.display="none");let C=document.getElementById("commentIcon"),O=document.getElementById("cloneCommentIcon");if(O){let M=O.parentElement;M&&M.removeChild(O)}if(C){C.style.display="none";let M=C.cloneNode(!0),j=C.parentElement;M.style.display="unset",M.id="cloneCommentIcon",M.addEventListener("click",A,!1),j&&j.append(M)}let T=document.getElementById("deleteIcon"),I=document.getElementById("cloneDeleteIcon");if(I){let M=I.parentElement;M&&M.removeChild(I)}if(T){T.style.display="none";let M=T.cloneNode(!0),j=T.parentElement;M.style.display="unset",M.id="cloneDeleteIcon",M.addEventListener("click",E,!1),j&&j.append(M)}}else f.style.display="none",this.selectionMenuClosed(),f.offsetWidth,f.style.display="block"}else{b.dataset.definition&&new wl(this.navigator).showPopup(b.dataset.definition,t);let f=this.navigator.definitionsModule?.properties?.definitions?.filter(g=>g.order===Number(b?.dataset.order))[0];$n.default.log(f),this.navigator.definitionsModule?.api?.click&&(this.navigator.definitionsModule.api?.click(D0.omit(f,"callbacks"),D0.omit(y,"definition")),this.navigator.emit("definition.click",f,y))}}}}async prepareContainers(t){for(let n in qe)await this.ensureHighlightsContainer(t,n)}async ensureHighlightsContainer(t,n){let i=t.document;if(!i.getElementById(n)){let o=i.createElement("div");o.setAttribute("id",n),n!==qe.R2_ID_GUTTER_RIGHT_CONTAINER&&o.style.setProperty("pointer-events","none"),this.navigator.view?.layout==="fixed"&&(o.style.setProperty("position","absolute"),o.style.setProperty("top","0"),o.style.setProperty("left","0")),i.body&&i.body.append(o),(await this.layerSettings.getProperty(n))?.value===!1&&(o.style.display="none")}return i.getElementById(n)}hideAllhighlights(t){this.removeAllChildNodes(t.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER)),this.removeAllChildNodes(t.getElementById(qe.R2_ID_SEARCH_CONTAINER)),this.removeAllChildNodes(t.getElementById(qe.R2_ID_READALOUD_CONTAINER)),this.removeAllChildNodes(t.getElementById(qe.R2_ID_PAGEBREAK_CONTAINER)),this.removeAllChildNodes(t.getElementById(qe.R2_ID_DEFINITIONS_CONTAINER))}destroyAllhighlights(t){this.hideAllhighlights(t),tn.splice(0,tn.length)}removeAllChildNodes(t){for(;t.firstChild;)t.removeChild(t.firstChild)}destroyHighlights(t){let n=this.navigator.iframes[0].contentWindow?.document;if(n){let i;switch(t){case it.ReadAloud:i=n.getElementById(qe.R2_ID_READALOUD_CONTAINER),i&&this.removeAllChildNodes(i);break;case it.Search:i=n.getElementById(qe.R2_ID_SEARCH_CONTAINER),i&&this.removeAllChildNodes(i);break;case it.PageBreak:i=n.getElementById(qe.R2_ID_PAGEBREAK_CONTAINER),i&&this.removeAllChildNodes(i);break;case it.Definition:i=n.getElementById(qe.R2_ID_DEFINITIONS_CONTAINER),i&&this.removeAllChildNodes(i);break;case it.LineFocus:i=n.getElementById(qe.R2_ID_LINEFOCUS_CONTAINER),i&&this.removeAllChildNodes(i);break;case it.Comment:i=n.getElementById(qe.R2_ID_GUTTER_RIGHT_CONTAINER),i&&this.removeAllChildNodes(i);break;default:i=n.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER),i&&this.removeAllChildNodes(i),tn.splice(0,tn.length);break}}}destroyHighlight(t,n){if(!t)return;let i=-1;tn.find((l,u)=>(i=u,l.id===n))&&i>=0&&i<tn.length&&tn.splice(i,1);let a=t.getElementById(n);a&&this.removeAllChildNodes(a)}createHighlight(t,n,i,o,a,l,u,d,h,y){try{let b=`${n.rangeInfo.startContainerElementCssSelector}${n.rangeInfo.startContainerChildTextNodeIndex}${n.rangeInfo.startOffset}${n.rangeInfo.endContainerElementCssSelector}${n.rangeInfo.endContainerChildTextNodeIndex}${n.rangeInfo.endOffset}`,w=Fi.hash(b),p=(y||"R2_HIGHLIGHT_")+w;this.destroyHighlight(t.document,p);let m=`rgb(${ls.red}, ${ls.green}, ${ls.blue})`,f={color:i||m,id:p,pointerInteraction:o,selectionInfo:n,marker:a,icon:l,popup:u,style:d,type:h||it.Annotation};(h===it.Annotation||h===it.Definition||h===void 0)&&tn.push(f);let g=this.createHighlightDom(t,f);return f.position=parseInt((g?.hasChildNodes()?g.childNodes[0]:g).style.top.replace("px","")),[f,g]}catch(b){throw"Can't create highlight: "+b}}createHighlightDom(t,n){let i=t.document,o=Jd(i,n.selectionInfo.rangeInfo);if(!o)return;for(let N in qe)this.ensureHighlightsContainer(t,N);let a=i.createElement("div");a.setAttribute("id",n.id),a.setAttribute("class",F_),a.style.setProperty("pointer-events","none"),n.pointerInteraction&&a.setAttribute("data-click","1");let l=this.navigator.view?.isPaginated();l?i.body.style.position="revert":i.body.style.position="relative";let u=i.body.getBoundingClientRect(),d=this.getScrollingElement(i),h=l?-d.scrollLeft:u.left,y=l?-d.scrollTop:u.top,b=1,w=!1,p=!1,f=w||p||!1;$n.default.debug(f),f=!0;let g=zd(o,f),v=3,A=2,C=3,O=0,E=24,T,I;for(let N of g){let q=i.createElement("div");q.setAttribute("class",Tn),q.dataset.marker=""+n.marker;let z="";if(w&&n.marker!==Ve.Custom&&n.marker!==Ve.Bookmark&&n.marker!==Ve.Comment){let x=n.color;Qe.isHexColor(x)&&(x=Qe.hexToRgbChannels(x)),z+=`border-bottom: ${A*b}px solid rgba(${x.red}, ${x.green}, ${x.blue}, ${_r}) !important`}if(n.marker===Ve.Custom||n.marker===Ve.Bookmark)if(n.style?.default){for(let x=0;x<n.style?.default?.length;x++){let R=n.style?.default[x];z+=`${R.property}: ${R.value} !${R.priority};`}q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; ${z}`)}else n.style?.defaultClass&&(q.classList.add(n.style?.defaultClass),q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; ${z}`));else if(n.marker===Ve.Underline||n.marker===Ve.Comment)if(typeof n.color=="object"){let x=n.color;q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; background-color: rgba(${x.red}, ${x.green}, ${x.blue}, ${0}) !important; ${z}`),q.style.setProperty("border-bottom",`2px solid rgba(${x.red}, ${x.green}, ${x.blue}, ${1})`,"important")}else if(Qe.isHexColor(n.color)){let x=Qe.hexToRgbChannels(n.color);q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; background-color: rgba(${x.red}, ${x.green}, ${x.blue}, ${0}) !important; ${z}`),q.style.setProperty("border-bottom",`2px solid rgba(${x.red}, ${x.green}, ${x.blue}, ${1})`,"important")}else q.setAttribute("style",`border-radius: ${v}px !important; ${z}`);else if(typeof n.color=="object"){let x=n.color;q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; background-color: rgba(${x.red}, ${x.green}, ${x.blue}, ${_r}) !important; ${z}`)}else if(Qe.isHexColor(n.color)){let x=Qe.hexToRgbChannels(n.color);q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; background-color: rgba(${x.red}, ${x.green}, ${x.blue}, ${_r}) !important; ${z}`)}else q.setAttribute("style",`border-radius: ${v}px !important; ${z}`);q.style.setProperty("pointer-events","none"),q.style.position="absolute",q.scale=b,q.rect={height:N.height,left:N.left-h,top:N.top-y,width:N.width},n.pointerInteraction&&(q.setAttribute("data-click","1"),q.tabIndex=0),q.style.width=`${q.rect.width*b}px`,q.style.height=`${q.rect.height*b}px`,q.style.left=`${q.rect.left*b}px`,q.style.top=`${q.rect.top*b}px`,a.append(q);let ne=parseInt(q.style.top.replace("px",""));if((ne<O||O===0)&&(O=ne),E=parseInt(q.style.height.replace("px","")),p){let x=i.createElement("div");x.setAttribute("class",Tn);let R=n.color;Qe.isHexColor(R)&&(R=Qe.hexToRgbChannels(R)),x.setAttribute("style",`background-color: rgba(${R.red}, ${R.green}, ${R.blue}, ${_r}) !important;`),x.style.setProperty("pointer-events","none"),x.style.position="absolute",x.scale=b,x.rect={height:N.height,left:N.left-h,top:N.top-y,width:N.width},x.style.width=`${x.rect.width*b}px`,x.style.height=`${C*b}px`,x.style.left=`${x.rect.left*b}px`,x.style.top=`${(x.rect.top+x.rect.height/2-C/2)*b}px`,a.append(x)}let oe=this.navigator.iframes[0].contentWindow?.innerWidth,ae=parseInt(getComputedStyle(i.documentElement).getPropertyValue("column-count")),te=parseInt(getComputedStyle(i.documentElement).getPropertyValue("column-width")),le=parseInt(getComputedStyle(i.body).getPropertyValue("padding-left")),xe=oe/(ae||1);xe<te&&(xe=oe),l||(xe=parseInt(getComputedStyle(i.body).width.replace("px","")));let fe=this.navigator.settings.fontSize/100,J=20*fe;fe<=1&&(J=-60);let D=0*fe;fe<=1&&(D=-60),T=Math.floor(N.left/xe)*xe+xe-(E<40?40:E)+D,I=Math.floor(N.left/xe)*xe+(E<40?40:E)-J;let k=parseInt(this.navigator.iframes[0].contentDocument.documentElement.style.getPropertyValue("--USER__pageMargins"));k>=2&&(I=I+le/ae,T=T-le/ae),l||(T=parseInt(getComputedStyle(this.navigator.iframes[0].contentDocument?.body).width.replace("px","")),I=parseInt(getComputedStyle(this.navigator.iframes[0].contentDocument?.body).width.replace("px",""))-xe,k>=2&&(I=I+le/2,T=T-le/2))}let M=o.getBoundingClientRect(),j=i.createElement("div");j.setAttribute("class",Sl),j.style.setProperty("pointer-events","none"),j.style.position="absolute",j.scale=b,j.rect={height:M.height,left:M.left-h,top:M.top-y,width:M.width},j.style.width=`${j.rect.width*b}px`,j.style.height=`${j.rect.height*b}px`,j.style.left=`${j.rect.left*b}px`,j.style.top=`${j.rect.top*b}px`,a.append(j);let U=i.createElement("div");if(U.setAttribute("class",Al),n.icon?.position==="left")U.setAttribute("style",`position: absolute;top:${O}px;left:${I+this.navigator.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${E}px; width:${E}px;`);else if(n.icon?.position==="inline")U.setAttribute("style",`position: absolute;top:${O-E/2}px;left:${parseInt(j.style.left.replace("px",""))+parseInt(j.style.width.replace("px",""))-E/2}px;height:${E}px; width:${E}px;`);else if(n.icon?.position==="center"){let q=E/3*2;U.setAttribute("style",`position: absolute;top:${O}px;left:${parseInt(j.style.left.replace("px",""))+parseInt(j.style.width.replace("px",""))-q}px;height:${E}px; width:${E}px;`)}else n.note&&n.marker!==Ve.Custom&&n.marker!==Ve.Bookmark&&n.marker!==Ve.Comment&&n.marker!==Ve.Highlight&&n.marker!==Ve.Underline?U.setAttribute("style",`position: absolute;top:${O-E/2}px;left:${parseInt(j.style.left.replace("px",""))+parseInt(j.style.width.replace("px",""))-E/2}px;height:${E}px; width:${E}px;`):n.note&&n.marker===Ve.Comment||n.marker===Ve.Highlight||n.marker===Ve.Underline?U.setAttribute("style",`position: absolute;top:${O}px;left:${T+this.navigator.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${E}px; width:${E}px;`):U.setAttribute("style",`position: absolute;top:${O}px;left:${T+this.navigator.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${E}px; width:${E}px;`);if(n.marker===Ve.Custom||n.marker===Ve.Bookmark)n.icon?.class?(U.classList.add(n.icon?.class),U.id=n.icon?.id):n.icon?.svgPath?U.innerHTML=ua(`${n.icon?.id}`,`${n.icon?.title}`,`${n.icon?.svgPath}`,"icon open",E,`${n.icon?.color} !important`):n.icon?.title&&(U.innerHTML=n.icon?.title);else if(n.note){let N=n.color;Qe.isHexColor(N)&&(N=Qe.hexToRgbChannels(N)),n.marker===Ve.Comment||n.marker===Ve.Highlight||n.marker===Ve.Underline?U.innerHTML=ua("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="14"/>',"icon open",E/2,`rgba(${N.red}, ${N.green}, ${N.blue}, 1) !important`):U.innerHTML=ua("note-icon","Note",'<rect fill="none" height="24" width="24"/><path d="M19,5v9l-5,0l0,5H5V5H19 M19,3H5C3.9,3,3,3.9,3,5v14c0,1.1,0.9,2,2,2h10l6-6V5C21,3.9,20.1,3,19,3z M12,14H7v-2h5V14z M17,10H7V8h10V10z"/>',"icon open",E,`rgba(${N.red}, ${N.green}, ${N.blue}, 1) !important`)}U.style.setProperty("pointer-events","all");let B=this;if(n.type!==it.PageBreak&&n.type!==it.Definition&&U.addEventListener("click",async function(N){let q;B.navigator.rights.enableAnnotations?(q=await B.navigator.annotationModule?.getAnnotationByID(n.id),B.navigator.annotationModule?.api?.selectedAnnotation(q).then(async()=>{})):B.navigator.rights.enableBookmarks&&(q=await B.navigator.bookmarkModule?.getAnnotationByID(n.id)),$n.default.log("selected highlight "+q.id),B.lastSelectedHighlight=q.id;let z=document.getElementById("highlight-toolbox");if(z)if(z.style.top=N.clientY+(B.navigator.attributes?.navHeight??0)+"px",z.style.left=N.clientX+"px",getComputedStyle(z).display==="none"){let xe=function(){B.navigator.rights.enableAnnotations?B.navigator.annotationModule?.deleteSelectedHighlight(q).then(async()=>{$n.default.log("delete highlight "+q.id),z.style.display="none",B.selectionMenuClosed()}):B.navigator.rights.enableBookmarks&&B.navigator.bookmarkModule?.deleteSelectedHighlight(q).then(async()=>{$n.default.log("delete highlight "+q.id),z.style.display="none",B.selectionMenuClosed()})};z.style.display="block",B.toolboxMode("edit");let oe=document.getElementById("colorIcon"),ae=document.getElementById("highlightIcon");oe&&(oe.style.display="none"),ae&&(ae.style.display="none");let te=document.getElementById("commentIcon"),le=document.getElementById("cloneCommentIcon");if(le){let D=le.parentElement;D&&D.removeChild(le)}te&&(te.style.display="none");let fe=document.getElementById("deleteIcon"),J=document.getElementById("cloneDeleteIcon");if(J){let D=J.parentElement;D&&D.removeChild(J)}if(fe){fe.style.display="none";let D=fe.cloneNode(!0),k=fe.parentElement;D.style.display="unset",D.id="cloneDeleteIcon",D.addEventListener("click",xe,!1),k&&k.append(D)}}else z.style.display="none",B.selectionMenuClosed(),z.offsetWidth,z.style.display="block";let ne=Array.from(a.querySelectorAll(`.${Tn}`));B.setHighlightAreaStyle(i,ne,n)}),n.note){let N=document.createElement("span");N.innerHTML=n.note,N.className="icon-tooltip",n.marker===Ve.Custom||n.marker===Ve.Bookmark?(n.popup?.background&&N.style.setProperty("background",n.popup.background),n.popup?.textColor&&N.style.setProperty("color",n.popup.textColor),n.popup?.class&&N.classList.add(n.popup.class)):(N.style.setProperty("background","lightyellow"),N.style.setProperty("color","black"))}switch((n.note||n.marker===Ve.Custom||n.marker===Ve.Bookmark)&&a.append(U),n.type){case it.Search:i.getElementById(qe.R2_ID_SEARCH_CONTAINER).append(a);break;case it.ReadAloud:i.getElementById(qe.R2_ID_READALOUD_CONTAINER).append(a);break;case it.PageBreak:i.getElementById(qe.R2_ID_PAGEBREAK_CONTAINER).append(a);break;case it.Definition:i.getElementById(qe.R2_ID_DEFINITIONS_CONTAINER).append(a);break;default:i.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER).append(a);break}return a}addSelectionMenuItem(t){(this.properties?.selectionMenuItems??[])&&(this.properties?.selectionMenuItems??[]).push(t)}};var Z_=nt(K0());H();var r8=nt(Jt());var Co={className:r=>!0,idName:r=>!0,tagName:r=>!0};var Q_=nt(Yd()),Ui=nt(Jt());H();var X_=nt(Jt()),cs;(function(n){n.BookmarkCreated="BookmarkCreated",n.HighlightCreated="HighlightCreated"})(cs||(cs={}));var Tl=class{constructor(t,n,i){this.currSeconds=0;this.publication=t,this.properties=n,this.api=i}static async create(t){let n=new this(t.publication,t,t.api);return await n.start(),n}async start(){this.startResearchSession()}async stop(){X_.default.log("Consumption module stop"),this.endResearchSession()}initialize(){let t=this.navigator.iframes[0].contentWindow;if(t){let n=this;t.onload=function(){n.resetTimer()},t.onmousemove=function(){n.resetTimer()},t.onmousedown=function(){n.resetTimer()},t.ontouchstart=function(){n.resetTimer()},t.onclick=function(){n.resetTimer()},t.onkeypress=function(){n.resetTimer()}}}trackAction(t,n){this.api?.actionTracked(t,n)}startReadingSession(t){if(this.firstReadingLocator&&this.lastReadingLocator){let n=this.lastReadingLocator.locations.totalProgression-this.firstReadingLocator.locations.totalProgression,i=(new Date().getTime()-this.startReadingTimer.getTime())/1e3;this.readingSessions.push({lastLocator:this.lastReadingLocator,firstLocator:this.firstReadingLocator,time:i,progress:Math.round(n*100)})}this.firstReadingLocator=t,this.startReadingTimer=new Date}continueReadingSession(t){this.properties.enableTrackingSession&&(this.startResearchTimer===void 0&&this.startResearchSession(),(this.lastReadingLocator===void 0||this.lastReadingLocator.locations.totalProgression<t.locations.totalProgression)&&(this.lastReadingLocator=t),this.firstReadingLocator===void 0&&(this.firstReadingLocator=t),this.startReadingTimer===void 0&&(this.startReadingTimer=new Date))}startResearchSession(){if(this.properties.enableTrackingSession){this.startResearchTimer=new Date,this.readingSessions=[],clearInterval(this.readingSessionsInterval);let t=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;this.researchSessionId=this.api?.startResearchSession(this.readingSessions,Math.round(t));let n=this;this.readingSessionsInterval=setInterval(function(){n.updateResearchSession()},this.properties.updateSessionInterval*1e3)}}updateResearchSession(){if(this.properties.enableTrackingSession){let t=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;this.api?.updateResearchSession(this.researchSessionId,this.readingSessions,Math.round(t))}}endResearchSession(){if(this.properties.enableTrackingSession){if(this.firstReadingLocator&&this.lastReadingLocator){let n=this.lastReadingLocator.locations.totalProgression-this.firstReadingLocator.locations.totalProgression,i=(new Date().getTime()-this.startReadingTimer.getTime())/1e3;this.readingSessions.push({lastLocator:this.lastReadingLocator,firstLocator:this.firstReadingLocator,time:i,progress:Math.round(n*100)})}let t=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;this.api?.updateResearchSession(this.researchSessionId,this.readingSessions,Math.round(t)),this.api?.endResearchSession(this.researchSessionId,this.readingSessions,Math.round(t)),this.researchSessionId=void 0,this.readingSessions=[],this.startResearchTimer=void 0,clearInterval(this.readingSessionsInterval),clearInterval(this.timer)}}startIdleTimer(){this.currSeconds++,this.currSeconds===this.properties.idleTimeout&&(this.api?.idleSince(this.currSeconds),this.startResearchTimer!==void 0?this.updateResearchSession():this.startResearchSession()),this.currSeconds===this.properties.idleTimeout+this.properties.responseTimeout&&this.endResearchSession()}resetTimer(){clearInterval(this.timer),this.currSeconds=0;let t=this;this.timer=setInterval(function(){t.startIdleTimer()},1e3)}};var us=class{constructor(t,n,i,o,a,l,u,d){this.hide=Ie(document,"#menu-button-hide");this.show=Ie(document,"#menu-button-show");this.annotator=t,this.rights=n,this.publication=i,this.headerMenu=d,this.initialAnnotations=o,this.highlighter=l,this.properties=a,this.api=u}static async create(t){let n=new this(t.annotator,t.rights||{enableAnnotations:!1,enableTTS:!1},t.publication,t.initialAnnotations||null,t,t.highlighter,t.api,t.headerMenu);return await n.start(),n}async stop(){Ui.default.log("Annotation module stop")}async start(){if(this.headerMenu&&(this.highlightsView=Ie(this.headerMenu,"#container-view-highlights")),this.initialAnnotations){var t=this.initialAnnotations.highlights||null;t&&this.annotator?.initAnnotations(t)}setTimeout(()=>{this.properties?.hideLayer?this.navigator.hideLayer("highlights"):this.navigator.showLayer("highlights")},10)}hideAnnotationLayer(){let t=this.navigator.iframes[0].contentDocument;if(t){let n=Ie(t,"#R2_ID_HIGHLIGHTS_CONTAINER");n&&(n.style.display="none")}this.show&&this.hide&&(this.show.style.display="block",this.hide.style.display="none")}showAnnotationLayer(){let t=this.navigator.iframes[0].contentDocument;if(t){let n=Ie(t,"#R2_ID_HIGHLIGHTS_CONTAINER");n&&(n.style.display="block")}this.show&&this.hide&&(this.show.style.display="none",this.hide.style.display="block")}async handleResize(){setTimeout(async()=>{await this.drawHighlights(),await this.showHighlights()},200)}initialize(){return new Promise(async t=>{await document.fonts.ready,this.rights.enableAnnotations&&setTimeout(()=>{this.drawHighlights(),this.showHighlights(),Ee(this.navigator.iframes[0].contentDocument?.body,"click",this.click.bind(this))},300),t(null)})}click(t){if(this.activeAnnotationMarkerId){let n=this.highlighter?.properties?.selectionMenuItems?.filter(i=>i.id===this.activeAnnotationMarkerId);if(n&&n?.length>0){let i=Q_.cloneDeep(n[0]);i.marker=Ve.Custom,this.activeAnnotationMarkerPosition&&(i.icon.position=this.activeAnnotationMarkerPosition),i.highlight.style.default=null,i.highlight.style.hover=null;let o=this.navigator.iframes[0].contentDocument;if(o){let h=function(b){try{let w=d.navigator.iframes[0].contentDocument;return w?wn(b,w,Co):""}catch(w){return Ui.default.log("uniqueCssSelector:"),Ui.default.error(w),""}},a=this.highlighter?.dom(o.body).getSelection(),l=a.getRangeAt(0),u=a.anchorNode;l.setStart(u,l.startOffset),l.setEnd(u,l.endOffset+1),a.removeAllRanges(),a.addRange(l);let d=this,y=Xr(l,h);if(a.removeAllRanges(),y){let b={rangeInfo:y},w=this.navigator.highlighter?.createHighlight(this.navigator.highlighter?.dom(o.body).getWindow(),b,i.highlight.color,!0,Ve.Bookmark,i.icon,i.popup,i.highlight.style);w&&this.saveAnnotation(w[0]).then(p=>{Ui.default.log("saved bookmark "+p.id)})}o.getSelection()?.removeAllRanges()}}}}async scrollToHighlight(t){Ui.default.log("still need to scroll to "+t);var n=await this.annotator?.getAnnotationElement(t,this.navigator.iframes[0].contentWindow);n.scrollIntoView({block:"center",behavior:"smooth"})}async updateLocalHighlight(t){if(this.annotator){let n=await this.annotator.deleteAnnotation(t.id),i=await this.addAnnotation(t);return Ui.default.log("Highlight deleted "+JSON.stringify(n)),Ui.default.log("Highlight added "+JSON.stringify(i)),await this.showHighlights(),await this.drawHighlights(),i}else return new Promise(n=>n(null))}async deleteLocalHighlight(t){if(this.annotator){var n=await this.annotator.deleteAnnotation(t);return Ui.default.log("Highlight deleted "+JSON.stringify(n)),await this.showHighlights(),await this.drawHighlights(),n}else return new Promise(i=>i(null))}async deleteAnnotation(t){await this.deleteLocalHighlight(t.id)}async addAnnotation(t){await this.annotator?.saveAnnotation(t),await this.showHighlights(),await this.drawHighlights()}async deleteHighlight(t){this.api?.deleteAnnotation?this.api?.deleteAnnotation(t).then(async()=>{this.deleteLocalHighlight(t.id)}):this.deleteLocalHighlight(t.id)}async deleteSelectedHighlight(t){this.api?.deleteAnnotation?this.api.deleteAnnotation(t).then(async()=>{this.deleteLocalHighlight(t.id)}):this.deleteLocalHighlight(t.id)}async updateAnnotation(t){this.api?.updateAnnotation?this.api.updateAnnotation(t).then(async()=>{this.updateLocalHighlight(t)}):this.updateLocalHighlight(t)}async saveAnnotation(t){if(this.annotator){var n=this.publication.getTOCItem(this.navigator.currentChapterLink.href);this.navigator.currentTocUrl&&(n=this.publication.getTOCItem(this.navigator.currentTocUrl)),n===void 0&&(n=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href));let i=this.navigator.view?.getCurrentPosition(),o=this.navigator.iframes[0].contentDocument;if(o){let a=Gr(o,"body"),l=t.position?t.position/a.scrollHeight:i,u=(0,Z_.v4)(),d;if(n){let h=n.Href;if(h.indexOf("#")>0&&(h=h.slice(0,h.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let y=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),b=Math.ceil((l??0)*(y.length-1)),w=y[b];d=Yt(et({},w),{id:u,href:h,created:new Date,title:this.navigator.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}})}else d={id:u,href:h,locations:{progression:l},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}}}if(d)if(this.navigator.consumptionModule?.trackAction(d,cs.HighlightCreated),this.api?.addAnnotation)try{let h=await this.api.addAnnotation(d),y=await this.annotator.saveAnnotation(h);return await this.showHighlights(),await this.drawHighlights(),new Promise(b=>b(y))}catch(h){await this.showHighlights(),await this.drawHighlights()}else{let h=await this.annotator.saveAnnotation(d);return await this.showHighlights(),await this.drawHighlights(),new Promise(y=>y(h))}}}return new Promise(i=>i(null))}getAnnotations(){let t=[];return this.annotator&&(t=this.annotator.getAnnotations()),t}showHighlights(){let t=[];this.annotator&&(t=this.annotator.getAnnotations(),t&&(t=t.filter(n=>n.highlight.marker!==Ve.Bookmark),t.forEach(n=>{tn.push(n.highlight)}))),this.highlightsView&&this.createTree(Si.Annotation,t,this.highlightsView)}async drawHighlights(){if(this.rights.enableAnnotations&&this.highlighter){if(this.api){let n=[];if(this.annotator&&(n=this.annotator.getAnnotationsByChapter(this.navigator.currentLocator().href)),this.highlighter&&n&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.highlighter.destroyHighlights(it.Annotation);for(let i of n){tn.push(i.highlight);let o=i,a=this.navigator.currentChapterLink.href;var t=this.publication.getTOCItem(a);if(this.navigator.currentTocUrl!==void 0&&(t=this.publication.getTOCItem(this.navigator.currentTocUrl)),t===null&&(t=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),t){let l=t.Href;l.indexOf("#")>0&&(l=l.slice(0,l.indexOf("#"))),o.href===l&&(await this.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,i.highlight),setTimeout(async()=>{if(o.highlight?.marker===Ve.Underline){let u=await this.annotator?.getAnnotationPosition(i.id,this.navigator.iframes[0].contentWindow),d='<div class="comment" style="top: '+u+'px;width:20px"></div>',h=document.createElement("div");h.innerHTML=d;let y=h.childNodes[0],b=document.createElement("i");b.innerHTML="sticky_note_2",b.className="material-icons",b.style.color=o.highlight.color,y.appendChild(b),Ee(h,"click",w=>{w.preventDefault(),w.stopPropagation(),this.scrollToHighlight(o.id)})}},100))}}}}else{let n=[];if(this.annotator&&(n=this.annotator.getAnnotationsByChapter(this.navigator.currentLocator().href)),this.highlighter&&n&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.highlighter.destroyHighlights(it.Annotation);for(let i of n){tn.push(i.highlight);let o=i,a=this.navigator.currentChapterLink.href,l=this.publication.getTOCItem(a);if(this.navigator.currentTocUrl&&(l=this.publication.getTOCItem(this.navigator.currentTocUrl)),l===null&&(l=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),l){let u=l.Href;u.indexOf("#")>0&&(u=u.slice(0,u.indexOf("#"))),o.href===u&&(await this.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,i.highlight),setTimeout(async()=>{if(o.highlight?.marker===Ve.Underline){let d=await this.annotator?.getAnnotationPosition(i.id,this.navigator.iframes[0].contentWindow),h='<div class="comment" style="top: '+d+"px;background: "+o.highlight?.color+';width:20px"></div>',y=document.createElement("div");y.innerHTML=h,y.childNodes[0].innerHTML=nr.note,Ee(y,"click",b=>{b.preventDefault(),b.stopPropagation(),this.scrollToHighlight(o.id)})}},100))}}}}this.properties?.initialAnnotationColor&&this.highlighter.setColor(this.properties?.initialAnnotationColor),this.repositionGutters()}}repositionGutters(){let t=this.navigator.iframes[0].contentDocument;if(t&&(this.commentGutter=t.getElementById(qe.R2_ID_GUTTER_RIGHT_CONTAINER),this.navigator.view?.isScrollMode()&&this.properties?.enableComments?this.commentGutter?.style.removeProperty("display"):this.commentGutter?.style.setProperty("display","none"),this.commentGutter&&this.navigator.view?.isScrollMode()&&this.properties?.enableComments)){this.commentGutter.innerHTML="";let n=[];this.annotator&&(n=this.annotator.getAnnotationsByChapter(this.navigator.currentLocator().href),n&&(n=n.filter(i=>i.highlight?.note?.length>0),n=this.syncPosition(n),n=this.reposition(n),n.forEach(i=>{let o=document.createElement("i");o.innerHTML="sticky_note_2",o.className="material-icons",o.style.color=i.highlight.color;let a=t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),l,u;a&&(l=a.querySelector(`#${i.highlight.id}`)),u=l.getElementsByClassName(Tn)[0];let h=parseInt(u.style.height.replace("px","")),y=i.highlight.position,b=t.createElement("div");b.setAttribute("style",`position: absolute;top:${y}px;display: flex;max-width: 250px !important;height:${h}px;width: 200px;align-items: center;`);let w=t.createElement("div");b.appendChild(w);let p=i.highlight.color;Qe.isHexColor(p)&&(p=Qe.hexToRgbChannels(p)),b.innerHTML=ua("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="8"/>',"icon open",10,`rgba(${p.red}, ${p.green}, ${p.blue}, 1) !important`);let m=t.createElement("div");m.innerHTML=i.highlight?.note,m.setAttribute("style",`height:${h}px;overflow: hidden;padding-left: 5px;`),b.appendChild(m),Ee(b,"click",f=>{f.preventDefault(),f.stopPropagation(),this.scrollToHighlight(i.highlight.id)}),this.commentGutter?.appendChild(b)})))}}createTree(t,n,i){if(n){let o=this,a=this.publication.readingOrder;if(a.length){let l=(u,d)=>{let h=document.createElement("ul");h.className="sidenav-annotations";for(let y of d){let b=document.createElement("li"),w=document.createElement("a"),p=document.createElement("span");if(w.tabIndex=-1,w.className="chapter-link",y.Href){let f=this.publication.getAbsoluteHref(y.Href),g=this.publication.getTOCItemAbsolute(f);w.href=f,w.innerHTML=g?.Title||"",b.appendChild(w)}else p.innerHTML=y.Title||"",p.className="chapter-title",b.appendChild(p);Ee(w,"click",f=>{f.preventDefault(),f.stopPropagation();let g={href:w.href,locations:{progression:0},type:y.TypeLink,title:w.title};this.navigator.stopReadAloud(),this.navigator.navigate(g)});let m=document.createElement("ol");n.forEach(function(f){let g=y.Href.indexOf("#")!==-1?y.Href.slice(0,y.Href.indexOf("#")):y.Href;if(y.Href&&f.href.endsWith(g)){let v=document.createElement("li");v.className="annotation-item";let A=document.createElement("a");if(A.setAttribute("href",f.href),t===Si.Annotation){A.className="highlight-link";let O=document.createElement("span"),E=document.createElement("span");if(O.className="title",E.innerHTML=f.highlight.selectionInfo.cleanText,f.highlight?.marker===Ve.Underline)if(typeof f.highlight?.color=="object"){let M=f.highlight?.color;M&&E.style.setProperty("border-bottom",`2px solid ${Qe.hexToRgbA(M)}`,"important")}else E.style.setProperty("border-bottom",`2px solid ${f.highlight?.color}`,"important");else if(typeof f.highlight?.color=="object"){let M=f.highlight?.color;M&&(E.style.backgroundColor=Qe.hexToRgbA(M))}else{let M=f.highlight?.color;M&&(E.style.backgroundColor=M)}O.appendChild(E),A.appendChild(O);let T=document.createElement("span"),I=Math.round((f.locations.progression??0)*100)+"% through resource";T.className="subtitle",T.innerHTML=I,A.appendChild(T)}let C=document.createElement("span");if(C.className="timestamp",C.innerHTML=us.readableTimestamp(f.created),A.appendChild(C),Ee(A,"click",O=>{O.preventDefault(),O.stopPropagation(),o.handleAnnotationLinkClick(O,f)}),v.appendChild(A),o.navigator.sideNavExpanded){let O=document.createElement("button");O.className="delete",O.innerHTML=nr.delete,Ee(O,"click",E=>{E.preventDefault(),E.stopPropagation(),o.handleAnnotationLinkDeleteClick(t,E,f)}),v.appendChild(O)}m.appendChild(v)}}),m.children.length>0&&(h.appendChild(b),h.appendChild(m)),h.children.length>0&&u.appendChild(h),y.Children&&y.Children.length>0&&l(u,y.Children)}};i.innerHTML="",l(i,a)}}}handleAnnotationLinkClick(t,n){n?(n.href=this.publication.getAbsoluteHref(n.href),this.navigator.stopReadAloud(),this.navigator.navigate(n)):Ui.default.log("annotation data missing: ",t)}handleAnnotationLinkDeleteClick(t,n,i){Ui.default.log("annotation data locator: ",i),i?t===Si.Annotation&&this.deleteHighlight(i):Ui.default.log("annotation data missing: ",n)}static readableTimestamp(t){let n=new Date(t);return n.toDateString()+" "+n.toLocaleTimeString()}async getAnnotation(t){return this.annotator?.getAnnotation(t)}async getAnnotationByID(t){return this.annotator?.getAnnotationByID(t)}syncPosition(t){let n=this.navigator.iframes[0].contentDocument,i=(o,a)=>{let l=n.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),u,d;l&&(u=l.querySelector(`#${a.highlight.id}`)),d=u.getElementsByClassName(Tn)[0];let y=parseInt(d.style.top.replace("px","")),b=Yt(et({},a),{highlight:Yt(et({},a.highlight),{position:y})});return[...o,b]};return t.reduce(i,[])}reposition(t){let n=this.navigator.iframes[0].contentDocument,i=(o,a,l)=>{let u=t[0],d=n.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),h,y;d&&(h=d.querySelector(`#${u.highlight.id}`)),y=h.getElementsByClassName(Tn)[0];let w=parseInt(y.style.height.replace("px","")),p=a.highlight.position,m=o[l-1]&&o[l-1].highlight.position,g=l===0?0:m+w+0,v=g>p?g:p,A=Yt(et({},a),{highlight:Yt(et({},a.highlight),{position:v})});return[...o,A]};return t.sort(function(o,a){return o.highlight.position-a.highlight.position}).reduce(i,[])}};H();var Y0=nt(K0());var $i=nt(Jt());var ds=class{static async create(t){let n=new this(t.annotator,t.rights||{enableBookmarks:!1},t.publication,t,t.initialAnnotations,t.api,t.headerMenu);return await n.start(),new Promise(i=>i(n))}constructor(t,n,i,o,a,l,u){this.annotator=t,this.rights=n,this.publication=i,this.headerMenu=u,this.initialAnnotations=a,this.properties=o,this.api=l}stop(){$i.default.log("Bookmark module stop")}async start(){if(this.headerMenu&&(this.bookmarksView=Ie(this.headerMenu,"#container-view-bookmarks")),this.headerMenu&&(this.sideNavSectionBookmarks=Ie(this.headerMenu,"#sidenav-section-bookmarks")),this.headerMenu){let t=Ie(this.headerMenu,"#menu-button-bookmark");t&&t.parentElement?.style.removeProperty("display"),t&&Ee(t,"click",this.saveBookmark.bind(this))}if(this.initialAnnotations){let t=this.initialAnnotations.bookmarks||null;t&&this.annotator?.initBookmarks(t)}}async handleResize(){setTimeout(async()=>{await this.drawBookmarks(),await this.showBookmarks(),setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("highlights"):this.navigator.showLayer("highlights")},10)},100)}initialize(){return new Promise(async t=>{await document.fonts.ready,this.rights.enableBookmarks&&setTimeout(()=>{this.drawBookmarks(),this.showBookmarks()},300),t(null)})}async deleteBookmark(t){if(this.annotator)if(this.api?.deleteBookmark){await this.api?.deleteBookmark(t);let n=await this.annotator.deleteBookmark(t);return $i.default.log("Bookmark deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),n}else{let n=await this.annotator.deleteBookmark(t);return $i.default.log("Bookmark deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),n}else return new Promise(n=>n(null))}async saveBookmarkPlus(){await this.addBookmarkPlus()}async saveBookmark(){if(this.annotator){var t=this.publication.getTOCItem(this.navigator.currentChapterLink.href);if(this.navigator.currentTocUrl&&(t=this.publication.getTOCItem(this.navigator.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),t){let n=t.Href;n.indexOf("#")>0&&(n=n.slice(0,n.indexOf("#")));let i=this.navigator.view?.getCurrentPosition(),o=(0,Y0.v4)(),a;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let l=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),u=Math.ceil((i??0)*(l.length-1)),d=l[u];a=Yt(et({},d),{id:o,href:n,created:new Date,title:this.navigator.currentChapterLink.title})}else a={id:o,href:n,locations:{progression:i},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title};if(!this.annotator.locatorExists(a,Si.Bookmark))if(this.navigator.consumptionModule?.trackAction(a,cs.BookmarkCreated),this.api?.addBookmark){let l=await this.api.addBookmark(a);l&&(a=l),$i.default.log(a);let u=this.annotator.saveBookmark(a);return $i.default.log("Bookmark added "+JSON.stringify(u)),this.showBookmarks(),await this.drawBookmarks(),u}else{let l=this.annotator.saveBookmark(a);return $i.default.log("Bookmark added "+JSON.stringify(l)),this.showBookmarks(),await this.drawBookmarks(),l}}}}async addBookmarkPlus(){let t=this,n=this.navigator.highlighter?.visibleTextRects[0],i=this.navigator.iframes[0].contentDocument;if(i){let u=this.navigator.highlighter?.dom(i.body).getWindow().document.createRange(),d=this.navigator.highlighter?.dom(this.navigator.iframes[0].contentDocument?.body).getSelection();d.removeAllRanges(),n&&u.selectNodeContents(n.node),d.addRange(u);let h=zd(u,!1),y=0;for(let b of h){if(!this.navigator.highlighter?.isOutsideViewport(b)){let w=d.focusNode,p=d.focusOffset;d.collapse(d.anchorNode,d.anchorOffset);for(let v=0;v<y;v++)d.modify("move","forward","line");d.extend(w,p);let m=d.focusNode,f=d.focusNode.length;d.collapse(d.anchorNode,d.anchorOffset);let g=f;d.anchorOffset>f?g=f:g=d.anchorOffset+1,d.modify("move","forward","character"),d.modify("move","backward","word"),d.extend(m,g),d.modify("extend","backward","character"),d.modify("extend","forward","word");break}y++}}function o(u){let d={},h=t.navigator.iframes[0].contentDocument;if(h)return wn(u,t.navigator.highlighter?.dom(h.body).getDocument(),d)}let a=this.navigator.iframes[0].contentWindow,l={id:"bookmarkIcon",marker:Ve.Bookmark,icon:{id:"bookmarkIcon",title:"Bookmark",svgPath:'<path d="M0 0h24v24H0V0z" fill="none"/><path d="M17 3H7c-1.1 0-2 .9-2 2v16l7-3 7 3V5c0-1.1-.9-2-2-2z"/>',color:"#000000",position:"left"},popup:{background:"#000000",textColor:"#ffffff"},highlight:{color:"#000000",style:{default:[{property:"border-bottom",value:"0px dashed #000000",priority:"important"}]}}};if(a!==null){let u=Er(a,o);if(u===void 0){let h=t.navigator.iframes[0].contentDocument;u=this.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(h)}let d=t.navigator.iframes[0].contentDocument;if(u&&d){let h=this.navigator.highlighter?.createHighlight(this.navigator.highlighter?.dom(d.body).getWindow(),u,l.highlight?.color,!0,Ve.Bookmark,l.icon,l.popup,l.highlight?.style);if(this.navigator.iframes[0].contentDocument?.getSelection()?.removeAllRanges(),h)return this.saveAnnotation(h[0]).then(y=>{$i.default.log("saved bookmark "+y?.id)})}}}async saveAnnotation(t){if(this.annotator){var n=this.publication.getTOCItem(this.navigator.currentChapterLink.href);this.navigator.currentTocUrl&&(n=this.publication.getTOCItem(this.navigator.currentTocUrl)),n===null&&(n=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href));let i=this.navigator.view?.getCurrentPosition(),o=this.navigator.iframes[0].contentDocument;if(o){let a=Gr(o,"body"),l=t.position?t.position/a.scrollHeight:i,u=(0,Y0.v4)(),d;if(n){let h=n.Href;if(h.indexOf("#")>0&&(h=h.slice(0,h.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let y=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),b=Math.ceil((l??0)*(y.length-1)),w=y[b];d=Yt(et({},w),{id:u,href:h,created:new Date,title:this.navigator.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}})}else d={id:u,href:h,locations:{progression:l},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}}}if(d)if(this.navigator.consumptionModule?.trackAction(d,cs.BookmarkCreated),this.api?.addBookmark){let h=await this.api.addBookmark(d),y=await this.annotator.saveAnnotation(h);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(b=>b(y))}else{let h=await this.annotator.saveAnnotation(d);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(y=>y(h))}}}return new Promise(i=>i(void 0))}getBookmarks(){let t=[];return this.annotator&&(t=this.annotator.getBookmarks()),t}showBookmarks(){let t=[];this.annotator&&(t=this.annotator.getBookmarks());let n=[];this.annotator&&(n=this.annotator.getAnnotations(),n&&(n=n.filter(i=>i.highlight.marker===Ve.Bookmark),t?t.push.apply(t,n):t=n)),this.bookmarksView&&this.createTree(Si.Bookmark,t,this.bookmarksView)}async drawBookmarks(){if(this.rights.enableBookmarks&&this.navigator.highlighter)if(this.api){let n=[];if(this.annotator&&(n=await this.annotator.getAnnotations()),this.navigator.highlighter&&n&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.navigator.highlighter.destroyHighlights(it.Annotation);for(let i of n){tn.push(i.highlight);let o=i,a=this.navigator.currentChapterLink.href;var t=this.publication.getTOCItem(a);if(this.navigator.currentTocUrl&&(t=this.publication.getTOCItem(this.navigator.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),t){let l=t.Href;l.indexOf("#")>0&&(l=l.slice(0,l.indexOf("#"))),o.href===l&&await this.navigator.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,i.highlight)}}}}else{let n=[];if(this.annotator&&(n=await this.annotator.getAnnotations()),this.navigator.highlighter&&n&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.navigator.highlighter.destroyHighlights(it.Annotation);for(let i of n){tn.push(i.highlight);let o=i,a=this.navigator.currentChapterLink.href,l=this.publication.getTOCItem(a);if(this.navigator.currentTocUrl&&(l=this.publication.getTOCItem(this.navigator.currentTocUrl)),l===void 0&&(l=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),l){let u=l.Href;u.indexOf("#")>0&&(u=u.slice(0,u.indexOf("#"))),o.href===u&&await this.navigator.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,i.highlight)}}}}}async deleteSelectedHighlight(t){this.api?.deleteBookmark?this.api.deleteBookmark(t).then(async()=>{this.deleteLocalHighlight(t.id)}):this.deleteLocalHighlight(t.id)}async deleteLocalHighlight(t){if(this.annotator){var n=await this.annotator.deleteAnnotation(t);return $i.default.log("Highlight deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),n}else return new Promise(i=>i(null))}createTree(t,n,i){if(n){let o=this,a=this.publication.readingOrder;if(a.length){let l=(u,d)=>{let h=document.createElement("ul");h.className="sidenav-annotations";for(let y of d){let b=document.createElement("li"),w=document.createElement("a"),p=document.createElement("span");if(w.tabIndex=-1,w.className="chapter-link",y.Href){let f=this.publication.getAbsoluteHref(y.Href),g=this.publication.getTOCItemAbsolute(f);w.href=f,w.innerHTML=g?.Title||"",b.appendChild(w)}else p.innerHTML=y.Title||"",p.className="chapter-title",b.appendChild(p);Ee(w,"click",f=>{f.preventDefault(),f.stopPropagation();let g={href:w.href,locations:{progression:0},type:y.TypeLink,title:w.title};this.navigator.stopReadAloud(),this.navigator.navigate(g)});let m=document.createElement("ol");n.forEach(function(f){let g=y.Href.indexOf("#")!==-1?y.Href.slice(0,y.Href.indexOf("#")):y.Href;if(y.Href&&f.href.endsWith(g)){let v=document.createElement("li");v.className="annotation-item";let A=document.createElement("a");if(A.setAttribute("href",f.href),t===Si.Bookmark){A.className="bookmark-link";let O=document.createElement("span"),E=Math.round((f.locations.progression??0)*100)+"% through resource";O.className="title",O.innerHTML=E,A.appendChild(O)}let C=document.createElement("span");if(C.className="timestamp",C.innerHTML=ds.readableTimestamp(f.created),A.appendChild(C),Ee(A,"click",O=>{O.preventDefault(),O.stopPropagation(),o.handleAnnotationLinkClick(O,f)}),v.appendChild(A),o.navigator.sideNavExpanded){let O=document.createElement("button");O.className="delete",O.innerHTML=nr.delete,Ee(O,"click",E=>{E.preventDefault(),E.stopPropagation(),o.handleAnnotationLinkDeleteClick(t,E,f)}),v.appendChild(O)}m.appendChild(v)}}),m.children.length>0&&(h.appendChild(b),h.appendChild(m)),h.children.length>0&&u.appendChild(h),y.Children&&y.Children.length>0&&l(u,y.Children)}};i.innerHTML="",l(i,a)}}}handleAnnotationLinkClick(t,n){n?(n.href=this.publication.getAbsoluteHref(n.href),this.navigator.stopReadAloud(),this.navigator.navigate(n)):$i.default.log("bookmark data missing: ",t)}handleAnnotationLinkDeleteClick(t,n,i){$i.default.log("bookmark data locator: ",i),i?t===Si.Bookmark&&this.deleteBookmark(i):$i.default.log("bookmark data missing: ",n)}static readableTimestamp(t){let n=new Date(t);return n.toDateString()+" "+n.toLocaleTimeString()}async getAnnotation(t){return this.annotator?.getAnnotation(t)}async getAnnotationByID(t){return this.annotator?.getAnnotationByID(t)}};H();var tS=nt(eS());H();var ii=nt(Jt()),Z0="r2-mo-active",fs=class{},Xe=fs;Xe.COLOR_REF="color",Xe.AUTO_SCROLL_REF="autoscroll",Xe.AUTO_TURN_REF="autoturn",Xe.VOLUME_REF="volume",Xe.RATE_REF="rate",Xe.COLOR_KEY="mediaoverlay-"+fs.COLOR_REF,Xe.AUTO_SCROLL_KEY="mediaoverlay-"+fs.AUTO_SCROLL_REF,Xe.AUTO_TURN_KEY="mediaoverlay-"+fs.AUTO_TURN_REF,Xe.VOLUME_KEY="mediaoverlay-"+fs.VOLUME_REF,Xe.RATE_KEY="mediaoverlay-"+fs.RATE_REF;var Q0=class{constructor(t,n,i){this.MEDIAOVERLAYSETTINGS="mediaOverlaySetting";this.color="r2-mo-active";this.autoScroll=!0;this.autoTurn=!0;this.volume=1;this.rate=1;this.playing=!1;this.resourceReady=!1;this.wait=1;this.settingsChangeCallback=()=>{};this.store=t,this.api=n,this.headerMenu=i,this.initialise(),ii.default.log(this.api)}static create(t){let n=new this(t.store,t.api,t.headerMenu);if(t.initialMediaOverlaySettings){let i=t.initialMediaOverlaySettings;i?.color&&(n.color=i.color,ii.default.log(n.color)),i?.autoScroll&&(n.autoScroll=i.autoScroll,ii.default.log(n.autoScroll)),i?.autoTurn&&(n.autoTurn=i.autoTurn,ii.default.log(n.autoScroll)),i?.volume&&(n.volume=i.volume,ii.default.log(n.volume)),i?.rate&&(n.rate=i.rate,ii.default.log(n.rate)),i?.wait&&(n.wait=i.wait,ii.default.log(n.wait))}return n.initializeSelections(),n}stop(){ii.default.log("MediaOverlay settings stop")}initialise(){this.autoScroll=this.getProperty(Xe.AUTO_SCROLL_KEY)!=null?this.getProperty(Xe.AUTO_SCROLL_KEY).value:this.autoScroll,this.autoTurn=this.getProperty(Xe.AUTO_TURN_KEY)!=null?this.getProperty(Xe.AUTO_TURN_KEY).value:this.autoTurn,this.color=this.getProperty(Xe.COLOR_KEY)!=null?this.getProperty(Xe.COLOR_KEY).value:this.color,this.volume=this.getProperty(Xe.VOLUME_KEY)!=null?this.getProperty(Xe.VOLUME_KEY).value:this.volume,this.rate=this.getProperty(Xe.RATE_KEY)!=null?this.getProperty(Xe.RATE_KEY).value:this.rate,this.userProperties=this.getMediaOverlaySettings()}reset(){this.color="redtext",this.autoScroll=!0,this.autoTurn=!0,this.volume=1,this.rate=1,this.wait=1,this.userProperties=this.getMediaOverlaySettings()}initializeSelections(){this.headerMenu&&(this.settingsView=Ie(this.headerMenu,"#container-view-mediaoverlay-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(t){this.headerMenu&&(this.speechAutoTurn=Ie(this.headerMenu,"#mediaOverlayAutoTurn")),this.headerMenu&&(this.speechAutoScroll=Ie(this.headerMenu,"#mediaOverlayAutoScroll")),this.headerMenu&&(this.speechVolume=Ie(this.headerMenu,"#mediaOverlayVolume")),this.headerMenu&&(this.speechRate=Ie(this.headerMenu,"#mediaOverlayRate")),this.speechAutoScroll&&(this.speechAutoScroll.checked=this.autoScroll),this.speechAutoTurn&&(this.speechAutoTurn.checked=this.autoTurn),this.speechVolume&&(this.speechVolume.value=this.volume.toString()),this.speechRate&&(this.speechRate.value=this.volume.toString()),Ee(Ie(t,"ul"),"click",n=>{n.stopPropagation()})}onSettingsChange(t){this.settingsChangeCallback=t}storeProperty(t){this.updateUserSettings(),this.saveProperty(t)}updateUserSettings(){let t={color:this.userProperties.getByRef(Xe.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(Xe.AUTO_SCROLL_REF)?.value,autoTurn:this.userProperties.getByRef(Xe.AUTO_TURN_REF)?.value,volume:this.userProperties.getByRef(Xe.VOLUME_REF)?.value,rate:this.userProperties.getByRef(Xe.RATE_REF)?.value};this.applyMediaOverlaySettings(t),this.api?.updateSettings&&this.api?.updateSettings(t).then(async n=>{ii.default.log("api updated sync settings",n)})}getMediaOverlaySettings(){let t=new Wr;return t.addSwitchable("mediaoverlay-auto-scroll-off","mediaoverlay-auto-scroll-on",this.autoScroll,Xe.AUTO_SCROLL_REF,Xe.AUTO_SCROLL_KEY),t.addSwitchable("mediaoverlay-auto-turn-off","mediaoverlay-auto-turn-on",this.autoTurn,Xe.AUTO_TURN_REF,Xe.AUTO_TURN_KEY),t.addStringable(this.color,Xe.COLOR_REF,Xe.COLOR_KEY),t.addIncremental(this.volume,.1,1,.1,"",Xe.VOLUME_REF,Xe.VOLUME_KEY),t.addIncremental(this.rate,.1,3,.1,"",Xe.RATE_REF,Xe.RATE_KEY),t}saveProperty(t){let n=this.store.get(this.MEDIAOVERLAYSETTINGS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.name!==t.name),i.push(t),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(i))}return t}getProperty(t){let n=this.store.get(this.MEDIAOVERLAYSETTINGS);if(n){let i=JSON.parse(n);return i=i.filter(o=>o.name===t),i.length===0?null:i[0]}return null}resetMediaOverlaySettings(){this.store.remove(this.MEDIAOVERLAYSETTINGS),this.reset(),this.settingsChangeCallback()}applyMediaOverlaySettings(t){if(t.color){this.color=t.color;let n=this.userProperties.getByRef(Xe.COLOR_REF);n&&(n.value=this.color,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoScroll!==void 0){ii.default.log("autoScroll "+this.autoScroll),this.autoScroll=t.autoScroll;let n=this.userProperties.getByRef(Xe.AUTO_SCROLL_REF);n&&(n.value=this.autoScroll,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoTurn!==void 0){ii.default.log("autoTurn "+this.autoTurn),this.autoTurn=t.autoTurn;let n=this.userProperties.getByRef(Xe.AUTO_TURN_REF);n&&(n.value=this.autoTurn,this.saveProperty(n)),this.settingsChangeCallback()}if(t.volume){ii.default.log("volume "+this.volume),this.volume=t.volume;let n=this.userProperties.getByRef(Xe.VOLUME_REF);n&&(n.value=this.volume,this.saveProperty(n)),this.settingsChangeCallback()}if(t.rate){ii.default.log("rate "+this.rate),this.rate=t.rate;let n=this.userProperties.getByRef(Xe.RATE_REF);n&&(n.value=this.rate,this.saveProperty(n)),this.settingsChangeCallback()}}applyMediaOverlaySetting(t,n){if(t===Xe.COLOR_REF){this.color=n;let i=this.userProperties.getByRef(Xe.COLOR_REF);i&&(i.value=this.color,this.saveProperty(i)),this.settingsChangeCallback()}else if(t===Xe.AUTO_SCROLL_REF){this.autoScroll=n;let i=this.userProperties.getByRef(Xe.AUTO_SCROLL_REF);i&&(i.value=this.autoScroll,this.saveProperty(i)),this.settingsChangeCallback()}else if(t===Xe.AUTO_TURN_REF){this.autoTurn=n;let i=this.userProperties.getByRef(Xe.AUTO_TURN_REF);i&&(i.value=this.autoTurn,this.saveProperty(i)),this.settingsChangeCallback()}}increase(t){if(t==="mo_volume"){this.userProperties.getByRef(Xe.VOLUME_REF).increment(),this.volume=this.userProperties.getByRef(Xe.VOLUME_REF)?.value;let n=this.userProperties.getByRef(Xe.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}else if(t==="mo_rate"){this.userProperties.getByRef(Xe.RATE_REF).increment(),this.rate=this.userProperties.getByRef(Xe.RATE_REF)?.value;let n=this.userProperties.getByRef(Xe.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}}decrease(t){if(t==="mo_volume"){this.userProperties.getByRef(Xe.VOLUME_REF).decrement(),this.volume=this.userProperties.getByRef(Xe.VOLUME_REF)?.value;let n=this.userProperties.getByRef(Xe.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}else if(t==="mo_rate"){this.userProperties.getByRef(Xe.RATE_REF).decrement(),this.rate=this.userProperties.getByRef(Xe.RATE_REF)?.value;let n=this.userProperties.getByRef(Xe.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}}};var Ze=nt(Jt()),Ol=class{constructor(t,n,i){this.play=Ie(document,"#menu-button-play");this.pause=Ie(document,"#menu-button-pause");this.currentLinkIndex=0;this.pid=void 0;this.__ontimeupdate=!1;this.ontimeupdate=async t=>{Ze.default.log("ontimeupdate"),this.trackCurrentTime()};this.ensureOnTimeUpdate=(t,n)=>{t?this.__ontimeupdate&&(this.__ontimeupdate=!1,this.audioElement&&this.audioElement.removeEventListener("timeupdate",this.ontimeupdate),cancelAnimationFrame(this.myReq)):(!this.__ontimeupdate||n)&&(this.__ontimeupdate=!0,n&&(this.audioElement&&this.audioElement.removeEventListener("timeupdate",this.ontimeupdate),this.audioElement.addEventListener("timeupdate",this.ontimeupdate)))};this.publication=t,this.settings=n,this.properties=i}static create(t){let n=new this(t.publication,t.settings,t);return n.start(),n}stop(){Ze.default.log("MediaOverlay module stop")}start(){Ze.default.log("MediaOverlay module start")}async initialize(){return new Promise(async t=>{await document.fonts.ready,this.settings.setControls(),this.settings.onSettingsChange(()=>{this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate}),t()})}async initializeResource(t){this.currentLinks=t,this.currentLinkIndex=0,await this.playLink()}async playLink(){let t=this.currentLinks[this.currentLinkIndex];if(t?.Properties?.MediaOverlay){this.ensureOnTimeUpdate(!1,!1);let n=t.Properties?.MediaOverlay,o=new URL(n,this.publication.manifestUrl).toString(),a;try{a=await fetch(o,this.navigator.requestConfig)}catch(h){console.error(h,o);return}a.ok||Ze.default.log("BAD RESPONSE?!");let l;try{l=await a.json()}catch(h){console.error(h)}if(!l){Ze.default.log("## moJson"+l);return}t.MediaOverlays=Ks(l,tS.MediaOverlayNode),t.MediaOverlays.initialized=!0;let u=t.HrefDecoded||t.Href,d=new URL("https://dita.digital/"+u);await this.playMediaOverlays(d.pathname.substr(1),t.MediaOverlays,void 0)}else this.audioElement&&await this.audioElement.pause(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement&&await this.audioElement.pause(),this.navigator.nextResource()):await this.stopReadAloud()}async startReadAloud(){if(this.navigator.rights.enableMediaOverlays){if(this.settings.playing=!0,this.audioElement&&this.currentLinks[this.currentLinkIndex]?.Properties.MediaOverlay){let t=this.currentAudioBegin?this.currentAudioBegin:0;this.audioElement.currentTime=t,await this.audioElement.play(),this.ensureOnTimeUpdate(!1,!0),this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate}else this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?this.navigator.nextResource():await this.stopReadAloud();this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display")}}async stopReadAloud(){this.navigator.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement&&this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}pauseReadAloud(){this.navigator.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}async resumeReadAloud(){this.navigator.rights.enableMediaOverlays&&(this.settings.playing=!0,await this.audioElement.play(),this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display"))}findDepthFirstTextAudioPair(t,n,i){Ze.default.log("findDepthFirstTextAudioPair()");let o,a;if(n.Text){let d=new URL("https://dita.digital/"+n.Text);if(d.pathname.substr(1)===t){if(o=!0,d.hash&&i){a=!1;let h=d.hash.substr(1);for(let y of i)if(y===h){a=!0;break}}}else o=!1}if(Ze.default.log("isFragmentIDMatch: "+a),Ze.default.log("isTextUrlMatch: "+o),!n.Children||!n.Children.length){if(Ze.default.log("findDepthFirstTextAudioPair() - leaf text/audio pair"),!o){Ze.default.log("findDepthFirstTextAudioPair() - leaf - !isTextUrlMatch");return}return a||o&&!i?(Ze.default.log("findDepthFirstTextAudioPair() - leaf - isFragmentIDMatch || (isTextUrlMatch && !textFragmentIDChain"),n):void 0}let l=i,u=i;for(let d of n.Children){Ze.default.log("findDepthFirstTextAudioPair() - child"),Ze.default.log(JSON.stringify(d));let h=this.findDepthFirstTextAudioPair(t,d,u);if(h===null&&(Ze.default.log("findDepthFirstTextAudioPair() - child - match null (skip)"),u=void 0),h)return Ze.default.log("findDepthFirstTextAudioPair() - child - match"),Ze.default.log(JSON.stringify(h)),h}if(a){Ze.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch");let d=this.findDepthFirstTextAudioPair(t,n,void 0);return d&&(Ze.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch - match"),Ze.default.log(JSON.stringify(d)),d)}if(l&&!u)return null}trackCurrentTime(){if(cancelAnimationFrame(this.myReq),this.mediaOverlayTextAudioPair)try{this.currentAudioEnd&&this.audioElement.currentTime>=this.currentAudioEnd-.05&&(Ze.default.log("ontimeupdate - mediaOverlaysNext()"),this.mediaOverlaysNext());let t=this.mediaOverlayTextAudioPair.Text.lastIndexOf("#"),n=this.mediaOverlayTextAudioPair.Text.substr(t+1);this.mediaOverlayHighlight(n),this.myReq=requestAnimationFrame(this.trackCurrentTime.bind(this))}catch(t){}}mediaOverlaysNext(t){if(Ze.default.log("mediaOverlaysNext()"),this.mediaOverlayRoot&&this.mediaOverlayTextAudioPair){let n=this.findNextTextAudioPair(this.mediaOverlayRoot,this.mediaOverlayTextAudioPair,{prev:void 0},!!t);if(!n)Ze.default.log("mediaOverlaysNext() - navLeftOrRight()"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.navigator.nextResource()):this.stopReadAloud());else{let i=!1;if(this.mediaOverlayTextAudioPair.Text&&n.Text){let o=new URL("https://dita.digital/"+this.mediaOverlayTextAudioPair.Text),a=new URL("https://dita.digital/"+n.Text);o.pathname!==a.pathname&&(Ze.default.log("mediaOverlaysNext() SWITCH! "+o.pathname+" != "+a.pathname),i=!0)}i?this.mediaOverlaysStop():(Ze.default.log("mediaOverlaysNext() - playMediaOverlaysAudio()"),setTimeout(async()=>{await this.playMediaOverlaysAudio(n,void 0,void 0)},0))}}else Ze.default.log("mediaOverlaysNext() - navLeftOrRight() 2"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.navigator.nextResource()):this.stopReadAloud())}mediaOverlaysStop(){Ze.default.log("mediaOverlaysStop()"),this.mediaOverlaysPause(),this.mediaOverlayRoot=void 0,this.mediaOverlayTextAudioPair=void 0}mediaOverlaysPause(){Ze.default.log("mediaOverlaysPause()"),this.mediaOverlayHighlight(void 0),this.audioElement&&this.audioElement.pause()}findNextTextAudioPair(t,n,i,o){if(!t.Children||!t.Children.length){if(i?.prev===n)return Ze.default.log("findNextTextAudioPair() - prevMo === moToMatch"),t;Ze.default.log("findNextTextAudioPair() - set previous"),Ze.default.log(JSON.stringify(t)),i.prev=t;return}for(let a of t.Children){Ze.default.log("findNextTextAudioPair() - child"),Ze.default.log(JSON.stringify(a));let l=this.findNextTextAudioPair(a,n,i,o);if(l)return Ze.default.log("findNextTextAudioPair() - match"),Ze.default.log(JSON.stringify(l)),l}}async playMediaOverlaysAudio(t,n,i){if(Ze.default.log("playMediaOverlaysAudio()"),this.mediaOverlayTextAudioPair=t,!t.Audio)return;let o=new URL(t.Audio,this.publication.manifestUrl),a=o.toString(),l=new URL(a);l.hash="",l.search="";let u=l.toString(),d=typeof n!="undefined",h=typeof i!="undefined";if(this.previousAudioEnd=this.currentAudioEnd,this.currentAudioBegin=void 0,this.currentAudioEnd=void 0,!d&&!h){if(o.hash){let b=o.hash.match(/t=([0-9.]+)(,([0-9.]+))?/);if(b&&b.length>=1){let w=b[1];try{this.currentAudioBegin=parseFloat(w)}catch(p){Ze.default.error(p)}if(b.length>=3){let p=b[3];try{this.currentAudioEnd=parseFloat(p)}catch(m){Ze.default.error(m)}}}}}else this.currentAudioBegin=n,this.currentAudioEnd=i;Ze.default.log(`${a} => [${this.currentAudioBegin}-${this.currentAudioEnd}]`);let y=async b=>{if(!this.audioElement)return;let w=this.currentAudioBegin?this.currentAudioBegin:0;if(b||this.audioElement.paused)if(b&&!w||this.audioElement.currentTime===w){if(Ze.default.log("playMediaOverlaysAudio() - playClip() - _currentAudioElement.play()"),this.ensureOnTimeUpdate(!1,!1),this.audioElement.playbackRate=this.settings.rate,this.audioElement.volume=this.settings.volume,this.settings.playing){let m=function(){p.settings.resourceReady?setTimeout(async()=>{await p.audioElement.play(),p.ensureOnTimeUpdate(!1,!0)},p.settings.wait*1e3):setTimeout(m,200)},p=this;m()}}else{Ze.default.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked");let p=async m=>{if(this.audioElement.removeEventListener("timeupdate",p),Ze.default.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked - .play()"),this.ensureOnTimeUpdate(!1,!1),this.audioElement&&(this.audioElement.playbackRate=this.settings.rate,this.audioElement.volume=this.settings.volume,this.settings.playing)){let g=function(){f.settings.resourceReady?setTimeout(async()=>{await f.audioElement.play(),f.ensureOnTimeUpdate(!1,!0)},f.settings.wait*1e3):setTimeout(g,200)},f=this;g()}};this.audioElement.addEventListener("timeupdate",p),this.audioElement.currentTime=w}else{let p=this.previousAudioUrl===this.currentAudioUrl&&typeof this.previousAudioEnd!="undefined"&&this.previousAudioEnd>w-.02&&this.previousAudioEnd<=w&&this.audioElement.currentTime>=w-.1;this.ensureOnTimeUpdate(!1,!1),p?Ze.default.log("playMediaOverlaysAudio() - playClip() - ensureOnTimeUpdate"):(Ze.default.log("playMediaOverlaysAudio() - playClip() - currentTime = timeToSeekTo"),this.audioElement.currentTime=w)}};if(this.previousAudioUrl=this.currentAudioUrl,!this.currentAudioUrl||u!==this.currentAudioUrl){this.currentAudioUrl=u,Ze.default.log("playMediaOverlaysAudio() - RESET: "+this.previousAudioUrl+" => "+this.currentAudioUrl),this.audioElement=document.getElementById("AUDIO_MO_ID"),this.audioElement&&(this.audioElement.pause(),this.audioElement.setAttribute("src",""),this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement)),this.audioElement=document.createElement("audio"),this.audioElement.setAttribute("style","display: none"),this.audioElement.setAttribute("id","AUDIO_MO_ID"),this.audioElement.setAttribute("role","media-overlays"),this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate,document.body.appendChild(this.audioElement),this.audioElement.addEventListener("error",p=>{Ze.default.log("-1) error: "+(this.currentAudioUrl!==p.currentTarget.src?this.currentAudioUrl+" -- ":"")+p.currentTarget.src.substr(p.currentTarget.src.lastIndexOf("/"))),this.audioElement&&this.audioElement.error&&(Ze.default.log(this.audioElement.error.code),Ze.default.log(this.audioElement.error.message))});let b=async p=>{p.currentTarget.removeEventListener("canplaythrough",b),Ze.default.log("oncanplaythrough"),await y(!0)};this.audioElement.addEventListener("canplaythrough",b);let w=async p=>{Ze.default.log("onended"),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.navigator.nextResource()):this.stopReadAloud()};this.audioElement.addEventListener("ended",w),this.audioElement.playbackRate=this.settings.rate,this.audioElement.setAttribute("src",this.currentAudioUrl)}else Ze.default.log("playMediaOverlaysAudio() - playClip()"),await y(!1)}async playMediaOverlays(t,n,i){Ze.default.log("playMediaOverlays()");let o=i?i.filter(l=>l):void 0;o&&o.length===0&&(o=void 0);let a=this.findDepthFirstTextAudioPair(t,n,o);!a&&o&&(Ze.default.log("playMediaOverlays() - findDepthFirstTextAudioPair() SECOND CHANCE "),Ze.default.log(JSON.stringify(o,null,4)),Ze.default.log(JSON.stringify(n,null,4)),a=this.findDepthFirstTextAudioPair(t,n,void 0)),a?a.Audio&&(Ze.default.log("playMediaOverlays() - playMediaOverlaysAudio()"),this.mediaOverlayRoot=n,await this.playMediaOverlaysAudio(a,void 0,void 0)):Ze.default.log("playMediaOverlays() - !moTextAudioPair "+t)}mediaOverlayHighlight(t){Ze.default.log("moHighlight: ## "+t);let n=this.publication.Metadata?.MediaOverlay?.ActiveClass;n||(n=this.settings.color);let i=this.navigator.iframes[0].contentDocument?.documentElement.getAttribute("style"),o=i?i.indexOf("readium-night-on")>0:!1,a=i?i.indexOf("readium-sepia-on")>0:!1;if((this.publication.Metadata.Rendition?.Layout??"unknown")!=="fixed"&&(n=o||a?Z0:n||Z0),this.pid){let u;this.currentLinkIndex===0?u=this.navigator.iframes[0].contentDocument?.getElementById(this.pid):u=this.navigator.iframes[1].contentDocument?.getElementById(this.pid),u&&u.classList.remove(n)}let l;t&&(this.currentLinkIndex===0?l=this.navigator.iframes[0].contentDocument?.getElementById(t):l=this.navigator.iframes[1].contentDocument?.getElementById(t),l&&l.classList.add(n),this.pid=t),l&&(this.publication.Metadata.Rendition?.Layout??"unknown")!=="fixed"&&l.scrollIntoView({block:"center",behavior:"smooth"})}};H();var eg=nt(Jt()),Rl=class{static async create(t){let n=new this(t.publication);return await n.start(),n}constructor(t){this.publication=t}async stop(){eg.default.log("Timeline module stop")}async start(){this.timelineContainer=Ie(document,"#container-view-timeline"),this.positionSlider=Ie(document,"#positionSlider"),this.publication.positions?this.positionSlider&&(this.positionSlider.style.display="block"):this.positionSlider&&(this.positionSlider.style.display="none")}async initialize(){return new Promise(async t=>{await document.fonts.ready;let n=this.navigator.currentLocator();(this.navigator.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions)&&(this.positionSlider&&(this.positionSlider.value=(n.locations.position??0).toString()),this.positionSlider&&(this.positionSlider.max=((n.locations.totalRemainingPositions??0)+(n.locations.position??0)).toString())),this.timelineContainer&&(this.timelineContainer.innerHTML=""),this.publication.readingOrder?.forEach(i=>{let o=this.publication.getAbsoluteHref(i.Href),a=this.publication.getTOCItemAbsolute(o),l=a?.Href.indexOf("#")!==-1?a?.Href.slice(0,a?.Href.indexOf("#")):a.Href,u=this.publication.getAbsoluteHref(l??"");var d;this.publication.positions&&this.navigator.view?.layout!=="fixed"?i.contentWeight?d=i.contentWeight:d=1:d=100/(this.publication.readingOrder?.length??0);var h=document.createElement("div");if(h.style.height=d+"%",h.style.width="100%",h.className="chapter",a?.Title!==void 0){var y=document.createElement("span");y.innerHTML=a.Title,y.className="chapter-tooltip",h.appendChild(y)}Ee(h,"click",b=>{b.preventDefault(),b.stopPropagation();var w;this.publication.positions||this.navigator.rights.autoGeneratePositions&&this.publication.positions?(w=et({},this.publication.positions.filter(p=>p.href===i.Href)[0]),w.href=this.publication.getAbsoluteHref(w.href)):w={href:u,locations:{progression:0},type:i.TypeLink,title:i.Title},eg.default.log(w),this.navigator.navigate(w)}),u===this.navigator.currentChapterLink.href?h.className+=" active":h.className=h.className.replace(" active",""),this.timelineContainer&&this.timelineContainer.appendChild(h)}),t()})}};H();var wg=nt(So());H();var nS=nt(Jt());function iS(r,t){return new Promise(function(n){setTimeout(n.bind(null,t),r)})}var a8=!1;nS.default.setLevel(a8?"trace":"warn",!0);var LA=nt(MA()),hh=nt(kA()),On=nt(Jt());var ya=class{constructor(t){this.hasEventListener=!1;this.isHacked=!1;this.properties=t}static async setupPreloadProtection(t){if(this.isCurrentBrowserSupported(t))t.detectInspect&&await this.startInspectorProtection(t);else throw new Error("Browser not supported")}static async create(t){let n=new this(t);return await n.start(),n}static async startInspectorProtection(t){(0,hh.addListener)(i=>{i&&(t.clearOnInspect&&(console.clear(),window.localStorage.clear(),window.sessionStorage.clear(),window.location.replace(window.location.origin)),t.detectInspect&&typeof t.api?.inspectDetected=="function"&&t.api.inspectDetected())}),(0,hh.launch)(),await iS(t.detectInspectInitDelay??100)}static isCurrentBrowserSupported(t){if(!t.enforceSupportedBrowsers)return!0;let n=[];return(t.supportedBrowsers??[]).forEach(o=>{n.push("last 1 "+o+" version")}),(0,LA.getUserAgentRegExp)({browsers:n,allowHigherVersions:!0}).test(navigator.userAgent)}async start(){if(this.properties?.enableObfuscation){this.wrapper=mt(document,"#iframe-wrapper"),this.securityContainer=Ie(document,"#container-view-security");var t=this;this.mutationObserver=new MutationObserver(function(n){n.forEach(function(i){On.default.log(i.type),t.isHacked=!0})})}}async stop(){if(On.default.log("Protection module stop"),this.properties?.enableObfuscation&&this.mutationObserver.disconnect(),this.properties?.disableKeys){je(this.navigator.mainElement,"keydown",this.disableSave),je(this.navigator.headerMenu,"keydown",this.disableSave);for(let t of this.navigator.iframes)je(t.contentDocument,"keydown",this.disableSave),je(t.contentWindow,"keydown",this.disableSave);je(window,"keydown",this.disableSave),je(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){je(this.navigator.mainElement,"copy",this.preventCopy),je(this.navigator.headerMenu,"copy",this.preventCopy);for(let t of this.navigator.iframes)je(t.contentDocument,"copy",this.preventCopy),je(t.contentWindow,"copy",this.preventCopy);je(window,"copy",this.preventCopy),je(document,"copy",this.preventCopy),je(this.navigator.mainElement,"cut",this.preventCopy),je(this.navigator.headerMenu,"cut",this.preventCopy);for(let t of this.navigator.iframes)je(t.contentDocument,"cut",this.preventCopy),je(t.contentWindow,"cut",this.preventCopy);je(window,"cut",this.preventCopy),je(document,"cut",this.preventCopy),je(this.navigator.mainElement,"keydown",this.preventCopyKey),je(this.navigator.headerMenu,"keydown",this.preventCopyKey);for(let t of this.navigator.iframes)je(t.contentDocument,"keydown",this.preventCopyKey),je(t.contentWindow,"keydown",this.preventCopyKey);je(window,"keydown",this.preventCopyKey),je(document,"keydown",this.preventCopyKey)}else if(this.properties?.canCopy){je(this.navigator.mainElement,"copy",this.restrictCopy),je(this.navigator.headerMenu,"copy",this.restrictCopy);for(let t of this.navigator.iframes)je(t.contentDocument,"copy",this.restrictCopy),je(t.contentWindow,"copy",this.restrictCopy);je(window,"copy",this.restrictCopy),je(document,"copy",this.restrictCopy),je(this.navigator.mainElement,"cut",this.restrictCopy),je(this.navigator.headerMenu,"cut",this.restrictCopy);for(let t of this.navigator.iframes)je(t.contentDocument,"cut",this.restrictCopy),je(t.contentWindow,"cut",this.restrictCopy);je(window,"cut",this.restrictCopy),je(document,"cut",this.restrictCopy),je(this.navigator.mainElement,"keydown",this.restrictCopyKey),je(this.navigator.headerMenu,"keydown",this.restrictCopyKey);for(let t of this.navigator.iframes)je(t.contentDocument,"keydown",this.restrictCopyKey),je(t.contentWindow,"keydown",this.restrictCopyKey);je(window,"keydown",this.restrictCopyKey),je(document,"keydown",this.restrictCopyKey)}if(this.properties?.disablePrint){je(this.navigator.mainElement,"beforeprint",this.beforePrint.bind(this)),je(this.navigator.headerMenu,"beforeprint",this.beforePrint.bind(this));for(let t of this.navigator.iframes)je(t.contentDocument,"beforeprint",this.beforePrint),je(t.contentWindow,"beforeprint",this.beforePrint);je(window,"beforeprint",this.beforePrint),je(document,"beforeprint",this.beforePrint),je(this.navigator.mainElement,"afterprint",this.afterPrint.bind(this)),je(this.navigator.headerMenu,"afterprint",this.afterPrint.bind(this));for(let t of this.navigator.iframes)je(t.contentDocument,"afterprint",this.afterPrint.bind(this)),je(t.contentWindow,"afterprint",this.afterPrint.bind(this));je(window,"afterprint",this.afterPrint.bind(this)),je(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){je(this.navigator.mainElement,"contextmenu",this.disableContext),je(this.navigator.headerMenu,"contextmenu",this.disableContext);for(let t of this.navigator.iframes)je(t.contentDocument,"contextmenu",this.disableContext),je(t.contentWindow,"contextmenu",this.disableContext);je(window,"contextmenu",this.disableContext),je(document,"contextmenu",this.disableContext)}this.properties?.hideTargetUrl&&this.hideTargetUrls(!1),this.properties?.disableDrag&&this.preventDrag(!1),je(this.wrapper,"scroll",this.handleScroll.bind(this))}observe(){if(this.properties?.enableObfuscation){this.securityContainer.hasAttribute("style")&&(this.isHacked=!0),this.mutationObserver.disconnect();var t={attributes:!0,childList:!0,characterData:!0};this.mutationObserver.observe(this.securityContainer,t)}}async deactivate(){this.properties?.enableObfuscation&&(this.observe(),this.rects.forEach(t=>this.deactivateRect(t,this.securityContainer,this.isHacked)))}async activate(){if(this.properties?.enableObfuscation){this.observe();for(let t of this.navigator.iframes)if(t.contentDocument){let n=Gr(t.contentDocument,"body");this.rects=this.findRects(n),this.rects.forEach(i=>this.toggleRect(i,this.securityContainer,this.isHacked))}}}setupEvents(){if(this.properties?.disableKeys){Ee(this.navigator.mainElement,"keydown",this.disableSave),Ee(this.navigator.headerMenu,"keydown",this.disableSave);for(let t of this.navigator.iframes)Ee(t,"keydown",this.disableSave),Ee(t.ownerDocument,"keydown",this.disableSave),Ee(t.contentDocument,"keydown",this.disableSave),Ee(t.contentWindow,"keydown",this.disableSave),Ee(t.contentWindow?.document,"keydown",this.disableSave);Ee(window,"keydown",this.disableSave),Ee(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){Ee(this.navigator.mainElement,"copy",this.preventCopy),Ee(this.navigator.headerMenu,"copy",this.preventCopy);for(let t of this.navigator.iframes)Ee(t,"copy",this.preventCopy),Ee(t.ownerDocument,"copy",this.preventCopy),Ee(t.contentDocument,"copy",this.preventCopy),Ee(t.contentWindow,"copy",this.preventCopy),Ee(t.contentWindow?.document,"copy",this.preventCopy);Ee(window,"copy",this.preventCopy),Ee(document,"copy",this.preventCopy),Ee(this.navigator.mainElement,"cut",this.preventCopy),Ee(this.navigator.headerMenu,"cut",this.preventCopy);for(let t of this.navigator.iframes)Ee(t,"cut",this.preventCopy),Ee(t.ownerDocument,"cut",this.preventCopy),Ee(t.contentDocument,"cut",this.preventCopy),Ee(t.contentWindow,"cut",this.preventCopy),Ee(t.contentWindow?.document,"cut",this.preventCopy);Ee(window,"cut",this.preventCopy),Ee(document,"cut",this.preventCopy),Ee(this.navigator.mainElement,"keydown",this.preventCopyKey),Ee(this.navigator.headerMenu,"keydown",this.preventCopyKey);for(let t of this.navigator.iframes)Ee(t,"keydown",this.preventCopyKey),Ee(t.ownerDocument,"keydown",this.preventCopyKey),Ee(t.contentDocument,"keydown",this.preventCopyKey),Ee(t.contentWindow,"keydown",this.preventCopyKey),Ee(t.contentWindow?.document,"keydown",this.preventCopyKey);Ee(window,"keydown",this.preventCopyKey),Ee(document,"keydown",this.preventCopyKey)}else if(this.properties?.canCopy){Ee(this.navigator.mainElement,"copy",this.restrictCopy.bind(this)),Ee(this.navigator.headerMenu,"copy",this.restrictCopy.bind(this));for(let t of this.navigator.iframes)Ee(t,"copy",this.restrictCopy),Ee(t.ownerDocument,"copy",this.restrictCopy.bind(this)),Ee(t.contentDocument,"copy",this.restrictCopy.bind(this)),Ee(t.contentWindow,"copy",this.restrictCopy.bind(this)),Ee(t.contentWindow?.document,"copy",this.restrictCopy.bind(this));Ee(window,"copy",this.restrictCopy.bind(this)),Ee(document,"copy",this.restrictCopy.bind(this)),Ee(this.navigator.mainElement,"cut",this.restrictCopy.bind(this)),Ee(this.navigator.headerMenu,"cut",this.restrictCopy.bind(this));for(let t of this.navigator.iframes)Ee(t,"cut",this.restrictCopy.bind(this)),Ee(t.ownerDocument,"cut",this.restrictCopy.bind(this)),Ee(t.contentDocument,"cut",this.restrictCopy.bind(this)),Ee(t.contentWindow,"cut",this.restrictCopy.bind(this)),Ee(t.contentWindow?.document,"cut",this.restrictCopy.bind(this));Ee(window,"cut",this.restrictCopy.bind(this)),Ee(document,"cut",this.restrictCopy.bind(this)),Ee(this.navigator.mainElement,"keydown",this.restrictCopyKey.bind(this)),Ee(this.navigator.headerMenu,"keydown",this.restrictCopyKey.bind(this));for(let t of this.navigator.iframes)Ee(t,"keydown",this.restrictCopyKey.bind(this)),Ee(t.ownerDocument,"keydown",this.restrictCopyKey.bind(this)),Ee(t.contentDocument,"keydown",this.restrictCopyKey.bind(this)),Ee(t.contentWindow,"keydown",this.restrictCopyKey.bind(this)),Ee(t.contentWindow?.document,"keydown",this.restrictCopyKey.bind(this));Ee(window,"keydown",this.restrictCopyKey.bind(this)),Ee(document,"keydown",this.restrictCopyKey.bind(this))}if(this.properties?.disablePrint){Ee(this.navigator.mainElement,"beforeprint",this.beforePrint),Ee(this.navigator.headerMenu,"beforeprint",this.beforePrint);for(let t of this.navigator.iframes)Ee(t,"beforeprint",this.beforePrint.bind(this)),Ee(t.ownerDocument,"beforeprint",this.beforePrint.bind(this)),Ee(t.contentDocument,"beforeprint",this.beforePrint.bind(this)),Ee(t.contentWindow,"beforeprint",this.beforePrint.bind(this)),Ee(t.contentWindow?.document,"beforeprint",this.beforePrint.bind(this));Ee(window,"beforeprint",this.beforePrint.bind(this)),Ee(document,"beforeprint",this.beforePrint.bind(this)),Ee(this.navigator.mainElement,"afterprint",this.afterPrint),Ee(this.navigator.headerMenu,"afterprint",this.afterPrint);for(let t of this.navigator.iframes)Ee(t,"afterprint",this.afterPrint.bind(this)),Ee(t.ownerDocument,"afterprint",this.afterPrint.bind(this)),Ee(t.contentDocument,"afterprint",this.afterPrint.bind(this)),Ee(t.contentWindow,"afterprint",this.afterPrint.bind(this)),Ee(t.contentWindow?.document,"afterprint",this.afterPrint.bind(this));Ee(window,"afterprint",this.afterPrint.bind(this)),Ee(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){Ee(this.navigator.mainElement,"contextmenu",this.disableContext),Ee(this.navigator.headerMenu,"contextmenu",this.disableContext);for(let t of this.navigator.iframes)Ee(t,"contextmenu",this.disableContext),Ee(t.ownerDocument,"contextmenu",this.disableContext),Ee(t.contentDocument,"contextmenu",this.disableContext),Ee(t.contentWindow,"contextmenu",this.disableContext),Ee(t.contentWindow?.document,"contextmenu",this.disableContext);Ee(window,"contextmenu",this.disableContext),Ee(document,"contextmenu",this.disableContext)}}initializeResource(){this.properties?.hideTargetUrl&&this.hideTargetUrls(!0),this.properties?.disableDrag&&this.preventDrag(!0)}async initialize(){if(this.properties?.enableObfuscation)return new Promise(async t=>{await document.fonts.ready;for(let n of this.navigator.iframes)if(n.contentDocument){let i=Gr(n.contentDocument,"body");this.observe(),setTimeout(()=>{this.rects=this.findRects(i),this.rects.forEach(o=>this.toggleRect(o,this.securityContainer,this.isHacked)),this.setupEvents(),this.hasEventListener||(this.hasEventListener=!0,Ee(this.wrapper,"scroll",this.handleScroll.bind(this))),t()},10)}})}handleScroll(){this.rects.forEach(t=>this.toggleRect(t,this.securityContainer,this.isHacked))}handleResize(){if(this.properties?.enableObfuscation){let t=(0,wg.debounce)(()=>{this.calcRects(this.rects),this.rects!==void 0&&this.rects.forEach(n=>this.toggleRect(n,this.securityContainer,this.isHacked))},10);this.rects&&(this.observe(),t())}}disableContext(t){return t.preventDefault(),t.stopPropagation(),!1}disableSave(t){return(navigator.platform==="MacIntel"||navigator.platform.match("Mac")?t.metaKey:t.ctrlKey&&(t.key==="s"||t.keyCode===83))?(t.preventDefault(),t.stopPropagation(),!1):!0}preventCopy(t){return On.default.log("copy action initiated"),t.clipboardData.setData("text/plain","copy not allowed"),t.stopPropagation(),t.preventDefault(),!1}preventCopyKey(t){return(navigator.platform==="MacIntel"||navigator.platform.match("Mac")?t.metaKey:t.ctrlKey&&(t.key==="c"||t.keyCode===67))?(t.preventDefault(),t.stopPropagation(),!1):!0}restrictCopy(t){if(this.citation)return;On.default.log("copy action initiated");let n=this.navigator.iframes[0].contentWindow;if(n){let o=function(l){let u={className:h=>Ai.indexOf(h)<0,idName:h=>Ai.indexOf(h)<0},d=i.navigator.iframes[0].contentDocument;if(d)return wn(l,d,u)},i=this,a=Er(n,o);if(a===void 0){let l=this.navigator.iframes[0].contentDocument;a=this.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(l)}t.clipboardData.setData("text/plain",a?.cleanText?.substring(0,this.properties?.charactersToCopy??0))}else t.clipboardData.setData("text/plain","");return t.stopPropagation(),t.preventDefault(),!1}restrictCopyKey(t){if(navigator.platform==="MacIntel"||navigator.platform.match("Mac")?t.metaKey:t.ctrlKey&&(t.key==="c"||t.keyCode===67)){let n=this.navigator.iframes[0].contentWindow;if(n){let o=function(l){let u={className:h=>Ai.indexOf(h)<0,idName:h=>Ai.indexOf(h)<0},d=i.navigator.iframes[0].contentDocument;if(d)return wn(l,d,u)},i=this,a=Er(n,o);if(a===void 0){let l=this.navigator.iframes[0].contentDocument;a=this.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(l)}this.copyToClipboard(a?.cleanText?.substring(0,this.properties?.charactersToCopy??0))}else this.copyToClipboard("");return t.stopPropagation(),t.preventDefault(),!1}return!0}copyToClipboard(t){if(t=t.substring(0,this.properties?.charactersToCopy??0),window.clipboardData)window.clipboardData.setData("text/plain",t);else{let n=this.createElementForExecCommand(t);this.selectContent(n);try{window.netscape&&netscape.security&&netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"),document.execCommand("copy",!1)}catch(i){}document.body.removeChild(n)}}createElementForExecCommand(t){let n=document.createElement("div");return n.style.position="absolute",n.style.left="-10000px",n.style.top="-10000px",n.innerHTML=t,document.body.appendChild(n),n.contentEditable=!0,n}selectContent(t){let n=document.createRange();n.selectNodeContents(t);let i=window.getSelection();i?.removeAllRanges(),i?.addRange(n)}beforePrint(t){return On.default.log("before print"),this.navigator&&this.navigator.headerMenu&&(this.navigator.headerMenu.style.display="none",this.navigator.mainElement.style.display="none"),t.stopPropagation(),t.preventDefault(),!1}afterPrint(t){return On.default.log("after print"),this.navigator&&this.navigator.headerMenu&&(this.navigator.headerMenu.style.removeProperty("display"),this.navigator.mainElement.style.removeProperty("display")),t.stopPropagation(),t.preventDefault(),!1}hideTargetUrls(t){function n(i){i.preventDefault();let o=i.currentTarget.getAttribute("data-href-resolved"),a=document.createElement("a");a.setAttribute("href",o),a.click()}for(let i of this.navigator.iframes){let o=i.contentDocument?.querySelectorAll("a");o?.forEach(a=>{let l=a.getAttribute("data-href"),u=a.getAttribute("href");!l&&u&&(a.setAttribute("data-href",u),a.setAttribute("data-href-resolved",a.href))}),t?o?.forEach(a=>{a.setAttribute("href",""),a.addEventListener("click",n)}):o?.forEach(a=>{let l=a.getAttribute("data-href");l&&a.setAttribute("href",l),a.removeEventListener("click",n)})}}preventDrag(t){let n="-webkit-user-drag: none; -khtml-user-drag: none; -moz-user-drag: none; -ms-user-drag: none; user-drag: none; -webkit-pointer-events: none; -khtml-pointer-events: none; -moz-pointer-events: none; -ms-pointer-events: none; pointer-events: none;",i=o=>{o.preventDefault()};for(let o of this.navigator.iframes){let a=o.contentDocument?.body.getAttribute("style")||"";t?(o.contentDocument?.body.addEventListener("dragstart",i),o.contentDocument?.body.setAttribute("style",a+n)):(o.contentDocument?.body.removeEventListener("dragstart",i),o.contentDocument?.body.setAttribute("style",a.replace(n,"")))}}recalculate(t=0){return new Promise(n=>{if(this.properties?.enableObfuscation){let i=(0,wg.debounce)(()=>{this.calcRects(this.rects),this.rects!==void 0&&this.rects.forEach(o=>this.toggleRect(o,this.securityContainer,this.isHacked)),n(!0)},t);this.rects?(this.observe(),i()):n(!1)}else n(!1)})}calcRects(t){t!==void 0&&t.forEach(n=>{try{let{top:i,height:o,left:a,width:l}=this.measureTextNode(n.node);n.top=i,n.height=o,n.width=l,n.left=a}catch(i){On.default.log("error "+i),On.default.log(n),On.default.log(n.node),On.default.log("scrambledTextContent "+n.scrambledTextContent),On.default.log("textContent "+n.textContent),On.default.log("isObfuscated "+n.isObfuscated)}})}deactivateRect(t,n,i){this.isBeingHacked(n)||i?(t.node.textContent=t.scrambledTextContent,t.isObfuscated=!0):(t.node.textContent=t.textContent,t.isObfuscated=!1)}toggleRect(t,n,i){let o=this.isOutsideViewport(t),a=this.isBeingHacked(n);t.isObfuscated&&!o&&!a&&!i&&(t.node.textContent=t.textContent,t.isObfuscated=!1),!t.isObfuscated&&(o||a||i)&&(t.node.textContent=t.scrambledTextContent,t.isObfuscated=!0)}findRects(t){return this.findTextNodes(t).map(i=>{let{top:o,height:a,left:l,width:u}=this.measureTextNode(i),d=i.parentElement?.nodeName==="option"||i.parentElement?.nodeName==="script"?i.textContent:this.obfuscateText(i.textContent??"");return{top:o,height:a,width:u,left:l,node:i,textContent:i.textContent??"",scrambledTextContent:d??"",isObfuscated:!1}})}obfuscateText(t){return this.scramble(t,!0)}measureTextNode(t){try{let n=document.createRange();n.selectNode(t);let i=n.getBoundingClientRect();return n.detach(),i}catch(n){On.default.log("measureTextNode "+n),On.default.log("measureTextNode "+t),On.default.log(t.textContent)}}isBeingHacked(t){return t.style.animation||t.style.transition||t.style.position||t.hasAttribute("style")?(On.default.log("content being hacked"),!0):!1}isOutsideViewport(t){let n=this.wrapper.scrollLeft,i=n+this.wrapper.clientWidth,o=t.left+t.width,a=t.top+t.height,l=this.wrapper.scrollTop,u=l+this.wrapper.clientHeight,d=a<l,h=t.top>u,y=o<n-window.innerWidth,b=t.left>i+window.innerWidth;return d||h||y||b}findTextNodes(t,n=[]){let i=t.firstChild;for(;i;)i.nodeType===1&&this.findTextNodes(i,n),i.nodeType===3&&i.textContent?.trim()&&n.push(i),i=i.nextSibling;return n}scramble(t,n=!1,i=!1){var o=t.split(" ");function a(l){for(var u=l.length,d,h;u>0;)h=Math.floor(Math.random()*u),u--,d=l[u],l[u]=l[h],l[h]=d;return l}return n&&(o=o.map(function(l){return l.includes("-")?l:a(l.split("")).join("")})),i?a(o).join(" "):o.join(" ")}};H();var FA=nt(BA());H();var fh=r=>r.replace(/\n/g," ").replace(/\s\s+/g," "),A8=r=>fh(r).trim(),NA=/[\\^$.*+?()[\]{}|]/g,x8=RegExp(NA.source);function DA(r){return r&&x8.test(r)?r.replace(NA,"\\$&"):r||""}var ph=0,C8=()=>()=>Number.isSafeInteger(++ph)?ph:ph=1,jA=()=>{ph=0},T8=C8(),O8=r=>t=>{try{return wn(t,r,Co)}catch(n){return console.error("uniqueCssSelector:",n),""}};async function Mo(r,t,n,i,o=!1){if(!t)return[];let a=t.body?.textContent;if(!a)return[];if(r=A8(r),!r.length)return[];let l=t.createNodeIterator(t.body,NodeFilter.SHOW_TEXT,{acceptNode:p=>NodeFilter.FILTER_ACCEPT}),u=new RegExp(DA(r).replace(/ /g,"\\s+"),"gim");o&&(u=new RegExp("\\b"+DA(r).replace(/ /g,"\\s+")+"\\b","gim"));let d=[],h=100,y=30,b=0,w;for(;w=u.exec(a);){let p=Math.max(0,w.index-h),m=Math.min(h,w.index),f=fh(a.substr(p,m));f=f.substr(f.length-y),p=u.lastIndex,m=Math.min(h,a.length-p);let g=fh(a.substr(p,m)).substr(0,y),v=new Range,A=w.index;for(;b<=A;){let E=l.nextNode();E&&E.nodeValue&&(b+=E.nodeValue.length)}let C=l.referenceNode.nodeValue?l.referenceNode.nodeValue?.length-(b-A):0;for(v.setStart(l.referenceNode,C),A=w.index+w[0].length;b<=A;){let T=l.nextNode()?.nodeValue;T&&(b+=T.length)}C=l.referenceNode.nodeValue?l.referenceNode.nodeValue?.length-(b-A):0,v.setEnd(l.referenceNode,C),t.getCssSelector||(t.getCssSelector=O8(t));let O=Xr(v,t.getCssSelector);O&&d.push({textMatch:fh(w[0]),textBefore:f,textAfter:g,rangeInfo:O,href:n,title:i,uuid:T8().toString()})}return d}var HA=nt(Jt()),Il=class{constructor(t,n,i,o,a){this.currentChapterSearchResult=[];this.bookSearchResult=[];this.currentSearchHighlights=[];this.headerMenu=a,this.publication=t,this.properties=n,this.api=o,this.highlighter=i}static async create(t){let n=new this(t.publication,t,t.highlighter,t.api,t.headerMenu);return await n.start(),n}async stop(){HA.default.log("Search module stop"),je(this.searchInput,"keypress",this.handleSearch.bind(this)),je(this.searchGo,"click",this.handleSearch.bind(this))}async start(){if(this.headerMenu){this.searchInput=Ie(this.headerMenu,"#searchInput"),Ee(this.searchInput,"keypress",this.handleSearch.bind(this)),this.searchGo=Ie(this.headerMenu,"#searchGo"),Ee(this.searchGo,"click",this.handleSearch.bind(this));var t=Ie(this.headerMenu,"#menu-button-search");t&&t.parentElement?.style.removeProperty("display")}setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("search"):this.navigator.showLayer("search")},10)}async handleSearch(t){(t.key==="Enter"||t.type==="click")&&(await this.handleSearchChapter(),await this.handleSearchBook())}async handleSearchChapter(t){var n=this,i=this.searchInput.value;let o=this.navigator.currentChapterLink.href,a=this.publication.getSpineItem(o);if(this.headerMenu)var l=Ie(document,"#searchResultChapter");n.currentChapterSearchResult=[],n.currentSearchHighlights=[];var u=[];await this.searchAndPaintChapter(i,t,async h=>{u=h,d(1),this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)});async function d(h){l.innerHTML="";var y;if(y=n.paginate(u,h,10),y.total===0){let b=document.createElement("a");b.className="collection-item",b.innerHTML="nothing found",l.appendChild(b)}else{for(let f=0;f<y.data.length;f++){let g=document.createElement("a"),v=y.data[f];g.className="collection-item",g.href=a?.Href??"",g.innerHTML="..."+v.textBefore+"<mark>"+v.textMatch+"</mark>"+v.textAfter+"...",Ee(g,"click",A=>{A.preventDefault(),A.stopPropagation(),n.jumpToMark(f+h*10-10)}),l.appendChild(g)}let b=document.createElement("div");b.style.textAlign="center",b.style.marginTop="10px";let w=document.createElement("ul");w.className="pagination";let p=document.createElement("li");if(p.className="disabled",p.innerHTML='<a href="#!"> < </a>',y.pre_page!==void 0){let f=y.pre_page;p.className="waves-effect",Ee(p,"click",g=>{g.preventDefault(),g.stopPropagation(),d(f)})}w.appendChild(p);for(let f=1;f<=y.total_pages;f++){let g,v=document.createElement("li");v.className="waves-effect",f===y.page&&(v.className="active",g=v),v.innerHTML='<a href="#!">'+f+"</a>",Ee(v,"click",A=>{A.preventDefault(),A.stopPropagation(),g&&(g.className="waves-effect"),v.className="active",g=v,d(f)}),w.appendChild(v)}let m=document.createElement("li");if(m.className="disabled",m.innerHTML='<a href="#!"> > </a>',y.next_page!==void 0){let f=y.next_page;m.className="waves-effect",Ee(m,"click",g=>{g.preventDefault(),g.stopPropagation(),d(f)})}w.appendChild(m),b.appendChild(w),l.appendChild(b)}}}async searchAndPaintChapter(t,n=0,i){this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.deactivate();let o=this.publication.getAbsoluteHref(this.publication.readingOrder[this.navigator.currentResource()??0].Href),a=this.publication.getTOCItem(o);a===null&&(a=this.publication.readingOrder[this.navigator.currentResource()??0]);let l=[];this.highlighter?.destroyHighlights(it.Search),this.navigator.rights.enableSearch&&this.drawSearch();let u=0;if(a){let d=this.navigator.iframes[0].contentDocument;d&&a&&Mo(t,d,a.Href,a.Title).then(h=>{h.forEach(y=>{let b={rangeInfo:y.rangeInfo};setTimeout(()=>{let w;u===n?(w=this.createSearchHighlight(b,this.properties?.current),this.jumpToMark(n)):w=this.createSearchHighlight(b,this.properties?.color),y.highlight=w,l.push(y),this.currentChapterSearchResult.push(y),this.currentSearchHighlights.push(w),u++},500)}),setTimeout(()=>{i(l)},500)})}}createSearchHighlight(t,n){try{var i=n;Qe.isHexColor(i)&&(i=Qe.hexToRgbChannels(i));let a=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,l=FA.SHA256.hash(a),u="R2_SEARCH_"+l;var o=!1;let d={color:i||ls,id:u,pointerInteraction:o,selectionInfo:t,marker:Ve.Highlight,type:it.Search},h=this.highlighter?.createHighlightDom(this.navigator.iframes[0].contentWindow,d);return d.position=parseInt((h?.hasChildNodes()?h.childNodes[0]:h).style.top.replace("px","")),d}catch(a){throw"Can't create highlight: "+a}}clearSearch(){this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.highlighter?.destroyHighlights(it.Search)}async search(t,n){return this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.bookSearchResult=[],jA(),await this.searchAndPaintChapter(t,0,async()=>{this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)}),n?(await this.searchBook(t),await this.searchChapter(t)):(await this.searchChapter(t),await this.searchBook(t))}async goToSearchID(t,n,i){var o=n,a;let l=this.navigator.currentChapterLink.href;var u=this.publication.getAbsoluteHref(t);let d=this.bookSearchResult.filter(h=>h.href===t);if(i?(a=this.currentChapterSearchResult.filter(h=>h.uuid===n)[0],o=this.currentChapterSearchResult.findIndex(h=>h.uuid===n)):(a=d.filter(h=>h.uuid===n)[0],o=d.findIndex(h=>h.uuid===n)),a!==void 0)if(l===u)this.jumpToMark(o);else{let y={href:u,locations:{progression:0},title:"title"};this.navigator.navigate(y),setTimeout(()=>{this.searchAndPaintChapter(a.textMatch,o,async()=>{this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)})},300)}}async goToSearchIndex(t,n,i){var o=n,a;let l=this.navigator.currentChapterLink.href;var u=this.publication.getAbsoluteHref(t);let d=this.bookSearchResult.filter(h=>h.href===t);if(i?a=this.currentChapterSearchResult[o]:a=d[o],a!==void 0)if(l===u)this.jumpToMark(o);else{let y={href:u,locations:{progression:0},title:"title"};this.navigator.navigate(y),setTimeout(()=>{this.searchAndPaintChapter(a.textMatch,o,async()=>{this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)})},300)}}async handleSearchBook(){var t=this,n=this.searchInput.value;if(t.headerMenu)var i=Ie(document,"#searchResultBook");o(1);async function o(l){i.innerHTML="";var u,d=await t.searchBook(n);if(u=t.paginate(d,l,10),u.total===0){let h=document.createElement("a");h.className="collection-item",h.innerHTML="nothing found",i.appendChild(h)}else{a(u.data,m=>m.href).forEach(m=>{let f=document.createElement("div");if(f.style.marginBottom="10px",m[0].title){let g=document.createElement("span");g.className="collection-item",g.style.display="block",g.innerHTML=m[0].title,f.appendChild(g)}i.appendChild(f),m.forEach(g=>{let v=document.createElement("a");v.className="collection-item";var A=t.publication.getAbsoluteHref(g.href);v.innerHTML="..."+g.textBefore+"<mark>"+g.textMatch+"</mark>"+g.textAfter+"...",Ee(v,"click",C=>{C.preventDefault(),C.stopPropagation();let E=d.filter(I=>I.href===g.href).findIndex(I=>I===g);if(t.navigator.currentChapterLink.href===A)t.jumpToMark(E);else{let M={href:A,locations:{progression:0},title:"title"};t.navigator.navigate(M),setTimeout(()=>{t.handleSearchChapter(E)},300)}}),f.appendChild(v)})});let y=document.createElement("div");y.style.textAlign="center",y.style.marginTop="10px";let b=document.createElement("ul");b.className="pagination";let w=document.createElement("li");if(w.className="disabled",w.innerHTML='<a href="#!"> < </a>',u.pre_page!=null){let m=u.pre_page;w.className="waves-effect",Ee(w,"click",f=>{f.preventDefault(),f.stopPropagation(),o(m)})}b.appendChild(w);for(let m=1;m<=u.total_pages;m++){let f,g=document.createElement("li");g.className="waves-effect",m===u.page&&(g.className="active",f=g),g.innerHTML='<a href="#!">'+m+"</a>",Ee(g,"click",v=>{v.preventDefault(),v.stopPropagation(),f&&(f.className="waves-effect"),g.className="active",f=g,o(m)}),b.appendChild(g)}let p=document.createElement("li");if(p.className="disabled",p.innerHTML='<a href="#!"> > </a>',u.next_page!=null){let m=u.next_page;p.className="waves-effect",Ee(p,"click",f=>{f.preventDefault(),f.stopPropagation(),o(m)})}b.appendChild(p),y.appendChild(b),i.appendChild(y)}}function a(l,u){let d=new Map;return l.forEach(h=>{let y=u(h),b=d.get(y);b?b.push(h):d.set(y,[h])}),Array.from(d.values())}}async searchBook(t){this.bookSearchResult=[];let n=[];for(let i=0;i<this.publication.readingOrder.length;i++){let o=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[i].Href:""),a=this.publication.getTOCItem(o);if(a===void 0&&this.publication.readingOrder&&(a=this.publication.readingOrder[i]),a){let l=this.publication.getAbsoluteHref(a.Href);this.navigator.api?.getContent?await this.navigator.api?.getContent(l).then(u=>{let h=new DOMParser().parseFromString(u,"application/xhtml+xml");a&&Mo(t,h,a.Href,a.Title).then(y=>{y.forEach(b=>{n.push(b),this.bookSearchResult.push(b)})})}):await fetch(l,this.navigator.requestConfig).then(u=>u.text()).then(async u=>{let h=new DOMParser().parseFromString(this.navigator.requestConfig?.encoded?this.decodeBase64(u):u,"application/xhtml+xml");a&&Mo(t,h,a.Href,a.Title).then(y=>{y.forEach(b=>{n.push(b),this.bookSearchResult.push(b)})})})}if(i===this.publication.readingOrder.length-1)return n}}decodeBase64(t){let n=atob(t),i=n.length,o=new Uint8Array(i);for(let l=0;l<i;l++)o[l]=n.charCodeAt(l);return new TextDecoder().decode(o)}async searchChapter(t){let n=[],i=this.publication.getAbsoluteHref(this.publication.readingOrder[this.navigator.currentResource()??0].Href),o=this.publication.getTOCItem(i);if(o===null&&(o=this.publication.readingOrder[this.navigator.currentResource()??0]),o){let a=this.publication.getAbsoluteHref(o.Href);this.navigator.api?.getContent?await this.navigator.api?.getContent(a).then(l=>{let d=new DOMParser().parseFromString(l,"application/xhtml+xml");o&&Mo(t,d,o.Href,o.Title).then(h=>{h.forEach(y=>{n.push(y)})})}):await fetch(a,this.navigator.requestConfig).then(l=>l.text()).then(async l=>{let d=new DOMParser().parseFromString(this.navigator.requestConfig?.encoded?this.decodeBase64(l):l,"application/xhtml+xml");o&&Mo(t,d,o.Href,o.Title).then(h=>{h.forEach(y=>{n.push(y)})})})}return n}drawSearch(){setTimeout(()=>{this.currentSearchHighlights=[],this.currentChapterSearchResult.forEach(t=>{let n={rangeInfo:t.rangeInfo};if(this.properties?.color){let i=this.createSearchHighlight(n,this.properties?.color);t.highlight=i,this.currentSearchHighlights.push(i)}})},100)}async handleResize(){await this.highlighter?.destroyHighlights(it.Search),this.drawSearch()}jumpToMark(t){setTimeout(()=>{if(this.currentChapterSearchResult.length){var n=this.currentChapterSearchResult[t];this.currentSearchHighlights.forEach(o=>{var a=this.properties?.color;Qe.isHexColor(a)&&(a=Qe.hexToRgbChannels(a)),o.color=a});var i=this.properties?.current;Qe.isHexColor(i)&&(i=Qe.hexToRgbChannels(i)),n.highlight.color=i,this.highlighter?.setAndResetSearchHighlight(n.highlight,this.currentSearchHighlights),this.navigator.view?.goToCssSelector(n.rangeInfo.startContainerElementCssSelector),this.navigator.updatePositionInfo()}},200)}paginate(t,n,i){let o=n||1,a=i||10,l=(o-1)*a,u=t.slice(l).slice(0,a),d=Math.ceil(t.length/a);return{page:o,per_page:a,pre_page:o-1?o-1:void 0,next_page:d>o?o+1:void 0,total:t.length,total_pages:d,data:u}}};H();var oi=nt(Jt()),ko=class{},Ke=ko;Ke.COLOR_REF="color",Ke.AUTO_SCROLL_REF="autoscroll",Ke.RATE_REF="rate",Ke.PITCH_REF="pitch",Ke.VOLUME_REF="volume",Ke.VOICE_REF="voice",Ke.COLOR_KEY="tts-"+ko.COLOR_REF,Ke.AUTO_SCROLL_KEY="tts-"+ko.AUTO_SCROLL_REF,Ke.RATE_KEY="tts-"+ko.RATE_REF,Ke.PITCH_KEY="tts-"+ko.PITCH_REF,Ke.VOLUME_KEY="tts-"+ko.VOLUME_REF,Ke.VOICE_KEY="tts-"+ko.VOICE_REF;var _g=class{constructor(t,n,i){this.TTSSETTINGS="ttsSetting";this.color="orange";this.autoScroll=!0;this.rate=1;this.pitch=1;this.volume=1;this.voice={usePublication:!0};this.settingsChangeCallback=()=>{};this.restartCallback=()=>{};this.store=t,this.api=n,this.headerMenu=i,this.initialise()}static create(t){let n=new this(t.store,t.api,t.headerMenu);if(t.initialTTSSettings){let i=t.initialTTSSettings;i?.rate&&(n.rate=i.rate,oi.default.log(n.rate)),i?.pitch&&(n.pitch=i.pitch,oi.default.log(n.pitch)),i?.volume&&(n.volume=i.volume,oi.default.log(n.volume)),i?.color&&(n.color=i.color,oi.default.log(n.color)),i?.autoScroll&&(n.autoScroll=i.autoScroll,oi.default.log(n.autoScroll)),i?.voice&&(n.voice=i.voice,oi.default.log(n.voice))}return n.initializeSelections(),n}stop(){oi.default.log("tts settings stop")}initialise(){this.autoScroll=this.getProperty(Ke.AUTO_SCROLL_KEY)!=null?this.getProperty(Ke.AUTO_SCROLL_KEY).value:this.autoScroll,this.rate=this.getProperty(Ke.RATE_KEY)!=null?this.getProperty(Ke.RATE_KEY).value:this.rate,this.pitch=this.getProperty(Ke.PITCH_KEY)!=null?this.getProperty(Ke.PITCH_KEY).value:this.pitch,this.volume=this.getProperty(Ke.VOLUME_KEY)!=null?this.getProperty(Ke.VOLUME_KEY).value:this.volume,this.color=this.getProperty(Ke.COLOR_KEY)!=null?this.getProperty(Ke.COLOR_KEY).value:this.color,this.voice=this.getProperty(Ke.VOICE_REF)!=null?this.getProperty(Ke.VOICE_REF).value:this.voice,this.userProperties=this.getTTSSettings()}reset(){this.color="orange",this.autoScroll=!0,this.rate=1,this.pitch=1,this.volume=1,this.voice={usePublication:!0},this.userProperties=this.getTTSSettings()}initializeSelections(){this.headerMenu&&(this.settingsView=Ie(this.headerMenu,"#container-view-tts-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(t){this.headerMenu&&(this.speechRate=Ie(this.headerMenu,"#speechRate")),this.headerMenu&&(this.speechPitch=Ie(this.headerMenu,"#speechPitch")),this.headerMenu&&(this.speechVolume=Ie(this.headerMenu,"#speechVolume")),this.headerMenu&&(this.speechAutoScroll=Ie(this.headerMenu,"#autoScroll")),this.speechRate&&(this.speechRate.value=this.rate.toString()),this.speechPitch&&(this.speechPitch.value=this.pitch.toString()),this.speechVolume&&(this.speechVolume.value=this.volume.toString()),this.speechAutoScroll&&(this.speechAutoScroll.checked=this.autoScroll),Ee(Ie(t,"ul"),"click",n=>{n.stopPropagation()})}onSettingsChange(t){this.settingsChangeCallback=t}onRestart(t){this.restartCallback=t}storeProperty(t){this.updateUserSettings(),this.saveProperty(t)}updateUserSettings(){var t={rate:this.userProperties.getByRef(Ke.RATE_REF)?.value,pitch:this.userProperties.getByRef(Ke.PITCH_REF)?.value,volume:this.userProperties.getByRef(Ke.VOLUME_REF)?.value,voice:this.userProperties.getByRef(Ke.VOLUME_REF)?.value,color:this.userProperties.getByRef(Ke.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(Ke.AUTO_SCROLL_REF)?.value};this.applyTTSSettings(t),this.api?.updateSettings&&this.api?.updateSettings(t).then(async n=>{oi.default.log("api updated tts settings",n)})}getTTSSettings(){var t=new Wr;return t.addSwitchable("tts-auto-scroll-off","tts-auto-scroll-on",this.autoScroll,Ke.AUTO_SCROLL_REF,Ke.AUTO_SCROLL_KEY),t.addIncremental(this.rate,.1,10,.1,"",Ke.RATE_REF,Ke.RATE_KEY),t.addIncremental(this.pitch,.1,2,.1,"",Ke.PITCH_REF,Ke.PITCH_KEY),t.addIncremental(this.volume,.1,1,.1,"",Ke.VOLUME_REF,Ke.VOLUME_KEY),t.addStringable(this.color,Ke.COLOR_REF,Ke.COLOR_KEY),t.addJSONable(JSON.stringify(this.voice),Ke.VOICE_REF,Ke.VOICE_KEY),t}saveProperty(t){let n=this.store.get(this.TTSSETTINGS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.name!==t.name),i.push(t),this.store.set(this.TTSSETTINGS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(this.TTSSETTINGS,JSON.stringify(i))}return t}getProperty(t){let n=this.store.get(this.TTSSETTINGS);if(n){let i=JSON.parse(n);return i=i.filter(o=>o.name===t),i.length===0?void 0:i[0]}}resetTTSSettings(){this.store.remove(this.TTSSETTINGS),this.reset(),this.settingsChangeCallback(),this.restartCallback()}applyTTSSettings(t){if(t.rate){oi.default.log("rate "+this.rate),this.rate=t.rate;let n=this.userProperties.getByRef(Ke.RATE_REF);n&&(n.value=this.rate,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.pitch){oi.default.log("pitch "+this.pitch),this.pitch=t.pitch;let n=this.userProperties.getByRef(Ke.PITCH_REF);n&&(n.value=this.pitch,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.volume){oi.default.log("volume "+this.volume),this.volume=t.volume;let n=this.userProperties.getByRef(Ke.VOLUME_REF);n&&(n.value=this.volume,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.color){this.color=t.color;let n=this.userProperties.getByRef(Ke.COLOR_REF);n&&(n.value=this.color,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoScroll!==void 0){oi.default.log("autoScroll "+this.autoScroll),this.autoScroll=t.autoScroll;let n=this.userProperties.getByRef(Ke.AUTO_SCROLL_REF);n&&(n.value=this.autoScroll,this.saveProperty(n)),this.settingsChangeCallback()}if(t.voice){oi.default.log("voice "+this.voice),this.voice=t.voice;let n=this.userProperties.getByRef(Ke.VOICE_REF);n&&(n.value=this.voice,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}}applyPreferredVoice(t){var n=t.indexOf(":")!==-1?t.slice(0,t.indexOf(":")):void 0,i=t.indexOf(":")!==-1?t.slice(t.indexOf(":")+1):t;n!==void 0&&i!==void 0?this.applyTTSSettings({voice:{usePublication:!0,name:n,lang:i}}):i!==void 0&&n===void 0&&this.applyTTSSettings({voice:{usePublication:!0,lang:i}})}increase(t){if(t==="rate"){this.userProperties.getByRef(Ke.RATE_REF).increment();let n=this.userProperties.getByRef(Ke.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="pitch"){this.userProperties.getByRef(Ke.PITCH_REF).increment();let n=this.userProperties.getByRef(Ke.PITCH_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="volume"){this.userProperties.getByRef(Ke.VOLUME_REF).increment();let n=this.userProperties.getByRef(Ke.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}}decrease(t){if(t==="rate"){this.userProperties.getByRef(Ke.RATE_REF).decrement();let n=this.userProperties.getByRef(Ke.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="pitch"){this.userProperties.getByRef(Ke.PITCH_REF).decrement();let n=this.userProperties.getByRef(Ke.PITCH_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="volume"){this.userProperties.getByRef(Ke.VOLUME_REF).decrement();let n=this.userProperties.getByRef(Ke.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}}};H();H();var gh=`${nr.loading}`,UA=`
|
|
79
|
+
</svg>`,nr={error:ni("error-icon","Warning",'<path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/>'),home:'<path d="M12 5.69l5 4.5V18h-2v-6H9v6H7v-7.81l5-4.5M12 3L2 12h3v8h6v-6h2v6h6v-8h3L12 3z"/>',expand:ni("expand-icon","Enter fullscreen",'<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>',"icon active-icon"),loading:V5("loading-icon","Loading",'<path fill="#BBBBBB" d="M145,241.6c-53.3,0-96.6-43.2-96.6-96.6c0-53.3,43.2-96.6,96.6-96.6c53.3,0,96.6,43.2,96.6,96.6 c0,26.7-10.8,50.9-28.3,68.3l7.6,7.6c19.4-19.4,31.5-46.3,31.5-75.9c0-59.3-48-107.3-107.3-107.3S37.7,85.7,37.7,145 c0,59.3,48,107.3,107.3,107.3V241.6z"/>',"0 0 290 290"),next:ni("next-icon","Next Chapter",'<path d="M6.49 20.13l1.77 1.77 9.9-9.9-9.9-9.9-1.77 1.77L14.62 12l-8.13 8.13z"/>'),previous:ni("previous-icon","Previous Chapter",'<path d="M17.51 3.87L15.73 2.1 5.84 12l9.9 9.9 1.77-1.77L9.38 12l8.13-8.13z"/>'),settings:ni("settings-icon","Settings",'<path d="M19.43 12.98c.04-.32.07-.64.07-.98 0-.34-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46c-.09-.16-.26-.25-.44-.25-.06 0-.12.01-.17.03l-2.49 1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65C14.46 2.18 14.25 2 14 2h-4c-.25 0-.46.18-.49.42l-.38 2.65c-.61.25-1.17.59-1.69.98l-2.49-1c-.06-.02-.12-.03-.18-.03-.17 0-.34.09-.43.25l-2 3.46c-.13.22-.07.49.12.64l2.11 1.65c-.04.32-.07.65-.07.98 0 .33.03.66.07.98l-2.11 1.65c-.19.15-.24.42-.12.64l2 3.46c.09.16.26.25.44.25.06 0 .12-.01.17-.03l2.49-1c.52.4 1.08.73 1.69.98l.38 2.65c.03.24.24.42.49.42h4c.25 0 .46-.18.49-.42l.38-2.65c.61-.25 1.17-.59 1.69-.98l2.49 1c.06.02.12.03.18.03.17 0 .34-.09.43-.25l2-3.46c.12-.22.07-.49-.12-.64l-2.11-1.65zm-1.98-1.71c.04.31.05.52.05.73 0 .21-.02.43-.05.73l-.14 1.13.89.7 1.08.84-.7 1.21-1.27-.51-1.04-.42-.9.68c-.43.32-.84.56-1.25.73l-1.06.43-.16 1.13-.2 1.35h-1.4l-.19-1.35-.16-1.13-1.06-.43c-.43-.18-.83-.41-1.23-.71l-.91-.7-1.06.43-1.27.51-.7-1.21 1.08-.84.89-.7-.14-1.13c-.03-.31-.05-.54-.05-.74s.02-.43.05-.73l.14-1.13-.89-.7-1.08-.84.7-1.21 1.27.51 1.04.42.9-.68c.43-.32.84-.56 1.25-.73l1.06-.43.16-1.13.2-1.35h1.39l.19 1.35.16 1.13 1.06.43c.43.18.83.41 1.23.71l.91.7 1.06-.43 1.27-.51.7 1.21-1.07.85-.89.7.14 1.13zM12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/>',"icon open"),toc:ni("toc-icon","Table of Contents",'<path d="M3 9h14V7H3v2zm0 4h14v-2H3v2zm0 4h14v-2H3v2zm16 0h2v-2h-2v2zm0-10v2h2V7h-2zm0 6h2v-2h-2v2z"/>',"icon open"),bookmarks:ni("toc-icon","Bookmarks",'<path d="M4,6H2v16h16v-2H4V6z"/><path d="M22,2H6v16h16V2z M20,12l-2.5-1.5L15,12V4h5V12z"/>',"icon open"),bookmark:ni("toc-icon","Bookmark",'<path d="M19,3H5v18l7-3l7,3V3z"/>',"icon open"),delete:ni("delete-icon","Delete",'<path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>',"icon open"),close:ni("close-icon","Close",'<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>',"icon open"),text:ni("text-icon","Text",'<path d="M5 4v3h5.5v12h3V7H19V4z"/>',"icon open"),speak:ni("speak-icon","Speak",'<circle cx="9" cy="9" r="4"/><path d="M9 15c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4zm7.76-9.64l-1.68 1.69c.84 1.18.84 2.71 0 3.89l1.68 1.69c2.02-2.02 2.02-5.07 0-7.27zM20.07 2l-1.63 1.63c2.77 3.02 2.77 7.56 0 10.74L20.07 16c3.9-3.89 3.91-9.95 0-14z"/><path d="M0 0h24v24H0z" fill="none"/>',"icon open"),note:ni("note-icon","Note",'<polygon points="17.71 24.66 22.3 20.07 17.71 20.07 17.71 24.66" fill="none"/><path d="M22.42.07H5.58A3.28,3.28,0,0,0,2.29,3.35V24.79a3.28,3.28,0,0,0,3.29,3.28H16.71a1,1,0,0,0,.71-.29l8-8a1,1,0,0,0,.29-.71V3.35A3.28,3.28,0,0,0,22.42.07Zm-8.17,15h-7v-2h7Zm-7-6v-2h13v2ZM16.5,25.86v-6a1,1,0,0,1,1-1h6Z" />',"icon open"),highlight:ni("highlight-icon","Highlight",'<path d="M27.71,7.78,21.12,1.19a1,1,0,0,0-1.38,0L4.32,15A1,1,0,0,0,4,15.7a1,1,0,0,0,.3.73c1.22,1.22,1.2,2.37,0,3.62a1,1,0,0,0,0,1.41l3.2,3.2a1,1,0,0,0,1.41,0c1.28-1.28,2.36-1.29,3.62,0a1,1,0,0,0,1.45,0L27.74,9.16A1,1,0,0,0,27.71,7.78Z" /><path d="M3.09,22.59l-2.8,2.8a1,1,0,0,0-.21,1.09A1,1,0,0,0,1,27.1H4.6a1,1,0,0,0,.71-.29l1-1Z" />',"icon open")};var D0=nt(Yd());var $n=nt(Jt()),qe;(function(d){d.R2_ID_HIGHLIGHTS_CONTAINER="R2_ID_HIGHLIGHTS_CONTAINER",d.R2_ID_BOOKMAKRS_CONTAINER="R2_ID_BOOKMAKRS_CONTAINER",d.R2_ID_READALOUD_CONTAINER="R2_ID_READALOUD_CONTAINER",d.R2_ID_PAGEBREAK_CONTAINER="R2_ID_PAGEBREAK_CONTAINER",d.R2_ID_SEARCH_CONTAINER="R2_ID_SEARCH_CONTAINER",d.R2_ID_DEFINITIONS_CONTAINER="R2_ID_DEFINITIONS_CONTAINER",d.R2_ID_LINEFOCUS_CONTAINER="R2_ID_LINEFOCUS_CONTAINER",d.R2_ID_GUTTER_RIGHT_CONTAINER="R2_ID_GUTTER_RIGHT_CONTAINER"})(qe||(qe={}));var F_="R2_CLASS_HIGHLIGHT_CONTAINER",Sl="R2_CLASS_HIGHLIGHT_BOUNDING_AREA",Tn="R2_CLASS_HIGHLIGHT_AREA",Al="R2_CLASS_HIGHLIGHT_ICON",_r=.5,H_=.75,ls={blue:100,green:50,red:230},tn=[],J5="data-highlighted",K5="data-timestamp",ha={ELEMENT_NODE:1,TEXT_NODE:3},xl;(function(i){i.INLINE="inline",i.TOP="top",i.BOTTOM="bottom"})(xl||(xl={}));var Ai=[qe.R2_ID_HIGHLIGHTS_CONTAINER,qe.R2_ID_PAGEBREAK_CONTAINER,qe.R2_ID_SEARCH_CONTAINER,qe.R2_ID_READALOUD_CONTAINER,qe.R2_ID_BOOKMAKRS_CONTAINER,qe.R2_ID_DEFINITIONS_CONTAINER,qe.R2_ID_LINEFOCUS_CONTAINER,qe.R2_ID_GUTTER_RIGHT_CONTAINER,F_,Tn,Sl],j0=-1,F0=-1,Qe=class{constructor(t,n,i,o,a){this.lastSelectedHighlight=void 0;this.activeAnnotationMarkerId=void 0;this.showTool=(0,_l.debounce)(t=>{this.isAndroid()||this.snapSelectionToWord(t),this.toolboxShow()},navigator.userAgent.toLowerCase().indexOf("firefox")>-1?200:100);this.isSelectionMenuOpen=!1;this.selectionMenuOpened=(0,_l.debounce)(()=>{this.isSelectionMenuOpen||(this.isSelectionMenuOpen=!0,this.api?.selectionMenuOpen&&this.api?.selectionMenuOpen(),this.navigator.emit("toolbox.opened","opened"))},100);this.selectionMenuClosed=(0,_l.debounce)(()=>{this.isSelectionMenuOpen&&(this.isSelectionMenuOpen=!1,this.api?.selectionMenuClose&&this.api?.selectionMenuClose(),this.navigator.emit("toolbox.closed","closed"))},100);this.selection=(0,_l.debounce)((t,n)=>{this.api?.selection&&this.api?.selection(t,n)},100);this.getScrollingElement=t=>t?.scrollingElement?t?.scrollingElement:t?.body?t?.body:document.createElement("body");this.layerSettings=t,this.properties=n,this.properties.menuPosition==null&&(this.properties.menuPosition=xl.INLINE),this.api=a,this.hasEventListener=i,this.options=this.defaults(o,{color:"#fce300",highlightedClass:"highlighted",contextClass:"highlighter-context",onBeforeHighlight:function(){return!0},onAfterHighlight:function(){}})}static async create(t){let n=new this(t.layerSettings,t,!1,{},t.api);return new Promise(i=>i(n))}async initialize(){let t=this.navigator.iframes[0].contentDocument;t&&this.dom(t.body).addClass(this.options.contextClass),this.bindEvents(this.navigator.iframes[0].contentDocument?.body,this,this.hasEventListener),this.initializeToolbox(),j0=-1,F0=-1;let n=this;async function i(){n.lastSelectedHighlight===void 0||(n.lastSelectedHighlight=void 0)}setTimeout(async()=>{let o=this.navigator.iframes[0].contentDocument;o&&await o.body?.addEventListener("click",i)},100)}haveSameColor(t,n){return this.dom(t).color()===this.dom(n).color()}defaults(t,n){t=t||{};for(let i in n)n.hasOwnProperty(i)&&t[i]===void 0&&(t[i]=n[i]);return t}unique(t){return t.filter(function(n,i,o){return o.indexOf(n)===i})}refineRangeBoundaries(t){let n=t.startContainer,i=t.endContainer,o=t.commonAncestorContainer,a=!0;if(t.endOffset===0){for(;!i.previousSibling&&i.parentNode!==o;)i=i.parentNode;i=i.previousSibling}else i.nodeType===ha.TEXT_NODE?t.endOffset<i.nodeValue.length&&i.splitText(t.endOffset):t.endOffset>0&&(i=i.childNodes.item(t.endOffset-1));return n.nodeType===ha.TEXT_NODE?t.startOffset===n.nodeValue.length?a=!1:t.startOffset>0&&(n=n.splitText(t.startOffset),i===n.previousSibling&&(i=n)):t.startOffset<n.childNodes.length?n=n.childNodes.item(t.startOffset):n=n.nextSibling,{startContainer:n,endContainer:i,goDeeper:a}}sortByDepth(t,n){let i=this;t.sort(function(o,a){return i.dom(n?a:o).parents().length-i.dom(n?o:a).parents().length})}groupHighlights(t){let n=[],i={},o=[];return t.forEach(function(a){let l=a.getAttribute(K5);typeof i[l]=="undefined"&&(i[l]=[],n.push(l)),i[l].push(a)}),n.forEach(function(a){let l=i[a];o.push({chunks:l,timestamp:a,toString:function(){return l.map(function(u){return u.textContent}).join("")}})}),o}dom(t){let n=this;return{addClass:function(i){t.classList?t.classList.add(i):t.className+=" "+i},removeClass:function(i){t.classList?t.classList.remove(i):t.className=t.className.replace(new RegExp("(^|\\b)"+i+"(\\b|$)","gi")," ")},prepend:function(i){let o=Array.prototype.slice.call(i),a=o.length;for(;a--;)t.insertBefore(o[a],t.firstChild)},append:function(i){let o=Array.prototype.slice.call(i);for(let a=0,l=o.length;a<l;++a)t.appendChild(o[a])},insertAfter:function(i){return i.parentNode?.insertBefore(t,i.nextSibling)},insertBefore:function(i){return i.parentNode?.insertBefore(t,i)},remove:function(){t.parentNode.removeChild(t),t=null},contains:function(i){return t!==i&&t.contains(i)},wrap:function(i){return t.parentNode&&t.parentNode.insertBefore(i,t),i.appendChild(t),i},unwrap:function(){let i=Array.prototype.slice.call(t.childNodes),o;return i.forEach(function(a){o=a.parentNode,n.dom(a).insertBefore(a.parentNode),n.dom(o).remove()}),i},parents:function(){let i,o=[];for(;i=t.parentNode;)o.push(i),t=i;return o},normalizeTextNodes:function(){if(!!t){if(t.nodeType===ha.TEXT_NODE)for(;t.nextSibling&&t.nextSibling.nodeType===ha.TEXT_NODE;)t.nodeValue+=t.nextSibling.nodeValue,t.parentNode.removeChild(t.nextSibling);else n.dom(t.firstChild).normalizeTextNodes();n.dom(t.nextSibling).normalizeTextNodes()}},color:function(){return t.style.backgroundColor},fromHTML:function(i){let o=document.createElement("div");return o.innerHTML=i,o.childNodes},getRange:function(){let i=n.dom(t)?.getSelection(),o;return i?.rangeCount>0&&(o=i?.getRangeAt(0)),o},removeAllRanges:function(){n.dom(t)?.getSelection()?.removeAllRanges(),n.toolboxHide()},getSelection:function(){return n.dom(t).getWindow()?.getSelection()},getWindow:function(){return n.dom(t).getDocument()?.defaultView},getDocument:function(){return t?.ownerDocument||t}}}disableContext(t){return t.preventDefault(),t.stopPropagation(),!1}bindEvents(t,n,i){let o=t.ownerDocument;t.addEventListener("mouseup",this.toolboxShowDelayed.bind(this)),t.addEventListener("touchend",this.toolboxShowDelayed.bind(this)),o.addEventListener("mouseup",this.toolboxShowDelayed.bind(this)),o.addEventListener("touchend",this.toolboxShowDelayed.bind(this)),i||window.addEventListener("resize",this.toolboxPlacement.bind(this)),o.addEventListener("selectionchange",this.toolboxPlacement.bind(this)),o.addEventListener("selectionchange",this.toolboxShowDelayed.bind(this)),t.addEventListener("mousedown",this.toolboxHide.bind(this)),t.addEventListener("touchstart",this.toolboxHide.bind(this)),this.isAndroid()&&t.addEventListener("contextmenu",this.disableContext),t.addEventListener("mousedown",this.mousedown.bind(this)),t.addEventListener("mouseup",this.mouseup.bind(this)),t.addEventListener("mousemove",this.mousemove.bind(this)),t.addEventListener("touchstart",this.mousedown.bind(this)),t.addEventListener("touchend",this.mouseup.bind(this)),t.addEventListener("touchmove",this.mousemove.bind(this)),this.hasEventListener=!0}async mousedown(t){j0=t.clientX,F0=t.clientY}async mouseup(t){Math.abs(j0-t.clientX)<3&&Math.abs(F0-t.clientY)<3&&await this.processMouseEvent(t)}async mousemove(t){await this.processMouseEvent(t)}unbindEvents(t,n){let i=t.ownerDocument;t.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),t.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),i.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),i.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),window.removeEventListener("resize",this.toolboxPlacement.bind(this)),i.removeEventListener("selectionchange",this.toolboxPlacement.bind(this)),t.removeEventListener("mousedown",this.toolboxHide.bind(this)),t.removeEventListener("touchstart",this.toolboxHide.bind(this)),this.isAndroid()&&t.removeEventListener("contextmenu",this.disableContext),t.removeEventListener("mousedown",this.mousedown.bind(this)),t.removeEventListener("mouseup",this.mouseup.bind(this)),t.removeEventListener("mousemove",this.mousemove.bind(this)),t.removeEventListener("touchstart",this.mousedown.bind(this)),t.removeEventListener("touchend",this.mouseup.bind(this)),t.removeEventListener("touchmove",this.mousemove.bind(this)),this.hasEventListener=!1}destroy(){this.toolboxHide();let t=this.navigator.iframes[0].contentDocument;t&&(this.unbindEvents(t.body,this),this.dom(t.body).removeClass(this.options.contextClass))}initializeToolbox(){let t=document.getElementById("highlight-toolbox-mode-colors"),n=document.getElementById("highlight-toolbox-mode-add"),i=["#fce300","#48e200","#00bae5","#157cf9","#6a39b7","#ea426a","#ff8500"],o=document.getElementById("colorIcon"),a=document.getElementById("actionIcon"),l=document.getElementById("dismissIcon"),u=document.getElementById("collapseIcon"),d=document.getElementById("highlightIcon"),h=this;if(l&&(l.innerHTML=nr.close,l.addEventListener("click",function(){h.toolboxMode("add")})),u&&(u.innerHTML=nr.close,u.addEventListener("click",function(){h.toolboxMode("add")})),o){o.style.position="relative",o.style.zIndex="20",i.forEach(w=>{let p=document.getElementById(w),m=document.getElementById(`c${w}`);p&&t?.contains(p)&&t.removeChild(p),n&&m&&n.contains(m)&&n.removeChild(m)});let y=[],b=[];if(o.addEventListener("click",function(){h.toolboxMode("colors")}),this.navigator.rights.enableAnnotations){let w=10;i.forEach(p=>{w--;let m=o?.cloneNode(!0),f=m.lastChild,g=Qe.hexToRgbChannels(p);f.style.backgroundColor="rgba("+[g.red,g.green,g.blue].join(",")+",.5)",m.id=`c${p}`,m.style.display="unset",m.style.position="relative",m.style.zIndex=`${w}`,m.style.marginLeft="-30px",b.push(m),n?.insertBefore(m,d)})}i.forEach(w=>{let p=o?.cloneNode(!0),m=p.lastChild;m.style.backgroundColor=w,p.id=w,p.style.position="relative",p.style.display="unset",y.push(p),o&&p.addEventListener("click",function(){h.setColor(w);let f=o?.lastChild;f&&(f.style.backgroundColor=w);let g=document.getElementById("highlightIcon"),v=document.getElementById("underlineIcon"),A=document.getElementById("noteIcon");(g?.getElementsByTagName?.("span").length??0)>0&&((g?.getElementsByTagName("span")[0]).style.background=h.getColor()),(v?.getElementsByTagName?.("span").length??0)>0&&((v?.getElementsByTagName("span")[0]).style.borderBottomColor=h.getColor()),(A?.getElementsByTagName?.("span").length??0)>0&&((A?.getElementsByTagName("span")[0]).style.borderBottomColor=h.getColor()),h.toolboxMode("add")}),t?.insertBefore(p,l)})}a&&a.addEventListener("click",function(){h.toolboxMode("action")}),h.toolboxMode("add")}toolboxMode(t){let n=document.getElementById("highlight-toolbox-mode-colors"),i=document.getElementById("highlight-toolbox-mode-add"),o=document.getElementById("highlight-toolbox-mode-edit"),a=document.getElementById("highlight-toolbox-mode-action");switch(t){case"colors":n&&(n.style.display="unset"),i&&(i.style.display="none"),o&&(o.style.display="none"),a&&(a.style.display="none");break;case"edit":n&&(n.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="unset"),a&&(a.style.display="none");break;case"action":n&&(n.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="none"),a&&(a.style.display="unset");break;default:n&&(n.style.display="none"),i&&(i.style.display="unset"),o&&(o.style.display="none"),a&&(a.style.display="none");break}}toolboxHide(){let t=document.getElementById("highlight-toolbox");t&&(t.style.display="none"),this.selectionMenuClosed()}toolboxShowDelayed(t){this.showTool(t.detail===1)}snapSelectionToWord(t=!1){let n=this,i=this.navigator.iframes[0].contentDocument;if(i){let a=n.dom(i.body)?.getSelection();if(n.dom(i.body)&&a&&!a?.isCollapsed){let h=function(g){let v=g.match(new RegExp("[^a-zA-Z0-9]+$"));return!v||!v.index?g:g.slice(0,v.index)},l=a.toString(),u=l.length-l.trimStart().length,d=l.length-l.trimEnd().length,y=l.length;var o=/[-!$%^&*()_+|~=`{}[\]:/;<>?,.@#]/;l=l.replace(o,""),u=y-l.trimStart().length,l=h(l),d=y-l.trimEnd().length;let b=document.createRange();t?(b.setStart(a.anchorNode,a.anchorOffset+u),b.setEnd(a.focusNode,a.focusOffset-d)):(b.setStart(a.anchorNode,a.anchorOffset),b.setEnd(a.focusNode,a.focusOffset));let w=b.collapsed;b.detach();let p=a.focusNode,m;t?(m=a.focusOffset-d,a.collapse(a.anchorNode,a.anchorOffset+u)):(m=a.focusOffset,a.collapse(a.anchorNode,a.anchorOffset));let f=["forward","backward"];w&&(f=["backward","forward"]),t?(a.modify("move",f[0],"character"),a.modify("move",f[1],"word"),a.extend(p,m),a.modify("extend",f[1],"character"),a.modify("extend",f[0],"word")):a.extend(p,m),this.selection(a.toString(),a)}return a}}toolboxShow(){if(this.activeAnnotationMarkerId===void 0){let t=this,n=document.getElementById("highlight-toolbox-mode-add"),i=this.dom(this.navigator.iframes[0].contentDocument?.body).getRange();if((!i||i.collapsed)&&n){getComputedStyle(n).display!=="none"&&t.toolboxHide();return}this.isIOS()&&setTimeout(function(){let o=t.navigator.iframes[0].contentDocument;if(o){let a=t.dom(o.body).getSelection();a.removeAllRanges(),setTimeout(function(){a.addRange(i);function l(h){let y={className:w=>Ai.indexOf(w)<0,idName:w=>Ai.indexOf(w)<0},b=t.navigator.iframes[0].contentDocument;if(b)return wn(h,b,y)}let u=t.navigator.iframes[0].contentWindow,d=Er(u,l);t.navigator.annotationModule?.annotator?.saveTemporarySelectionInfo(d)},5)}},100),this.toolboxPlacement(),this.toolboxHandler()}}toolboxPlacement(){let t=this.dom(this.navigator.iframes[0].contentDocument?.body).getRange();if(!t||t.collapsed)return;let n=t.getBoundingClientRect(),i=document.getElementById("highlight-toolbox");i&&(this.properties?.menuPosition===xl.TOP?(i.style.left="0px",i.style.transform="revert",i.style.width="100%",i.style.textAlign="center",i.style.position="absolute",i.style.setProperty("--content","revert")):this.properties?.menuPosition===xl.BOTTOM?(i.style.bottom="0px",i.style.left="0px",i.style.transform="revert",i.style.width="100%",i.style.textAlign="center",i.style.position="absolute",i.style.setProperty("--content","revert")):(this.navigator.view?.isPaginated()?i.style.top=n.top+(this.navigator.attributes?.navHeight??0)+"px":i.style.top=n.top+"px",i.style.left=(n.right-n.left)/2+n.left+"px"))}toolboxHandler(){let t=document.getElementById("highlight-toolbox");if(t&&getComputedStyle(t).display==="none"){t.style.display="block",this.navigator.view?.isPaginated()?t.style.position="absolute":t.style.position="relative",this.selectionMenuOpened();let i=this;i.toolboxMode("add");let o=document.getElementById("highlightIcon"),a=document.getElementById("collapseIcon"),l=document.getElementById("underlineIcon"),u=document.getElementById("noteIcon"),d=document.getElementById("colorIcon"),h=document.getElementById("speakIcon");if(this.navigator.rights.enableAnnotations){if(o&&(o.style.display="unset",d&&o.getElementsByTagName("span").length>0&&(o.getElementsByTagName("span")[0].style.background=this.getColor())),l&&(l.style.display="unset",d&&l.getElementsByTagName("span").length>0&&(l.getElementsByTagName("span")[0].style.borderBottomColor=this.getColor())),u&&(u.style.display="unset",d&&u.getElementsByTagName("span").length>0&&(u.getElementsByTagName("span")[0].style.borderBottomColor=this.getColor())),d){d.style.display="unset";let y=d.lastChild;y.style.backgroundColor=this.getColor()}if(o){let y=function(){i.doHighlight(!1,Ve.Highlight),i.toolboxHide(),o?.removeEventListener("click",y)},b=o.cloneNode(!0);o?.parentNode?.replaceChild(b,o),o=document.getElementById("highlightIcon"),o?.addEventListener("click",y)}if(l){let y=function(){i.doHighlight(!1,Ve.Underline),i.toolboxHide(),l?.removeEventListener("click",y)},b=l.cloneNode(!0);l?.parentNode?.replaceChild(b,l),l=document.getElementById("underlineIcon"),l?.addEventListener("click",y)}if(u){let y=function(){i.doHighlight(!1,Ve.Comment),i.toolboxHide(),u?.removeEventListener("click",y)},b=u.cloneNode(!0);u?.parentNode?.replaceChild(b,u),u=document.getElementById("noteIcon"),u?.addEventListener("click",y)}}else o&&o.style.setProperty("display","none"),l&&l.style.setProperty("display","none"),u&&u.style.setProperty("display","none"),d&&d.style.setProperty("display","none"),a&&a.style.setProperty("display","none");if(this.navigator.rights.enableTTS){if(h){let y=function(){h?.removeEventListener("click",y),i.speak()},b=h.cloneNode(!0);h?.parentNode?.replaceChild(b,h),h=document.getElementById("speakIcon"),h?.addEventListener("click",y)}}else h&&h.style.setProperty("display","none");(this.properties?.selectionMenuItems??[])&&(this.properties?.selectionMenuItems??[]).forEach(y=>{y.icon&&(y.icon.id=y.id);let b=document.getElementById(y.id),w=this;function p(){b?.removeEventListener("click",p);function m(g){let v={className:C=>Ai.indexOf(C)<0,idName:C=>Ai.indexOf(C)<0},A=w.navigator.iframes[0].contentDocument;if(A)return wn(g,A,v)}let f=w.navigator.iframes[0].contentWindow;if(f){let g=Er(f,m);if(g===void 0){let v=w.navigator.iframes[0].contentDocument;g=w.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(v)}if(g!==void 0)if(y.callback)y.callback(g.cleanText,g.range?.startContainer.parentElement);else{let v=y.highlight?.style,A=y.marker?y.marker:Ve.Custom;if(A===Ve.Custom&&w.navigator.rights.enableAnnotations||A===Ve.Bookmark&&w.navigator.rights.enableBookmarks){let C=w.navigator.iframes[0].contentDocument;if(C){let O=w.createHighlight(w.dom(C.body).getWindow(),g,y.highlight?.color,!0,A,y.icon,y.popup,v);w.options.onAfterHighlight(O,A),w.navigator.rights.enableAnnotations?w.navigator.annotationModule?.saveAnnotation(O[0]).then(E=>{y?.note&&E.highlight&&w.navigator.annotationModule?.api?.addCommentToAnnotation(E).then(T=>{w.navigator.annotationModule?.updateAnnotation(T).then(async()=>{$n.default.log("update highlight "+T.id)})})}):w.navigator.rights.enableBookmarks&&w.navigator.bookmarkModule?.saveAnnotation(O[0])}}}}w.callbackComplete()}if(b){let m=b.cloneNode(!0);b?.parentNode?.replaceChild(m,b),b=document.getElementById(y.id),b?.addEventListener("click",p)}})}}doHighlight(t,n){let i=this;function o(l){let u={className:h=>Ai.indexOf(h)<0,idName:h=>Ai.indexOf(h)<0},d=i.navigator.iframes[0].contentDocument;if(d)return wn(l,d,u)}let a=i.navigator.iframes[0].contentWindow;if(a){let l=Er(a,o);if(l===void 0){let u=i.navigator.iframes[0].contentDocument;l=this.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(u)}if(l){if(this.options.onBeforeHighlight(l)===!0){let u;u=this.getColor(),Qe.isHexColor(u)&&(u=Qe.hexToRgbChannels(u));let d=i.navigator.iframes[0].contentDocument;if(d){let h=this.createHighlight(i.dom(d.body).getWindow(),l,u,!0,n??Ve.Highlight);this.options.onAfterHighlight(h,n),this.navigator.rights.enableAnnotations&&n!==Ve.Bookmark?this.navigator.annotationModule?.saveAnnotation(h[0]):this.navigator.rights.enableBookmarks&&n===Ve.Bookmark&&this.navigator.bookmarkModule?.saveAnnotation(h[0])}}t||this.dom(this.navigator.iframes[0].contentDocument?.body).removeAllRanges()}else t||this.dom(this.navigator.iframes[0].contentDocument?.body).removeAllRanges()}}speak(){if(this.navigator.rights.enableTTS){let n=function(l){let u={className:h=>Ai.indexOf(h)<0,idName:h=>Ai.indexOf(h)<0},d=t.navigator.iframes[0].contentDocument;if(d)return wn(l,d,u)},t=this,i=t.navigator.iframes[0].contentWindow;if(i){let l=Er(i,n);if(l===void 0){let u=t.navigator.iframes[0].contentDocument;l=t.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(u)}l!==void 0&&this.navigator.ttsModule.speak(l,!0,()=>{})}let o=t.navigator.iframes[0].contentDocument;o&&t.dom(o.body).getSelection().removeAllRanges();let a=document.getElementById("highlight-toolbox");a&&(a.style.display="none"),this.selectionMenuClosed()}}stopReadAloud(){this.navigator.rights.enableTTS&&this.doneSpeaking()}callbackComplete(){this.toolboxHide();let t=this.navigator.iframes[0].contentDocument;t&&this.dom(t.body).removeAllRanges()}isOutsideViewport(t){let n=mt(document,"#iframe-wrapper"),i=n.scrollLeft,o=i+n.clientWidth,a=t.left+t.width,l=t.top+t.height,u=n.scrollTop,d=u+n.clientHeight,h=l<u,y=t.top>d,b=a<i,w=t.left>o;return h||y||b||w}isInsideViewport(t){let n=mt(document,"#iframe-wrapper"),i=n.scrollTop,o=i+n.clientHeight,a=t.top+20>=i,l=t.top<=o,u=n.scrollLeft,d=u+n.clientWidth,h=t.left+t.width,y=t.left>u,b=h<d;return a&&l&&y&&b}get visibleTextRects(){let t=this.navigator.iframes[0].contentDocument;if(t){let i=function(u,d=[]){let h=u.firstChild;for(;h;)h.nodeType===1&&i(h,d),h.nodeType===3&&h.textContent?.trim()&&d.push(h),h=h.nextSibling;return d},o=function(u){return i(u).map(h=>{let{top:y,height:b,left:w,width:p}=a(h);return{top:y,height:b,width:p,left:w,node:h,textContent:h.textContent??""}})},a=function(u){try{let d=document.createRange();d.selectNode(u);let h=d.getBoundingClientRect();return d.detach(),h}catch(d){$n.default.log("measureTextNode "+d),$n.default.log("measureTextNode "+u),$n.default.log(`${u.textContent}`)}},n=Gr(t,"body");return o(n).filter(u=>this.isInsideViewport(u))}return[]}doneSpeaking(t=!1){if(this.navigator.rights.enableTTS){this.toolboxHide();let n=this.navigator.iframes[0].contentDocument;n&&this.dom(n.body).removeAllRanges(),this.navigator.ttsModule.cancel(),t&&this.navigator.reload()}}normalizeHighlights(t){var n;return n=t.filter(function(i){return i.parentElement?i:null}),n=this.unique(n),n.sort(function(i,o){return i.offsetTop-o.offsetTop||i.offsetLeft-o.offsetLeft}),n}flattenNestedHighlights(t){let n,i=this;i.sortByDepth(t,!0);function o(){let a=!1;return t.forEach(function(l,u){let d=l.parentElement,h=d.previousSibling,y=d.nextSibling;i.isHighlight(d)&&(i.haveSameColor(d,l)?(d.replaceChild(l.firstChild,l),t[u]=d,a=!0):(l.nextSibling||(i.dom(l).insertBefore(y||d),a=!0),l.previousSibling||(i.dom(l).insertAfter(h||d),a=!0),d.hasChildNodes()||i.dom(d).remove()))}),a}do n=o();while(n)}mergeSiblingHighlights(t){let n=this;function i(o,a){return a&&a.nodeType===ha.ELEMENT_NODE&&n.haveSameColor(o,a)&&n.isHighlight(a)}t.forEach(function(o){let a=o.previousSibling,l=o.nextSibling;i(o,a)&&(n.dom(o).prepend(a.childNodes),n.dom(a).remove()),i(o,l)&&(n.dom(o).append(l.childNodes),n.dom(l).remove()),n.dom(o).normalizeTextNodes()})}setColor(t){this.options.color=t}getColor(){return this.options.color}isHighlight(t){return t&&t.nodeType===ha.ELEMENT_NODE&&t.hasAttribute(J5)}createWrapper(){let t=document.createElement("mark");return t.style.background="linear-gradient("+Qe.hexToRgbA(this.options.color)+", "+Qe.hexToRgbA(this.options.color)+")",t.className=this.options.highlightedClass,t}static isHexColor(t){return/^#([A-Fa-f0-9]{3}){1,2}$/.test(t)}static hexToRgbString(t){let n;return n=t.substring(1).split(""),n.length===3&&(n=[n[0],n[0],n[1],n[1],n[2],n[2]]),n="0x"+n.join(""),n}static hexToRgbChannels(t){let n;if(this.isHexColor(t))return n=this.hexToRgbString(t),{red:n>>16&255,green:n>>8&255,blue:n&255};throw new Error("Bad Hex")}static hexToRgbA(t){let n;if(this.isHexColor(t))return n=this.hexToRgbChannels(t),"rgba("+[n.red,n.green,n.blue].join(",")+",.5)";if(typeof t=="object"){let i=t;return"rgba("+[i.red,i.green,i.blue].join(",")+",.5)"}throw new Error("Bad Hex")}static hexToRgbAWithOpacity(t,n){let i;if(this.isHexColor(t))return i=this.hexToRgbChannels(t),"rgba("+[i.red,i.green,i.blue].join(",")+","+n+")";if(typeof t=="object"){let o=t;return"rgba("+[o.red,o.green,o.blue].join(",")+","+n+")"}throw new Error("Bad Hex")}resetHighlightBoundingStyle(t){t.style.outline="none",t.style.setProperty("background-color","transparent","important")}resetHighlightAreaStyle(t,n){let i=this.navigator.iframes[0].contentWindow?.document,o=t.parentNode&&t.parentNode.nodeType===Node.ELEMENT_NODE&&t.parentNode.getAttribute?t.parentNode.getAttribute("id"):void 0;if(o){let a=tn.find(l=>l.id===o);if(a){if(a.marker===Ve.Custom||a.marker===Ve.Bookmark)if(a.style?.hover){if(a.style?.hover)for(let d=0;d<a.style?.hover?.length;d++){let h=a.style?.hover[d];t.style.removeProperty(h.property)}let u="";if(a.style?.default)for(let d=0;d<a.style?.default?.length;d++){let h=a.style?.default[d];t.style.removeProperty(h.property),u+=`${h.property}: ${h.value} !${h.priority};`}t.setAttribute("style",`${t.getAttribute("style")}; ${u}`)}else if(a.style?.hoverClass){a.style?.hoverClass&&t.classList.remove(a.style?.hoverClass);let u="";a.style?.defaultClass&&t.classList.add(a.style?.defaultClass),t.setAttribute("style",`${t.getAttribute("style")}; ${u}`)}else if(Qe.isHexColor(a.color)){let u=Qe.hexToRgbChannels(a.color);t.style.setProperty("background-color",`rgba(${u.red}, ${u.green}, ${u.blue}, ${0})`,"important")}else t.classList.remove("hover");else if(a.marker===Ve.Underline||a.marker===Ve.Comment)if(typeof a.color=="object"){let u=a.color;t.style.setProperty("background-color",`rgba(${u.red}, ${u.green}, ${u.blue}, ${0})`,"important"),t.style.setProperty("border-bottom",`2px solid rgba(${u.red}, ${u.green}, ${u.blue}, ${1})`,"important")}else if(Qe.isHexColor(a.color)){let u=Qe.hexToRgbChannels(a.color);t.style.setProperty("background-color",`rgba(${u.red}, ${u.green}, ${u.blue}, ${0})`,"important"),t.style.setProperty("border-bottom",`2px solid rgba(${u.red}, ${u.green}, ${u.blue}, ${1})`,"important")}else t.classList.remove("hover");else if(typeof a.color=="object"){let u=a.color;t.style.setProperty("background-color",`rgba(${u.red}, ${u.green}, ${u.blue}, ${_r})`,"important")}else if(Qe.isHexColor(a.color)){let u=Qe.hexToRgbChannels(a.color);t.style.setProperty("background-color",`rgba(${u.red}, ${u.green}, ${u.blue}, ${_r})`,"important")}else t.classList.remove("hover");let l;if(i){let u=i.getElementById(n);u&&(l=u.querySelector(`#${a.id}`))}if(l){let u=l.getElementsByClassName(Al);if(u.length>0){let d=u.item(0).getElementsByClassName("icon-tooltip");d.length>0&&d.item(0).style.removeProperty("display")}}}}}setHighlightAreaStyle(t,n,i){for(let o of n){if(i.marker===Ve.Custom||i.marker===Ve.Bookmark)if(i.style?.hover){if(i.style?.default)for(let l=0;l<i.style?.default?.length;l++){let u=i.style?.default[l];o.style.removeProperty(u.property)}let a="";for(let l=0;l<i.style?.hover?.length;l++){let u=i.style?.hover[l];o.style.removeProperty(u.property),a+=`${u.property}: ${u.value} !${u.priority};`}o.setAttribute("style",`${o.getAttribute("style")}; ${a}`)}else if(i.style?.hoverClass){i.style?.defaultClass&&o.classList.remove(i.style?.defaultClass);let a="";o.classList.add(i.style?.hoverClass),o.setAttribute("style",`${o.getAttribute("style")}; ${a}`)}else if(Qe.isHexColor(i.color)){let a=Qe.hexToRgbChannels(i.color);o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${.1})`,"important")}else o.classList.add("hover");else if(i.marker===Ve.Underline||i.marker===Ve.Comment)if(typeof i.color=="object"){let a=i.color;o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${.1})`,"important"),o.style.setProperty("border-bottom",`2px solid rgba(${a.red}, ${a.green}, ${a.blue}, ${1})`,"important")}else if(Qe.isHexColor(i.color)){let a=Qe.hexToRgbChannels(i.color);o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${.1})`,"important"),o.style.setProperty("border-bottom",`2px solid rgba(${a.red}, ${a.green}, ${a.blue}, ${1})`,"important")}else o.classList.add("hover");else if(typeof i.color=="object"){let a=i.color;o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${H_})`,"important")}else if(Qe.isHexColor(i.color)){let a=Qe.hexToRgbChannels(i.color);o.style.setProperty("background-color",`rgba(${a.red}, ${a.green}, ${a.blue}, ${H_})`,"important")}else o.classList.add("hover");if(i.type!==it.Definition){let l=t.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER).querySelector(`#${i.id}`).getElementsByClassName(Al);if(l.length>0){let u=l.item(0).getElementsByClassName("icon-tooltip");u.length>0&&u.item(0).style.setProperty("display","block")}}}}setAndResetSearchHighlight(t,n){let i=this.navigator.iframes[0].contentWindow?.document,o=Array.from(i.getElementById(qe.R2_ID_SEARCH_CONTAINER).querySelectorAll(`.${Tn}`));for(let a of o){let l=a,u=l.parentNode&&l.parentNode.nodeType===Node.ELEMENT_NODE&&l.parentNode.getAttribute?l.parentNode.getAttribute("id"):void 0;if(n.forEach(d=>{if(u===d.id&&d){if(typeof d.color=="object"){let b=d.color;l.style.setProperty("background-color",`rgba(${b.red}, ${b.green}, ${b.blue}, ${_r})`,"important")}else if(Qe.isHexColor(d.color)){let b=Qe.hexToRgbChannels(d.color);l.style.setProperty("background-color",`rgba(${b.red}, ${b.green}, ${b.blue}, ${_r})`,"important")}else l.classList.remove("hover");let y=i.getElementById(qe.R2_ID_SEARCH_CONTAINER).querySelector(`#${d.id}`).getElementsByClassName(Al);if(y.length>0){let b=y.item(0).getElementsByClassName("icon-tooltip");b.length>0&&b.item(0).style.removeProperty("display")}}}),u===t.id&&t){if(typeof t.color=="object"){let y=t.color;l.style.setProperty("background-color",`rgba(${y.red}, ${y.green}, ${y.blue}, ${_r})`,"important")}else if(Qe.isHexColor(t.color)){let y=Qe.hexToRgbChannels(t.color);l.style.setProperty("background-color",`rgba(${y.red}, ${y.green}, ${y.blue}, ${_r})`,"important")}else l.classList.remove("hover");let h=i.getElementById(qe.R2_ID_SEARCH_CONTAINER).querySelector(`#${t.id}`).getElementsByClassName(Al);if(h.length>0){let y=h.item(0).getElementsByClassName("icon-tooltip");y.length>0&&y.item(0).style.removeProperty("display")}}}}isIOS(){return navigator.userAgent.match(/iPhone|iPad|iPod/i)!=null||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}isAndroid(){return navigator.userAgent.match(/Android/i)!=null}async processMouseEvent(t){let n=this.navigator.iframes[0].contentWindow?.document,i=t.clientX,o=t.clientY;if(!n||!n.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER)&&!n.getElementById(qe.R2_ID_SEARCH_CONTAINER)&&!n.getElementById(qe.R2_ID_PAGEBREAK_CONTAINER)&&!n.getElementById(qe.R2_ID_READALOUD_CONTAINER)&&!n.getElementById(qe.R2_ID_DEFINITIONS_CONTAINER))return;let a=this.navigator.view?.isPaginated(),l=n.body.getBoundingClientRect(),u=this.getScrollingElement(n),d=a?-u.scrollLeft:l.left,h=a?-u.scrollTop:l.top,y,b;for(let w=tn.length-1;w>=0;w--){let p=tn[w],m=n.getElementById(`${p.id}`);if(!m){let v=n.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER);v&&(m=v.querySelector(`#${p.id}`))}if(!m)continue;let f=!1,g=m.querySelectorAll(`.${Tn}`);for(let v of g){let A=v,C=A.rect.left+d,O=A.rect.top+h;if(i>=C&&i<C+A.rect.width&&o>=O&&o<O+A.rect.height){f=!0;break}}if(f){y=p,b=m;break}}if(!y||!b){for(let w in qe){let p=n.getElementById(w);if(p){let m=p.querySelectorAll(`.${Sl}`);for(let g of m)this.resetHighlightBoundingStyle(g);let f=Array.from(p.querySelectorAll(`.${Tn}`));for(let g of f)this.resetHighlightAreaStyle(g,w)}}return}if(b.getAttribute("data-click")){if((t.type==="mousemove"||t.type==="touchmove")&&b.parentElement?.style.display!=="none"){let w=Array.from(b.querySelectorAll(`.${Tn}`));for(let m in qe){let f=n.getElementById(m);if(f){let g=f.querySelectorAll(`.${Tn}`);for(let v of g)w.indexOf(v)<0&&this.resetHighlightAreaStyle(v,m)}}this.setHighlightAreaStyle(n,w,y);let p=b.querySelector(`.${Sl}`);for(let m in qe){let f=n.getElementById(m);if(f){let g=f.querySelectorAll(`.${Sl}`);for(let v of g)(!p||v!==p)&&this.resetHighlightBoundingStyle(v)}}}else if((t.type==="mouseup"||t.type==="click"||t.type==="touchup")&&b.parentElement?.style.display!=="none"){let w={highlight:y};$n.default.log(JSON.stringify(w));let p=this,m;if(p.navigator.rights.enableAnnotations?m=await this.navigator.annotationModule?.getAnnotation(w.highlight):p.navigator.rights.enableBookmarks&&(m=await this.navigator.bookmarkModule?.getAnnotation(w.highlight)),w.highlight.type===it.Annotation&&this.navigator.annotationModule?.api?.selectedAnnotation(m).then(async()=>{}),m?.id){$n.default.log("selected highlight "+m.id),p.lastSelectedHighlight=m.id;let f=document.getElementById("highlight-toolbox");if(f)if(f.style.top=t.clientY+(this.navigator.attributes?.navHeight??0)+"px",f.style.left=t.clientX+"px",getComputedStyle(f).display==="none"){let A=function(){p.navigator.annotationModule?.api?.addCommentToAnnotation(m).then(M=>{p.navigator.annotationModule?.updateAnnotation(M).then(async()=>{$n.default.log("update highlight "+M.id),f&&(f.style.display="none"),p.selectionMenuClosed()}),f&&(f.style.display="none"),p.selectionMenuClosed(),C?.removeEventListener("click",A,!1)})},E=function(){p.navigator.rights.enableAnnotations?p.navigator.annotationModule?.deleteSelectedHighlight(m).then(async()=>{$n.default.log("delete highlight "+m.id),f&&(f.style.display="none"),p.selectionMenuClosed()}):p.navigator.rights.enableBookmarks&&p.navigator.bookmarkModule?.deleteSelectedHighlight(m).then(async()=>{$n.default.log("delete highlight "+m.id),f&&(f.style.display="none"),p.selectionMenuClosed()})};f.style.display="block",this.toolboxMode("edit");let g=document.getElementById("colorIcon"),v=document.getElementById("highlightIcon");g&&(g.style.display="none"),v&&(v.style.display="none");let C=document.getElementById("commentIcon"),O=document.getElementById("cloneCommentIcon");if(O){let M=O.parentElement;M&&M.removeChild(O)}if(C){C.style.display="none";let M=C.cloneNode(!0),j=C.parentElement;M.style.display="unset",M.id="cloneCommentIcon",M.addEventListener("click",A,!1),j&&j.append(M)}let T=document.getElementById("deleteIcon"),I=document.getElementById("cloneDeleteIcon");if(I){let M=I.parentElement;M&&M.removeChild(I)}if(T){T.style.display="none";let M=T.cloneNode(!0),j=T.parentElement;M.style.display="unset",M.id="cloneDeleteIcon",M.addEventListener("click",E,!1),j&&j.append(M)}}else f.style.display="none",this.selectionMenuClosed(),f.offsetWidth,f.style.display="block"}else{b.dataset.definition&&new wl(this.navigator).showPopup(b.dataset.definition,t);let f=this.navigator.definitionsModule?.properties?.definitions?.filter(g=>g.order===Number(b?.dataset.order))[0];$n.default.log(f),this.navigator.definitionsModule?.api?.click&&(this.navigator.definitionsModule.api?.click(D0.omit(f,"callbacks"),D0.omit(y,"definition")),this.navigator.emit("definition.click",f,y))}}}}async prepareContainers(t){for(let n in qe)await this.ensureHighlightsContainer(t,n)}async ensureHighlightsContainer(t,n){let i=t.document;if(!i.getElementById(n)){let o=i.createElement("div");o.setAttribute("id",n),n!==qe.R2_ID_GUTTER_RIGHT_CONTAINER&&o.style.setProperty("pointer-events","none"),this.navigator.view?.layout==="fixed"&&(o.style.setProperty("position","absolute"),o.style.setProperty("top","0"),o.style.setProperty("left","0")),i.body&&i.body.append(o),(await this.layerSettings.getProperty(n))?.value===!1&&(o.style.display="none")}return i.getElementById(n)}hideAllhighlights(t){this.removeAllChildNodes(t.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER)),this.removeAllChildNodes(t.getElementById(qe.R2_ID_SEARCH_CONTAINER)),this.removeAllChildNodes(t.getElementById(qe.R2_ID_READALOUD_CONTAINER)),this.removeAllChildNodes(t.getElementById(qe.R2_ID_PAGEBREAK_CONTAINER)),this.removeAllChildNodes(t.getElementById(qe.R2_ID_DEFINITIONS_CONTAINER))}destroyAllhighlights(t){this.hideAllhighlights(t),tn.splice(0,tn.length)}removeAllChildNodes(t){for(;t.firstChild;)t.removeChild(t.firstChild)}destroyHighlights(t){let n=this.navigator.iframes[0].contentWindow?.document;if(n){let i;switch(t){case it.ReadAloud:i=n.getElementById(qe.R2_ID_READALOUD_CONTAINER),i&&this.removeAllChildNodes(i);break;case it.Search:i=n.getElementById(qe.R2_ID_SEARCH_CONTAINER),i&&this.removeAllChildNodes(i);break;case it.PageBreak:i=n.getElementById(qe.R2_ID_PAGEBREAK_CONTAINER),i&&this.removeAllChildNodes(i);break;case it.Definition:i=n.getElementById(qe.R2_ID_DEFINITIONS_CONTAINER),i&&this.removeAllChildNodes(i);break;case it.LineFocus:i=n.getElementById(qe.R2_ID_LINEFOCUS_CONTAINER),i&&this.removeAllChildNodes(i);break;case it.Comment:i=n.getElementById(qe.R2_ID_GUTTER_RIGHT_CONTAINER),i&&this.removeAllChildNodes(i);break;default:i=n.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER),i&&this.removeAllChildNodes(i),tn.splice(0,tn.length);break}}}destroyHighlight(t,n){if(!t)return;let i=-1;tn.find((l,u)=>(i=u,l.id===n))&&i>=0&&i<tn.length&&tn.splice(i,1);let a=t.getElementById(n);a&&this.removeAllChildNodes(a)}createHighlight(t,n,i,o,a,l,u,d,h,y){try{let b=`${n.rangeInfo.startContainerElementCssSelector}${n.rangeInfo.startContainerChildTextNodeIndex}${n.rangeInfo.startOffset}${n.rangeInfo.endContainerElementCssSelector}${n.rangeInfo.endContainerChildTextNodeIndex}${n.rangeInfo.endOffset}`,w=Fi.hash(b),p=(y||"R2_HIGHLIGHT_")+w;this.destroyHighlight(t.document,p);let m=`rgb(${ls.red}, ${ls.green}, ${ls.blue})`,f={color:i||m,id:p,pointerInteraction:o,selectionInfo:n,marker:a,icon:l,popup:u,style:d,type:h||it.Annotation};(h===it.Annotation||h===it.Definition||h===void 0)&&tn.push(f);let g=this.createHighlightDom(t,f);return f.position=parseInt((g?.hasChildNodes()?g.childNodes[0]:g).style.top.replace("px","")),[f,g]}catch(b){throw"Can't create highlight: "+b}}createHighlightDom(t,n){let i=t.document,o=Jd(i,n.selectionInfo.rangeInfo);if(!o)return;for(let N in qe)this.ensureHighlightsContainer(t,N);let a=i.createElement("div");a.setAttribute("id",n.id),a.setAttribute("class",F_),a.style.setProperty("pointer-events","none"),n.pointerInteraction&&a.setAttribute("data-click","1");let l=this.navigator.view?.isPaginated();l?i.body.style.position="revert":i.body.style.position="relative";let u=i.body.getBoundingClientRect(),d=this.getScrollingElement(i),h=l?-d.scrollLeft:u.left,y=l?-d.scrollTop:u.top,b=1,w=!1,p=!1,f=w||p||!1;$n.default.debug(f),f=!0;let g=zd(o,f),v=3,A=2,C=3,O=0,E=24,T,I;for(let N of g){let q=i.createElement("div");q.setAttribute("class",Tn),q.dataset.marker=""+n.marker;let z="";if(w&&n.marker!==Ve.Custom&&n.marker!==Ve.Bookmark&&n.marker!==Ve.Comment){let x=n.color;Qe.isHexColor(x)&&(x=Qe.hexToRgbChannels(x)),z+=`border-bottom: ${A*b}px solid rgba(${x.red}, ${x.green}, ${x.blue}, ${_r}) !important`}if(n.marker===Ve.Custom||n.marker===Ve.Bookmark)if(n.style?.default){for(let x=0;x<n.style?.default?.length;x++){let R=n.style?.default[x];z+=`${R.property}: ${R.value} !${R.priority};`}q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; ${z}`)}else n.style?.defaultClass&&(q.classList.add(n.style?.defaultClass),q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; ${z}`));else if(n.marker===Ve.Underline||n.marker===Ve.Comment)if(typeof n.color=="object"){let x=n.color;q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; background-color: rgba(${x.red}, ${x.green}, ${x.blue}, ${0}) !important; ${z}`),q.style.setProperty("border-bottom",`2px solid rgba(${x.red}, ${x.green}, ${x.blue}, ${1})`,"important")}else if(Qe.isHexColor(n.color)){let x=Qe.hexToRgbChannels(n.color);q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; background-color: rgba(${x.red}, ${x.green}, ${x.blue}, ${0}) !important; ${z}`),q.style.setProperty("border-bottom",`2px solid rgba(${x.red}, ${x.green}, ${x.blue}, ${1})`,"important")}else q.setAttribute("style",`border-radius: ${v}px !important; ${z}`);else if(typeof n.color=="object"){let x=n.color;q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; background-color: rgba(${x.red}, ${x.green}, ${x.blue}, ${_r}) !important; ${z}`)}else if(Qe.isHexColor(n.color)){let x=Qe.hexToRgbChannels(n.color);q.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${v}px !important; background-color: rgba(${x.red}, ${x.green}, ${x.blue}, ${_r}) !important; ${z}`)}else q.setAttribute("style",`border-radius: ${v}px !important; ${z}`);q.style.setProperty("pointer-events","none"),q.style.position="absolute",q.scale=b,q.rect={height:N.height,left:N.left-h,top:N.top-y,width:N.width},n.pointerInteraction&&(q.setAttribute("data-click","1"),q.tabIndex=0),q.style.width=`${q.rect.width*b}px`,q.style.height=`${q.rect.height*b}px`,q.style.left=`${q.rect.left*b}px`,q.style.top=`${q.rect.top*b}px`,a.append(q);let ne=parseInt(q.style.top.replace("px",""));if((ne<O||O===0)&&(O=ne),E=parseInt(q.style.height.replace("px","")),p){let x=i.createElement("div");x.setAttribute("class",Tn);let R=n.color;Qe.isHexColor(R)&&(R=Qe.hexToRgbChannels(R)),x.setAttribute("style",`background-color: rgba(${R.red}, ${R.green}, ${R.blue}, ${_r}) !important;`),x.style.setProperty("pointer-events","none"),x.style.position="absolute",x.scale=b,x.rect={height:N.height,left:N.left-h,top:N.top-y,width:N.width},x.style.width=`${x.rect.width*b}px`,x.style.height=`${C*b}px`,x.style.left=`${x.rect.left*b}px`,x.style.top=`${(x.rect.top+x.rect.height/2-C/2)*b}px`,a.append(x)}let oe=this.navigator.iframes[0].contentWindow?.innerWidth,ae=parseInt(getComputedStyle(i.documentElement).getPropertyValue("column-count")),te=parseInt(getComputedStyle(i.documentElement).getPropertyValue("column-width")),le=parseInt(getComputedStyle(i.body).getPropertyValue("padding-left")),xe=oe/(ae||1);xe<te&&(xe=oe),l||(xe=parseInt(getComputedStyle(i.body).width.replace("px","")));let fe=this.navigator.settings.fontSize/100,J=20*fe;fe<=1&&(J=-60);let D=0*fe;fe<=1&&(D=-60),T=Math.floor(N.left/xe)*xe+xe-(E<40?40:E)+D,I=Math.floor(N.left/xe)*xe+(E<40?40:E)-J;let k=parseInt(this.navigator.iframes[0].contentDocument.documentElement.style.getPropertyValue("--USER__pageMargins"));k>=2&&(I=I+le/ae,T=T-le/ae),l||(T=parseInt(getComputedStyle(this.navigator.iframes[0].contentDocument?.body).width.replace("px","")),I=parseInt(getComputedStyle(this.navigator.iframes[0].contentDocument?.body).width.replace("px",""))-xe,k>=2&&(I=I+le/2,T=T-le/2))}let M=o.getBoundingClientRect(),j=i.createElement("div");j.setAttribute("class",Sl),j.style.setProperty("pointer-events","none"),j.style.position="absolute",j.scale=b,j.rect={height:M.height,left:M.left-h,top:M.top-y,width:M.width},j.style.width=`${j.rect.width*b}px`,j.style.height=`${j.rect.height*b}px`,j.style.left=`${j.rect.left*b}px`,j.style.top=`${j.rect.top*b}px`,a.append(j);let U=i.createElement("div");if(U.setAttribute("class",Al),n.icon?.position==="left")U.setAttribute("style",`position: absolute;top:${O}px;left:${I+this.navigator.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${E}px; width:${E}px;`);else if(n.icon?.position==="inline")U.setAttribute("style",`position: absolute;top:${O-E/2}px;left:${parseInt(j.style.left.replace("px",""))+parseInt(j.style.width.replace("px",""))-E/2}px;height:${E}px; width:${E}px;`);else if(n.icon?.position==="center"){let q=E/3*2;U.setAttribute("style",`position: absolute;top:${O}px;left:${parseInt(j.style.left.replace("px",""))+parseInt(j.style.width.replace("px",""))-q}px;height:${E}px; width:${E}px;`)}else n.note&&n.marker!==Ve.Custom&&n.marker!==Ve.Bookmark&&n.marker!==Ve.Comment&&n.marker!==Ve.Highlight&&n.marker!==Ve.Underline?U.setAttribute("style",`position: absolute;top:${O-E/2}px;left:${parseInt(j.style.left.replace("px",""))+parseInt(j.style.width.replace("px",""))-E/2}px;height:${E}px; width:${E}px;`):n.note&&n.marker===Ve.Comment||n.marker===Ve.Highlight||n.marker===Ve.Underline?U.setAttribute("style",`position: absolute;top:${O}px;left:${T+this.navigator.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${E}px; width:${E}px;`):U.setAttribute("style",`position: absolute;top:${O}px;left:${T+this.navigator.iframes[0].contentDocument?.scrollingElement?.scrollLeft}px;height:${E}px; width:${E}px;`);if(n.marker===Ve.Custom||n.marker===Ve.Bookmark)n.icon?.class?(U.classList.add(n.icon?.class),U.id=n.icon?.id):n.icon?.svgPath?U.innerHTML=ua(`${n.icon?.id}`,`${n.icon?.title}`,`${n.icon?.svgPath}`,"icon open",E,`${n.icon?.color} !important`):n.icon?.title&&(U.innerHTML=n.icon?.title);else if(n.note){let N=n.color;Qe.isHexColor(N)&&(N=Qe.hexToRgbChannels(N)),n.marker===Ve.Comment||n.marker===Ve.Highlight||n.marker===Ve.Underline?U.innerHTML=ua("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="14"/>',"icon open",E/2,`rgba(${N.red}, ${N.green}, ${N.blue}, 1) !important`):U.innerHTML=ua("note-icon","Note",'<rect fill="none" height="24" width="24"/><path d="M19,5v9l-5,0l0,5H5V5H19 M19,3H5C3.9,3,3,3.9,3,5v14c0,1.1,0.9,2,2,2h10l6-6V5C21,3.9,20.1,3,19,3z M12,14H7v-2h5V14z M17,10H7V8h10V10z"/>',"icon open",E,`rgba(${N.red}, ${N.green}, ${N.blue}, 1) !important`)}U.style.setProperty("pointer-events","all");let B=this;if(n.type!==it.PageBreak&&n.type!==it.Definition&&U.addEventListener("click",async function(N){let q;B.navigator.rights.enableAnnotations?(q=await B.navigator.annotationModule?.getAnnotationByID(n.id),B.navigator.annotationModule?.api?.selectedAnnotation(q).then(async()=>{})):B.navigator.rights.enableBookmarks&&(q=await B.navigator.bookmarkModule?.getAnnotationByID(n.id)),$n.default.log("selected highlight "+q.id),B.lastSelectedHighlight=q.id;let z=document.getElementById("highlight-toolbox");if(z)if(z.style.top=N.clientY+(B.navigator.attributes?.navHeight??0)+"px",z.style.left=N.clientX+"px",getComputedStyle(z).display==="none"){let xe=function(){B.navigator.rights.enableAnnotations?B.navigator.annotationModule?.deleteSelectedHighlight(q).then(async()=>{$n.default.log("delete highlight "+q.id),z.style.display="none",B.selectionMenuClosed()}):B.navigator.rights.enableBookmarks&&B.navigator.bookmarkModule?.deleteSelectedHighlight(q).then(async()=>{$n.default.log("delete highlight "+q.id),z.style.display="none",B.selectionMenuClosed()})};z.style.display="block",B.toolboxMode("edit");let oe=document.getElementById("colorIcon"),ae=document.getElementById("highlightIcon");oe&&(oe.style.display="none"),ae&&(ae.style.display="none");let te=document.getElementById("commentIcon"),le=document.getElementById("cloneCommentIcon");if(le){let D=le.parentElement;D&&D.removeChild(le)}te&&(te.style.display="none");let fe=document.getElementById("deleteIcon"),J=document.getElementById("cloneDeleteIcon");if(J){let D=J.parentElement;D&&D.removeChild(J)}if(fe){fe.style.display="none";let D=fe.cloneNode(!0),k=fe.parentElement;D.style.display="unset",D.id="cloneDeleteIcon",D.addEventListener("click",xe,!1),k&&k.append(D)}}else z.style.display="none",B.selectionMenuClosed(),z.offsetWidth,z.style.display="block";let ne=Array.from(a.querySelectorAll(`.${Tn}`));B.setHighlightAreaStyle(i,ne,n)}),n.note){let N=document.createElement("span");N.innerHTML=n.note,N.className="icon-tooltip",n.marker===Ve.Custom||n.marker===Ve.Bookmark?(n.popup?.background&&N.style.setProperty("background",n.popup.background),n.popup?.textColor&&N.style.setProperty("color",n.popup.textColor),n.popup?.class&&N.classList.add(n.popup.class)):(N.style.setProperty("background","lightyellow"),N.style.setProperty("color","black"))}switch((n.note||n.marker===Ve.Custom||n.marker===Ve.Bookmark)&&a.append(U),n.type){case it.Search:i.getElementById(qe.R2_ID_SEARCH_CONTAINER).append(a);break;case it.ReadAloud:i.getElementById(qe.R2_ID_READALOUD_CONTAINER).append(a);break;case it.PageBreak:i.getElementById(qe.R2_ID_PAGEBREAK_CONTAINER).append(a);break;case it.Definition:i.getElementById(qe.R2_ID_DEFINITIONS_CONTAINER).append(a);break;default:i.getElementById(qe.R2_ID_HIGHLIGHTS_CONTAINER).append(a);break}return a}addSelectionMenuItem(t){(this.properties?.selectionMenuItems??[])&&(this.properties?.selectionMenuItems??[]).push(t)}};var Z_=nt(K0());H();var r8=nt(Jt());var Co={className:r=>!0,idName:r=>!0,tagName:r=>!0};var Q_=nt(Yd()),Ui=nt(Jt());H();var X_=nt(Jt()),cs;(function(n){n.BookmarkCreated="BookmarkCreated",n.HighlightCreated="HighlightCreated"})(cs||(cs={}));var Tl=class{constructor(t,n,i){this.currSeconds=0;this.publication=t,this.properties=n,this.api=i}static async create(t){let n=new this(t.publication,t,t.api);return await n.start(),n}async start(){this.startResearchSession()}async stop(){X_.default.log("Consumption module stop"),this.endResearchSession()}initialize(){let t=this.navigator.iframes[0].contentWindow;if(t){let n=this;t.onload=function(){n.resetTimer()},t.onmousemove=function(){n.resetTimer()},t.onmousedown=function(){n.resetTimer()},t.ontouchstart=function(){n.resetTimer()},t.onclick=function(){n.resetTimer()},t.onkeypress=function(){n.resetTimer()}}}trackAction(t,n){this.api?.actionTracked(t,n)}startReadingSession(t){if(this.firstReadingLocator&&this.lastReadingLocator){let n=this.lastReadingLocator.locations.totalProgression-this.firstReadingLocator.locations.totalProgression,i=(new Date().getTime()-this.startReadingTimer.getTime())/1e3;this.readingSessions.push({lastLocator:this.lastReadingLocator,firstLocator:this.firstReadingLocator,time:i,progress:Math.round(n*100)})}this.firstReadingLocator=t,this.startReadingTimer=new Date}continueReadingSession(t){this.properties.enableTrackingSession&&(this.startResearchTimer===void 0&&this.startResearchSession(),(this.lastReadingLocator===void 0||this.lastReadingLocator.locations.totalProgression<t.locations.totalProgression)&&(this.lastReadingLocator=t),this.firstReadingLocator===void 0&&(this.firstReadingLocator=t),this.startReadingTimer===void 0&&(this.startReadingTimer=new Date))}startResearchSession(){if(this.properties.enableTrackingSession){this.startResearchTimer=new Date,this.readingSessions=[],clearInterval(this.readingSessionsInterval);let t=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;this.researchSessionId=this.api?.startResearchSession(this.readingSessions,Math.round(t));let n=this;this.readingSessionsInterval=setInterval(function(){n.updateResearchSession()},this.properties.updateSessionInterval*1e3)}}updateResearchSession(){if(this.properties.enableTrackingSession){let t=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;this.api?.updateResearchSession(this.researchSessionId,this.readingSessions,Math.round(t))}}endResearchSession(){if(this.properties.enableTrackingSession){if(this.firstReadingLocator&&this.lastReadingLocator){let n=this.lastReadingLocator.locations.totalProgression-this.firstReadingLocator.locations.totalProgression,i=(new Date().getTime()-this.startReadingTimer.getTime())/1e3;this.readingSessions.push({lastLocator:this.lastReadingLocator,firstLocator:this.firstReadingLocator,time:i,progress:Math.round(n*100)})}let t=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;this.api?.updateResearchSession(this.researchSessionId,this.readingSessions,Math.round(t)),this.api?.endResearchSession(this.researchSessionId,this.readingSessions,Math.round(t)),this.researchSessionId=void 0,this.readingSessions=[],this.startResearchTimer=void 0,clearInterval(this.readingSessionsInterval),clearInterval(this.timer)}}startIdleTimer(){this.currSeconds++,this.currSeconds===this.properties.idleTimeout&&(this.api?.idleSince(this.currSeconds),this.startResearchTimer!==void 0?this.updateResearchSession():this.startResearchSession()),this.currSeconds===this.properties.idleTimeout+this.properties.responseTimeout&&this.endResearchSession()}resetTimer(){clearInterval(this.timer),this.currSeconds=0;let t=this;this.timer=setInterval(function(){t.startIdleTimer()},1e3)}};var us=class{constructor(t,n,i,o,a,l,u,d){this.hide=Ie(document,"#menu-button-hide");this.show=Ie(document,"#menu-button-show");this.annotator=t,this.rights=n,this.publication=i,this.headerMenu=d,this.initialAnnotations=o,this.highlighter=l,this.properties=a,this.api=u}static async create(t){let n=new this(t.annotator,t.rights||{enableAnnotations:!1,enableTTS:!1},t.publication,t.initialAnnotations||null,t,t.highlighter,t.api,t.headerMenu);return await n.start(),n}async stop(){Ui.default.log("Annotation module stop")}async start(){if(this.headerMenu&&(this.highlightsView=Ie(this.headerMenu,"#container-view-highlights")),this.initialAnnotations){var t=this.initialAnnotations.highlights||null;t&&this.annotator?.initAnnotations(t)}setTimeout(()=>{this.properties?.hideLayer?this.navigator.hideLayer("highlights"):this.navigator.showLayer("highlights")},10)}hideAnnotationLayer(){let t=this.navigator.iframes[0].contentDocument;if(t){let n=Ie(t,"#R2_ID_HIGHLIGHTS_CONTAINER");n&&(n.style.display="none")}this.show&&this.hide&&(this.show.style.display="block",this.hide.style.display="none")}showAnnotationLayer(){let t=this.navigator.iframes[0].contentDocument;if(t){let n=Ie(t,"#R2_ID_HIGHLIGHTS_CONTAINER");n&&(n.style.display="block")}this.show&&this.hide&&(this.show.style.display="none",this.hide.style.display="block")}async handleResize(){setTimeout(async()=>{await this.drawHighlights(),await this.showHighlights()},200)}initialize(){return new Promise(async t=>{await document.fonts.ready,this.rights.enableAnnotations&&setTimeout(()=>{this.drawHighlights(),this.showHighlights(),Ee(this.navigator.iframes[0].contentDocument?.body,"click",this.click.bind(this))},300),t(null)})}click(t){if(this.activeAnnotationMarkerId){let n=this.highlighter?.properties?.selectionMenuItems?.filter(i=>i.id===this.activeAnnotationMarkerId);if(n&&n?.length>0){let i=Q_.cloneDeep(n[0]);i.marker=Ve.Custom,this.activeAnnotationMarkerPosition&&(i.icon.position=this.activeAnnotationMarkerPosition),i.highlight.style.default=null,i.highlight.style.hover=null;let o=this.navigator.iframes[0].contentDocument;if(o){let h=function(b){try{let w=d.navigator.iframes[0].contentDocument;return w?wn(b,w,Co):""}catch(w){return Ui.default.log("uniqueCssSelector:"),Ui.default.error(w),""}},a=this.highlighter?.dom(o.body).getSelection(),l=a.getRangeAt(0),u=a.anchorNode;l.setStart(u,l.startOffset),l.setEnd(u,l.endOffset+1),a.removeAllRanges(),a.addRange(l);let d=this,y=Xr(l,h);if(a.removeAllRanges(),y){let b={rangeInfo:y},w=this.navigator.highlighter?.createHighlight(this.navigator.highlighter?.dom(o.body).getWindow(),b,i.highlight.color,!0,Ve.Bookmark,i.icon,i.popup,i.highlight.style);w&&this.saveAnnotation(w[0]).then(p=>{Ui.default.log("saved bookmark "+p.id)})}o.getSelection()?.removeAllRanges()}}}}async scrollToHighlight(t){Ui.default.log("still need to scroll to "+t);var n=await this.annotator?.getAnnotationElement(t,this.navigator.iframes[0].contentWindow);n.scrollIntoView({block:"center",behavior:"smooth"})}async updateLocalHighlight(t){if(this.annotator){let n=await this.annotator.deleteAnnotation(t.id),i=await this.addAnnotation(t);return Ui.default.log("Highlight deleted "+JSON.stringify(n)),Ui.default.log("Highlight added "+JSON.stringify(i)),await this.showHighlights(),await this.drawHighlights(),i}else return new Promise(n=>n(null))}async deleteLocalHighlight(t){if(this.annotator){var n=await this.annotator.deleteAnnotation(t);return Ui.default.log("Highlight deleted "+JSON.stringify(n)),await this.showHighlights(),await this.drawHighlights(),n}else return new Promise(i=>i(null))}async deleteAnnotation(t){await this.deleteLocalHighlight(t.id)}async addAnnotation(t){await this.annotator?.saveAnnotation(t),await this.showHighlights(),await this.drawHighlights()}async deleteHighlight(t){this.api?.deleteAnnotation?this.api?.deleteAnnotation(t).then(async()=>{this.deleteLocalHighlight(t.id)}):this.deleteLocalHighlight(t.id)}async deleteSelectedHighlight(t){this.api?.deleteAnnotation?this.api.deleteAnnotation(t).then(async()=>{this.deleteLocalHighlight(t.id)}):this.deleteLocalHighlight(t.id)}async updateAnnotation(t){this.api?.updateAnnotation?this.api.updateAnnotation(t).then(async()=>{this.updateLocalHighlight(t)}):this.updateLocalHighlight(t)}async saveAnnotation(t){if(this.annotator){var n=this.publication.getTOCItem(this.navigator.currentChapterLink.href);this.navigator.currentTocUrl&&(n=this.publication.getTOCItem(this.navigator.currentTocUrl)),n===void 0&&(n=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href));let i=this.navigator.view?.getCurrentPosition(),o=this.navigator.iframes[0].contentDocument;if(o){let a=Gr(o,"body"),l=t.position?t.position/a.scrollHeight:i,u=(0,Z_.v4)(),d;if(n){let h=n.Href;if(h.indexOf("#")>0&&(h=h.slice(0,h.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let y=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),b=Math.ceil((l??0)*(y.length-1)),w=y[b];d=Yt(et({},w),{id:u,href:h,created:new Date,title:this.navigator.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}})}else d={id:u,href:h,locations:{progression:l},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}}}if(d)if(this.navigator.consumptionModule?.trackAction(d,cs.HighlightCreated),this.api?.addAnnotation)try{let h=await this.api.addAnnotation(d),y=await this.annotator.saveAnnotation(h);return await this.showHighlights(),await this.drawHighlights(),new Promise(b=>b(y))}catch(h){await this.showHighlights(),await this.drawHighlights()}else{let h=await this.annotator.saveAnnotation(d);return await this.showHighlights(),await this.drawHighlights(),new Promise(y=>y(h))}}}return new Promise(i=>i(null))}getAnnotations(){let t=[];return this.annotator&&(t=this.annotator.getAnnotations()),t}showHighlights(){let t=[];this.annotator&&(t=this.annotator.getAnnotations(),t&&(t=t.filter(n=>n.highlight.marker!==Ve.Bookmark),t.forEach(n=>{tn.push(n.highlight)}))),this.highlightsView&&this.createTree(Si.Annotation,t,this.highlightsView)}async drawHighlights(){if(this.rights.enableAnnotations&&this.highlighter){if(this.api){let n=[];if(this.annotator&&(n=this.annotator.getAnnotationsByChapter(this.navigator.currentLocator().href)),this.highlighter&&n&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.highlighter.destroyHighlights(it.Annotation);for(let i of n){tn.push(i.highlight);let o=i,a=this.navigator.currentChapterLink.href;var t=this.publication.getTOCItem(a);if(this.navigator.currentTocUrl!==void 0&&(t=this.publication.getTOCItem(this.navigator.currentTocUrl)),t===null&&(t=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),t){let l=t.Href;l.indexOf("#")>0&&(l=l.slice(0,l.indexOf("#"))),o.href===l&&(await this.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,i.highlight),setTimeout(async()=>{if(o.highlight?.marker===Ve.Underline){let u=await this.annotator?.getAnnotationPosition(i.id,this.navigator.iframes[0].contentWindow),d='<div class="comment" style="top: '+u+'px;width:20px"></div>',h=document.createElement("div");h.innerHTML=d;let y=h.childNodes[0],b=document.createElement("i");b.innerHTML="sticky_note_2",b.className="material-icons",b.style.color=o.highlight.color,y.appendChild(b),Ee(h,"click",w=>{w.preventDefault(),w.stopPropagation(),this.scrollToHighlight(o.id)})}},100))}}}}else{let n=[];if(this.annotator&&(n=this.annotator.getAnnotationsByChapter(this.navigator.currentLocator().href)),this.highlighter&&n&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.highlighter.destroyHighlights(it.Annotation);for(let i of n){tn.push(i.highlight);let o=i,a=this.navigator.currentChapterLink.href,l=this.publication.getTOCItem(a);if(this.navigator.currentTocUrl&&(l=this.publication.getTOCItem(this.navigator.currentTocUrl)),l===null&&(l=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),l){let u=l.Href;u.indexOf("#")>0&&(u=u.slice(0,u.indexOf("#"))),o.href===u&&(await this.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,i.highlight),setTimeout(async()=>{if(o.highlight?.marker===Ve.Underline){let d=await this.annotator?.getAnnotationPosition(i.id,this.navigator.iframes[0].contentWindow),h='<div class="comment" style="top: '+d+"px;background: "+o.highlight?.color+';width:20px"></div>',y=document.createElement("div");y.innerHTML=h,y.childNodes[0].innerHTML=nr.note,Ee(y,"click",b=>{b.preventDefault(),b.stopPropagation(),this.scrollToHighlight(o.id)})}},100))}}}}this.properties?.initialAnnotationColor&&this.highlighter.setColor(this.properties?.initialAnnotationColor),this.repositionGutters()}}repositionGutters(){let t=this.navigator.iframes[0].contentDocument;if(t&&(this.commentGutter=t.getElementById(qe.R2_ID_GUTTER_RIGHT_CONTAINER),this.navigator.view?.isScrollMode()&&this.properties?.enableComments?this.commentGutter?.style.removeProperty("display"):this.commentGutter?.style.setProperty("display","none"),this.commentGutter&&this.navigator.view?.isScrollMode()&&this.properties?.enableComments)){this.commentGutter.innerHTML="";let n=[];this.annotator&&(n=this.annotator.getAnnotationsByChapter(this.navigator.currentLocator().href),n&&(n=n.filter(i=>i.highlight?.note?.length>0),n=this.syncPosition(n),n=this.reposition(n),n.forEach(i=>{let o=document.createElement("i");o.innerHTML="sticky_note_2",o.className="material-icons",o.style.color=i.highlight.color;let a=t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),l,u;a&&(l=a.querySelector(`#${i.highlight.id}`)),u=l.getElementsByClassName(Tn)[0];let h=parseInt(u.style.height.replace("px","")),y=i.highlight.position,b=t.createElement("div");b.setAttribute("style",`position: absolute;top:${y}px;display: flex;max-width: 250px !important;height:${h}px;width: 200px;align-items: center;`);let w=t.createElement("div");b.appendChild(w);let p=i.highlight.color;Qe.isHexColor(p)&&(p=Qe.hexToRgbChannels(p)),b.innerHTML=ua("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="8"/>',"icon open",10,`rgba(${p.red}, ${p.green}, ${p.blue}, 1) !important`);let m=t.createElement("div");m.innerHTML=i.highlight?.note,m.setAttribute("style",`height:${h}px;overflow: hidden;padding-left: 5px;`),b.appendChild(m),Ee(b,"click",f=>{f.preventDefault(),f.stopPropagation(),this.scrollToHighlight(i.highlight.id)}),this.commentGutter?.appendChild(b)})))}}createTree(t,n,i){if(n){let o=this,a=this.publication.readingOrder;if(a.length){let l=(u,d)=>{let h=document.createElement("ul");h.className="sidenav-annotations";for(let y of d){let b=document.createElement("li"),w=document.createElement("a"),p=document.createElement("span");if(w.tabIndex=-1,w.className="chapter-link",y.Href){let f=this.publication.getAbsoluteHref(y.Href),g=this.publication.getTOCItemAbsolute(f);w.href=f,w.innerHTML=g?.Title||"",b.appendChild(w)}else p.innerHTML=y.Title||"",p.className="chapter-title",b.appendChild(p);Ee(w,"click",f=>{f.preventDefault(),f.stopPropagation();let g={href:w.href,locations:{progression:0},type:y.TypeLink,title:w.title};this.navigator.stopReadAloud(),this.navigator.navigate(g)});let m=document.createElement("ol");n.forEach(function(f){let g=y.Href.indexOf("#")!==-1?y.Href.slice(0,y.Href.indexOf("#")):y.Href;if(y.Href&&f.href.endsWith(g)){let v=document.createElement("li");v.className="annotation-item";let A=document.createElement("a");if(A.setAttribute("href",f.href),t===Si.Annotation){A.className="highlight-link";let O=document.createElement("span"),E=document.createElement("span");if(O.className="title",E.innerHTML=f.highlight.selectionInfo.cleanText,f.highlight?.marker===Ve.Underline)if(typeof f.highlight?.color=="object"){let M=f.highlight?.color;M&&E.style.setProperty("border-bottom",`2px solid ${Qe.hexToRgbA(M)}`,"important")}else E.style.setProperty("border-bottom",`2px solid ${f.highlight?.color}`,"important");else if(typeof f.highlight?.color=="object"){let M=f.highlight?.color;M&&(E.style.backgroundColor=Qe.hexToRgbA(M))}else{let M=f.highlight?.color;M&&(E.style.backgroundColor=M)}O.appendChild(E),A.appendChild(O);let T=document.createElement("span"),I=Math.round((f.locations.progression??0)*100)+"% through resource";T.className="subtitle",T.innerHTML=I,A.appendChild(T)}let C=document.createElement("span");if(C.className="timestamp",C.innerHTML=us.readableTimestamp(f.created),A.appendChild(C),Ee(A,"click",O=>{O.preventDefault(),O.stopPropagation(),o.handleAnnotationLinkClick(O,f)}),v.appendChild(A),o.navigator.sideNavExpanded){let O=document.createElement("button");O.className="delete",O.innerHTML=nr.delete,Ee(O,"click",E=>{E.preventDefault(),E.stopPropagation(),o.handleAnnotationLinkDeleteClick(t,E,f)}),v.appendChild(O)}m.appendChild(v)}}),m.children.length>0&&(h.appendChild(b),h.appendChild(m)),h.children.length>0&&u.appendChild(h),y.Children&&y.Children.length>0&&l(u,y.Children)}};i.innerHTML="",l(i,a)}}}handleAnnotationLinkClick(t,n){n?(n.href=this.publication.getAbsoluteHref(n.href),this.navigator.stopReadAloud(),this.navigator.navigate(n)):Ui.default.log("annotation data missing: ",t)}handleAnnotationLinkDeleteClick(t,n,i){Ui.default.log("annotation data locator: ",i),i?t===Si.Annotation&&this.deleteHighlight(i):Ui.default.log("annotation data missing: ",n)}static readableTimestamp(t){let n=new Date(t);return n.toDateString()+" "+n.toLocaleTimeString()}async getAnnotation(t){return this.annotator?.getAnnotation(t)}async getAnnotationByID(t){return this.annotator?.getAnnotationByID(t)}syncPosition(t){let n=this.navigator.iframes[0].contentDocument,i=(o,a)=>{let l=n.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),u,d;l&&(u=l.querySelector(`#${a.highlight.id}`)),d=u.getElementsByClassName(Tn)[0];let y=parseInt(d.style.top.replace("px","")),b=Yt(et({},a),{highlight:Yt(et({},a.highlight),{position:y})});return[...o,b]};return t.reduce(i,[])}reposition(t){let n=this.navigator.iframes[0].contentDocument,i=(o,a,l)=>{let u=t[0],d=n.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),h,y;d&&(h=d.querySelector(`#${u.highlight.id}`)),y=h.getElementsByClassName(Tn)[0];let w=parseInt(y.style.height.replace("px","")),p=a.highlight.position,m=o[l-1]&&o[l-1].highlight.position,g=l===0?0:m+w+0,v=g>p?g:p,A=Yt(et({},a),{highlight:Yt(et({},a.highlight),{position:v})});return[...o,A]};return t.sort(function(o,a){return o.highlight.position-a.highlight.position}).reduce(i,[])}};H();var Y0=nt(K0());var $i=nt(Jt());var ds=class{static async create(t){let n=new this(t.annotator,t.rights||{enableBookmarks:!1},t.publication,t,t.initialAnnotations,t.api,t.headerMenu);return await n.start(),new Promise(i=>i(n))}constructor(t,n,i,o,a,l,u){this.annotator=t,this.rights=n,this.publication=i,this.headerMenu=u,this.initialAnnotations=a,this.properties=o,this.api=l}stop(){$i.default.log("Bookmark module stop")}async start(){if(this.headerMenu&&(this.bookmarksView=Ie(this.headerMenu,"#container-view-bookmarks")),this.headerMenu&&(this.sideNavSectionBookmarks=Ie(this.headerMenu,"#sidenav-section-bookmarks")),this.headerMenu){let t=Ie(this.headerMenu,"#menu-button-bookmark");t&&t.parentElement?.style.removeProperty("display"),t&&Ee(t,"click",this.saveBookmark.bind(this))}if(this.initialAnnotations){let t=this.initialAnnotations.bookmarks||null;t&&this.annotator?.initBookmarks(t)}}async handleResize(){setTimeout(async()=>{await this.drawBookmarks(),await this.showBookmarks(),setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("highlights"):this.navigator.showLayer("highlights")},10)},100)}initialize(){return new Promise(async t=>{await document.fonts.ready,this.rights.enableBookmarks&&setTimeout(()=>{this.drawBookmarks(),this.showBookmarks()},300),t(null)})}async deleteBookmark(t){if(this.annotator)if(this.api?.deleteBookmark){await this.api?.deleteBookmark(t);let n=await this.annotator.deleteBookmark(t);return $i.default.log("Bookmark deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),n}else{let n=await this.annotator.deleteBookmark(t);return $i.default.log("Bookmark deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),n}else return new Promise(n=>n(null))}async saveBookmarkPlus(){await this.addBookmarkPlus()}async saveBookmark(){if(this.annotator){var t=this.publication.getTOCItem(this.navigator.currentChapterLink.href);if(this.navigator.currentTocUrl&&(t=this.publication.getTOCItem(this.navigator.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),t){let n=t.Href;n.indexOf("#")>0&&(n=n.slice(0,n.indexOf("#")));let i=this.navigator.view?.getCurrentPosition(),o=(0,Y0.v4)(),a;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let l=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),u=Math.ceil((i??0)*(l.length-1)),d=l[u];a=Yt(et({},d),{id:o,href:n,created:new Date,title:this.navigator.currentChapterLink.title})}else a={id:o,href:n,locations:{progression:i},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title};if(!this.annotator.locatorExists(a,Si.Bookmark))if(this.navigator.consumptionModule?.trackAction(a,cs.BookmarkCreated),this.api?.addBookmark){let l=await this.api.addBookmark(a);l&&(a=l),$i.default.log(a);let u=this.annotator.saveBookmark(a);return $i.default.log("Bookmark added "+JSON.stringify(u)),this.showBookmarks(),await this.drawBookmarks(),u}else{let l=this.annotator.saveBookmark(a);return $i.default.log("Bookmark added "+JSON.stringify(l)),this.showBookmarks(),await this.drawBookmarks(),l}}}}async addBookmarkPlus(){let t=this,n=this.navigator.highlighter?.visibleTextRects[0],i=this.navigator.iframes[0].contentDocument;if(i){let u=this.navigator.highlighter?.dom(i.body).getWindow().document.createRange(),d=this.navigator.highlighter?.dom(this.navigator.iframes[0].contentDocument?.body).getSelection();d.removeAllRanges(),n&&u.selectNodeContents(n.node),d.addRange(u);let h=zd(u,!1),y=0;for(let b of h){if(!this.navigator.highlighter?.isOutsideViewport(b)){let w=d.focusNode,p=d.focusOffset;d.collapse(d.anchorNode,d.anchorOffset);for(let v=0;v<y;v++)d.modify("move","forward","line");d.extend(w,p);let m=d.focusNode,f=d.focusNode.length;d.collapse(d.anchorNode,d.anchorOffset);let g=f;d.anchorOffset>f?g=f:g=d.anchorOffset+1,d.modify("move","forward","character"),d.modify("move","backward","word"),d.extend(m,g),d.modify("extend","backward","character"),d.modify("extend","forward","word");break}y++}}function o(u){let d={},h=t.navigator.iframes[0].contentDocument;if(h)return wn(u,t.navigator.highlighter?.dom(h.body).getDocument(),d)}let a=this.navigator.iframes[0].contentWindow,l={id:"bookmarkIcon",marker:Ve.Bookmark,icon:{id:"bookmarkIcon",title:"Bookmark",svgPath:'<path d="M0 0h24v24H0V0z" fill="none"/><path d="M17 3H7c-1.1 0-2 .9-2 2v16l7-3 7 3V5c0-1.1-.9-2-2-2z"/>',color:"#000000",position:"left"},popup:{background:"#000000",textColor:"#ffffff"},highlight:{color:"#000000",style:{default:[{property:"border-bottom",value:"0px dashed #000000",priority:"important"}]}}};if(a!==null){let u=Er(a,o);if(u===void 0){let h=t.navigator.iframes[0].contentDocument;u=this.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(h)}let d=t.navigator.iframes[0].contentDocument;if(u&&d){let h=this.navigator.highlighter?.createHighlight(this.navigator.highlighter?.dom(d.body).getWindow(),u,l.highlight?.color,!0,Ve.Bookmark,l.icon,l.popup,l.highlight?.style);if(this.navigator.iframes[0].contentDocument?.getSelection()?.removeAllRanges(),h)return this.saveAnnotation(h[0]).then(y=>{$i.default.log("saved bookmark "+y?.id)})}}}async saveAnnotation(t){if(this.annotator){var n=this.publication.getTOCItem(this.navigator.currentChapterLink.href);this.navigator.currentTocUrl&&(n=this.publication.getTOCItem(this.navigator.currentTocUrl)),n===null&&(n=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href));let i=this.navigator.view?.getCurrentPosition(),o=this.navigator.iframes[0].contentDocument;if(o){let a=Gr(o,"body"),l=t.position?t.position/a.scrollHeight:i,u=(0,Y0.v4)(),d;if(n){let h=n.Href;if(h.indexOf("#")>0&&(h=h.slice(0,h.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let y=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),b=Math.ceil((l??0)*(y.length-1)),w=y[b];d=Yt(et({},w),{id:u,href:h,created:new Date,title:this.navigator.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}})}else d={id:u,href:h,locations:{progression:l},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title,highlight:t,text:{highlight:t.selectionInfo.cleanText}}}if(d)if(this.navigator.consumptionModule?.trackAction(d,cs.BookmarkCreated),this.api?.addBookmark){let h=await this.api.addBookmark(d),y=await this.annotator.saveAnnotation(h);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(b=>b(y))}else{let h=await this.annotator.saveAnnotation(d);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(y=>y(h))}}}return new Promise(i=>i(void 0))}getBookmarks(){let t=[];return this.annotator&&(t=this.annotator.getBookmarks()),t}showBookmarks(){let t=[];this.annotator&&(t=this.annotator.getBookmarks());let n=[];this.annotator&&(n=this.annotator.getAnnotations(),n&&(n=n.filter(i=>i.highlight.marker===Ve.Bookmark),t?t.push.apply(t,n):t=n)),this.bookmarksView&&this.createTree(Si.Bookmark,t,this.bookmarksView)}async drawBookmarks(){if(this.rights.enableBookmarks&&this.navigator.highlighter)if(this.api){let n=[];if(this.annotator&&(n=await this.annotator.getAnnotations()),this.navigator.highlighter&&n&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.navigator.highlighter.destroyHighlights(it.Annotation);for(let i of n){tn.push(i.highlight);let o=i,a=this.navigator.currentChapterLink.href;var t=this.publication.getTOCItem(a);if(this.navigator.currentTocUrl&&(t=this.publication.getTOCItem(this.navigator.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),t){let l=t.Href;l.indexOf("#")>0&&(l=l.slice(0,l.indexOf("#"))),o.href===l&&await this.navigator.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,i.highlight)}}}}else{let n=[];if(this.annotator&&(n=await this.annotator.getAnnotations()),this.navigator.highlighter&&n&&this.navigator.iframes[0].contentDocument?.readyState==="complete"){await this.navigator.highlighter.destroyHighlights(it.Annotation);for(let i of n){tn.push(i.highlight);let o=i,a=this.navigator.currentChapterLink.href,l=this.publication.getTOCItem(a);if(this.navigator.currentTocUrl&&(l=this.publication.getTOCItem(this.navigator.currentTocUrl)),l===void 0&&(l=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),l){let u=l.Href;u.indexOf("#")>0&&(u=u.slice(0,u.indexOf("#"))),o.href===u&&await this.navigator.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,i.highlight)}}}}}async deleteSelectedHighlight(t){this.api?.deleteBookmark?this.api.deleteBookmark(t).then(async()=>{this.deleteLocalHighlight(t.id)}):this.deleteLocalHighlight(t.id)}async deleteLocalHighlight(t){if(this.annotator){var n=await this.annotator.deleteAnnotation(t);return $i.default.log("Highlight deleted "+JSON.stringify(n)),await this.showBookmarks(),await this.drawBookmarks(),n}else return new Promise(i=>i(null))}createTree(t,n,i){if(n){let o=this,a=this.publication.readingOrder;if(a.length){let l=(u,d)=>{let h=document.createElement("ul");h.className="sidenav-annotations";for(let y of d){let b=document.createElement("li"),w=document.createElement("a"),p=document.createElement("span");if(w.tabIndex=-1,w.className="chapter-link",y.Href){let f=this.publication.getAbsoluteHref(y.Href),g=this.publication.getTOCItemAbsolute(f);w.href=f,w.innerHTML=g?.Title||"",b.appendChild(w)}else p.innerHTML=y.Title||"",p.className="chapter-title",b.appendChild(p);Ee(w,"click",f=>{f.preventDefault(),f.stopPropagation();let g={href:w.href,locations:{progression:0},type:y.TypeLink,title:w.title};this.navigator.stopReadAloud(),this.navigator.navigate(g)});let m=document.createElement("ol");n.forEach(function(f){let g=y.Href.indexOf("#")!==-1?y.Href.slice(0,y.Href.indexOf("#")):y.Href;if(y.Href&&f.href.endsWith(g)){let v=document.createElement("li");v.className="annotation-item";let A=document.createElement("a");if(A.setAttribute("href",f.href),t===Si.Bookmark){A.className="bookmark-link";let O=document.createElement("span"),E=Math.round((f.locations.progression??0)*100)+"% through resource";O.className="title",O.innerHTML=E,A.appendChild(O)}let C=document.createElement("span");if(C.className="timestamp",C.innerHTML=ds.readableTimestamp(f.created),A.appendChild(C),Ee(A,"click",O=>{O.preventDefault(),O.stopPropagation(),o.handleAnnotationLinkClick(O,f)}),v.appendChild(A),o.navigator.sideNavExpanded){let O=document.createElement("button");O.className="delete",O.innerHTML=nr.delete,Ee(O,"click",E=>{E.preventDefault(),E.stopPropagation(),o.handleAnnotationLinkDeleteClick(t,E,f)}),v.appendChild(O)}m.appendChild(v)}}),m.children.length>0&&(h.appendChild(b),h.appendChild(m)),h.children.length>0&&u.appendChild(h),y.Children&&y.Children.length>0&&l(u,y.Children)}};i.innerHTML="",l(i,a)}}}handleAnnotationLinkClick(t,n){n?(n.href=this.publication.getAbsoluteHref(n.href),this.navigator.stopReadAloud(),this.navigator.navigate(n)):$i.default.log("bookmark data missing: ",t)}handleAnnotationLinkDeleteClick(t,n,i){$i.default.log("bookmark data locator: ",i),i?t===Si.Bookmark&&this.deleteBookmark(i):$i.default.log("bookmark data missing: ",n)}static readableTimestamp(t){let n=new Date(t);return n.toDateString()+" "+n.toLocaleTimeString()}async getAnnotation(t){return this.annotator?.getAnnotation(t)}async getAnnotationByID(t){return this.annotator?.getAnnotationByID(t)}};H();var tS=nt(eS());H();var ii=nt(Jt()),Z0="r2-mo-active",fs=class{},Xe=fs;Xe.COLOR_REF="color",Xe.AUTO_SCROLL_REF="autoscroll",Xe.AUTO_TURN_REF="autoturn",Xe.VOLUME_REF="volume",Xe.RATE_REF="rate",Xe.COLOR_KEY="mediaoverlay-"+fs.COLOR_REF,Xe.AUTO_SCROLL_KEY="mediaoverlay-"+fs.AUTO_SCROLL_REF,Xe.AUTO_TURN_KEY="mediaoverlay-"+fs.AUTO_TURN_REF,Xe.VOLUME_KEY="mediaoverlay-"+fs.VOLUME_REF,Xe.RATE_KEY="mediaoverlay-"+fs.RATE_REF;var Q0=class{constructor(t,n,i){this.MEDIAOVERLAYSETTINGS="mediaOverlaySetting";this.color="r2-mo-active";this.autoScroll=!0;this.autoTurn=!0;this.volume=1;this.rate=1;this.playing=!1;this.resourceReady=!1;this.wait=1;this.settingsChangeCallback=()=>{};this.store=t,this.api=n,this.headerMenu=i,this.initialise(),ii.default.log(this.api)}static create(t){let n=new this(t.store,t.api,t.headerMenu);if(t.initialMediaOverlaySettings){let i=t.initialMediaOverlaySettings;i?.color&&(n.color=i.color,ii.default.log(n.color)),i?.autoScroll&&(n.autoScroll=i.autoScroll,ii.default.log(n.autoScroll)),i?.autoTurn&&(n.autoTurn=i.autoTurn,ii.default.log(n.autoScroll)),i?.volume&&(n.volume=i.volume,ii.default.log(n.volume)),i?.rate&&(n.rate=i.rate,ii.default.log(n.rate)),i?.wait&&(n.wait=i.wait,ii.default.log(n.wait))}return n.initializeSelections(),n}stop(){ii.default.log("MediaOverlay settings stop")}initialise(){this.autoScroll=this.getProperty(Xe.AUTO_SCROLL_KEY)!=null?this.getProperty(Xe.AUTO_SCROLL_KEY).value:this.autoScroll,this.autoTurn=this.getProperty(Xe.AUTO_TURN_KEY)!=null?this.getProperty(Xe.AUTO_TURN_KEY).value:this.autoTurn,this.color=this.getProperty(Xe.COLOR_KEY)!=null?this.getProperty(Xe.COLOR_KEY).value:this.color,this.volume=this.getProperty(Xe.VOLUME_KEY)!=null?this.getProperty(Xe.VOLUME_KEY).value:this.volume,this.rate=this.getProperty(Xe.RATE_KEY)!=null?this.getProperty(Xe.RATE_KEY).value:this.rate,this.userProperties=this.getMediaOverlaySettings()}reset(){this.color="redtext",this.autoScroll=!0,this.autoTurn=!0,this.volume=1,this.rate=1,this.wait=1,this.userProperties=this.getMediaOverlaySettings()}initializeSelections(){this.headerMenu&&(this.settingsView=Ie(this.headerMenu,"#container-view-mediaoverlay-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(t){this.headerMenu&&(this.speechAutoTurn=Ie(this.headerMenu,"#mediaOverlayAutoTurn")),this.headerMenu&&(this.speechAutoScroll=Ie(this.headerMenu,"#mediaOverlayAutoScroll")),this.headerMenu&&(this.speechVolume=Ie(this.headerMenu,"#mediaOverlayVolume")),this.headerMenu&&(this.speechRate=Ie(this.headerMenu,"#mediaOverlayRate")),this.speechAutoScroll&&(this.speechAutoScroll.checked=this.autoScroll),this.speechAutoTurn&&(this.speechAutoTurn.checked=this.autoTurn),this.speechVolume&&(this.speechVolume.value=this.volume.toString()),this.speechRate&&(this.speechRate.value=this.volume.toString()),Ee(Ie(t,"ul"),"click",n=>{n.stopPropagation()})}onSettingsChange(t){this.settingsChangeCallback=t}storeProperty(t){this.updateUserSettings(),this.saveProperty(t)}updateUserSettings(){let t={color:this.userProperties.getByRef(Xe.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(Xe.AUTO_SCROLL_REF)?.value,autoTurn:this.userProperties.getByRef(Xe.AUTO_TURN_REF)?.value,volume:this.userProperties.getByRef(Xe.VOLUME_REF)?.value,rate:this.userProperties.getByRef(Xe.RATE_REF)?.value};this.applyMediaOverlaySettings(t),this.api?.updateSettings&&this.api?.updateSettings(t).then(async n=>{ii.default.log("api updated sync settings",n)})}getMediaOverlaySettings(){let t=new Wr;return t.addSwitchable("mediaoverlay-auto-scroll-off","mediaoverlay-auto-scroll-on",this.autoScroll,Xe.AUTO_SCROLL_REF,Xe.AUTO_SCROLL_KEY),t.addSwitchable("mediaoverlay-auto-turn-off","mediaoverlay-auto-turn-on",this.autoTurn,Xe.AUTO_TURN_REF,Xe.AUTO_TURN_KEY),t.addStringable(this.color,Xe.COLOR_REF,Xe.COLOR_KEY),t.addIncremental(this.volume,.1,1,.1,"",Xe.VOLUME_REF,Xe.VOLUME_KEY),t.addIncremental(this.rate,.1,3,.1,"",Xe.RATE_REF,Xe.RATE_KEY),t}saveProperty(t){let n=this.store.get(this.MEDIAOVERLAYSETTINGS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.name!==t.name),i.push(t),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(i))}return t}getProperty(t){let n=this.store.get(this.MEDIAOVERLAYSETTINGS);if(n){let i=JSON.parse(n);return i=i.filter(o=>o.name===t),i.length===0?null:i[0]}return null}resetMediaOverlaySettings(){this.store.remove(this.MEDIAOVERLAYSETTINGS),this.reset(),this.settingsChangeCallback()}applyMediaOverlaySettings(t){if(t.color){this.color=t.color;let n=this.userProperties.getByRef(Xe.COLOR_REF);n&&(n.value=this.color,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoScroll!==void 0){ii.default.log("autoScroll "+this.autoScroll),this.autoScroll=t.autoScroll;let n=this.userProperties.getByRef(Xe.AUTO_SCROLL_REF);n&&(n.value=this.autoScroll,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoTurn!==void 0){ii.default.log("autoTurn "+this.autoTurn),this.autoTurn=t.autoTurn;let n=this.userProperties.getByRef(Xe.AUTO_TURN_REF);n&&(n.value=this.autoTurn,this.saveProperty(n)),this.settingsChangeCallback()}if(t.volume){ii.default.log("volume "+this.volume),this.volume=t.volume;let n=this.userProperties.getByRef(Xe.VOLUME_REF);n&&(n.value=this.volume,this.saveProperty(n)),this.settingsChangeCallback()}if(t.rate){ii.default.log("rate "+this.rate),this.rate=t.rate;let n=this.userProperties.getByRef(Xe.RATE_REF);n&&(n.value=this.rate,this.saveProperty(n)),this.settingsChangeCallback()}}applyMediaOverlaySetting(t,n){if(t===Xe.COLOR_REF){this.color=n;let i=this.userProperties.getByRef(Xe.COLOR_REF);i&&(i.value=this.color,this.saveProperty(i)),this.settingsChangeCallback()}else if(t===Xe.AUTO_SCROLL_REF){this.autoScroll=n;let i=this.userProperties.getByRef(Xe.AUTO_SCROLL_REF);i&&(i.value=this.autoScroll,this.saveProperty(i)),this.settingsChangeCallback()}else if(t===Xe.AUTO_TURN_REF){this.autoTurn=n;let i=this.userProperties.getByRef(Xe.AUTO_TURN_REF);i&&(i.value=this.autoTurn,this.saveProperty(i)),this.settingsChangeCallback()}}increase(t){if(t==="mo_volume"){this.userProperties.getByRef(Xe.VOLUME_REF).increment(),this.volume=this.userProperties.getByRef(Xe.VOLUME_REF)?.value;let n=this.userProperties.getByRef(Xe.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}else if(t==="mo_rate"){this.userProperties.getByRef(Xe.RATE_REF).increment(),this.rate=this.userProperties.getByRef(Xe.RATE_REF)?.value;let n=this.userProperties.getByRef(Xe.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}}decrease(t){if(t==="mo_volume"){this.userProperties.getByRef(Xe.VOLUME_REF).decrement(),this.volume=this.userProperties.getByRef(Xe.VOLUME_REF)?.value;let n=this.userProperties.getByRef(Xe.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}else if(t==="mo_rate"){this.userProperties.getByRef(Xe.RATE_REF).decrement(),this.rate=this.userProperties.getByRef(Xe.RATE_REF)?.value;let n=this.userProperties.getByRef(Xe.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback()}}};var Ze=nt(Jt()),Ol=class{constructor(t,n,i){this.play=Ie(document,"#menu-button-play");this.pause=Ie(document,"#menu-button-pause");this.currentLinkIndex=0;this.pid=void 0;this.__ontimeupdate=!1;this.ontimeupdate=async t=>{Ze.default.log("ontimeupdate"),this.trackCurrentTime()};this.ensureOnTimeUpdate=(t,n)=>{t?this.__ontimeupdate&&(this.__ontimeupdate=!1,this.audioElement&&this.audioElement.removeEventListener("timeupdate",this.ontimeupdate),cancelAnimationFrame(this.myReq)):(!this.__ontimeupdate||n)&&(this.__ontimeupdate=!0,n&&(this.audioElement&&this.audioElement.removeEventListener("timeupdate",this.ontimeupdate),this.audioElement.addEventListener("timeupdate",this.ontimeupdate)))};this.publication=t,this.settings=n,this.properties=i}static create(t){let n=new this(t.publication,t.settings,t);return n.start(),n}stop(){Ze.default.log("MediaOverlay module stop")}start(){Ze.default.log("MediaOverlay module start")}async initialize(){return new Promise(async t=>{await document.fonts.ready,this.settings.setControls(),this.settings.onSettingsChange(()=>{this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate}),t()})}async initializeResource(t){this.currentLinks=t,this.currentLinkIndex=0,await this.playLink()}async playLink(){let t=this.currentLinks[this.currentLinkIndex];if(t?.Properties?.MediaOverlay){this.ensureOnTimeUpdate(!1,!1);let n=t.Properties?.MediaOverlay,o=new URL(n,this.publication.manifestUrl).toString(),a;try{a=await fetch(o,this.navigator.requestConfig)}catch(h){console.error(h,o);return}a.ok||Ze.default.log("BAD RESPONSE?!");let l;try{l=await a.json()}catch(h){console.error(h)}if(!l){Ze.default.log("## moJson"+l);return}t.MediaOverlays=Ks(l,tS.MediaOverlayNode),t.MediaOverlays.initialized=!0;let u=t.HrefDecoded||t.Href,d=new URL("https://dita.digital/"+u);await this.playMediaOverlays(d.pathname.substr(1),t.MediaOverlays,void 0)}else this.audioElement&&await this.audioElement.pause(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement&&await this.audioElement.pause(),this.navigator.nextResource()):await this.stopReadAloud()}async startReadAloud(){if(this.navigator.rights.enableMediaOverlays){if(this.settings.playing=!0,this.audioElement&&this.currentLinks[this.currentLinkIndex]?.Properties.MediaOverlay){let t=this.currentAudioBegin?this.currentAudioBegin:0;this.audioElement.currentTime=t,await this.audioElement.play(),this.ensureOnTimeUpdate(!1,!0),this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate}else this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?this.navigator.nextResource():await this.stopReadAloud();this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display")}}async stopReadAloud(){this.navigator.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement&&this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}pauseReadAloud(){this.navigator.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}async resumeReadAloud(){this.navigator.rights.enableMediaOverlays&&(this.settings.playing=!0,await this.audioElement.play(),this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display"))}findDepthFirstTextAudioPair(t,n,i){Ze.default.log("findDepthFirstTextAudioPair()");let o,a;if(n.Text){let d=new URL("https://dita.digital/"+n.Text);if(d.pathname.substr(1)===t){if(o=!0,d.hash&&i){a=!1;let h=d.hash.substr(1);for(let y of i)if(y===h){a=!0;break}}}else o=!1}if(Ze.default.log("isFragmentIDMatch: "+a),Ze.default.log("isTextUrlMatch: "+o),!n.Children||!n.Children.length){if(Ze.default.log("findDepthFirstTextAudioPair() - leaf text/audio pair"),!o){Ze.default.log("findDepthFirstTextAudioPair() - leaf - !isTextUrlMatch");return}return a||o&&!i?(Ze.default.log("findDepthFirstTextAudioPair() - leaf - isFragmentIDMatch || (isTextUrlMatch && !textFragmentIDChain"),n):void 0}let l=i,u=i;for(let d of n.Children){Ze.default.log("findDepthFirstTextAudioPair() - child"),Ze.default.log(JSON.stringify(d));let h=this.findDepthFirstTextAudioPair(t,d,u);if(h===null&&(Ze.default.log("findDepthFirstTextAudioPair() - child - match null (skip)"),u=void 0),h)return Ze.default.log("findDepthFirstTextAudioPair() - child - match"),Ze.default.log(JSON.stringify(h)),h}if(a){Ze.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch");let d=this.findDepthFirstTextAudioPair(t,n,void 0);return d&&(Ze.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch - match"),Ze.default.log(JSON.stringify(d)),d)}if(l&&!u)return null}trackCurrentTime(){if(cancelAnimationFrame(this.myReq),this.mediaOverlayTextAudioPair)try{this.currentAudioEnd&&this.audioElement.currentTime>=this.currentAudioEnd-.05&&(Ze.default.log("ontimeupdate - mediaOverlaysNext()"),this.mediaOverlaysNext());let t=this.mediaOverlayTextAudioPair.Text.lastIndexOf("#"),n=this.mediaOverlayTextAudioPair.Text.substr(t+1);this.mediaOverlayHighlight(n),this.myReq=requestAnimationFrame(this.trackCurrentTime.bind(this))}catch(t){}}mediaOverlaysNext(t){if(Ze.default.log("mediaOverlaysNext()"),this.mediaOverlayRoot&&this.mediaOverlayTextAudioPair){let n=this.findNextTextAudioPair(this.mediaOverlayRoot,this.mediaOverlayTextAudioPair,{prev:void 0},!!t);if(!n)Ze.default.log("mediaOverlaysNext() - navLeftOrRight()"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.navigator.nextResource()):this.stopReadAloud());else{let i=!1;if(this.mediaOverlayTextAudioPair.Text&&n.Text){let o=new URL("https://dita.digital/"+this.mediaOverlayTextAudioPair.Text),a=new URL("https://dita.digital/"+n.Text);o.pathname!==a.pathname&&(Ze.default.log("mediaOverlaysNext() SWITCH! "+o.pathname+" != "+a.pathname),i=!0)}i?this.mediaOverlaysStop():(Ze.default.log("mediaOverlaysNext() - playMediaOverlaysAudio()"),setTimeout(async()=>{await this.playMediaOverlaysAudio(n,void 0,void 0)},0))}}else Ze.default.log("mediaOverlaysNext() - navLeftOrRight() 2"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.navigator.nextResource()):this.stopReadAloud())}mediaOverlaysStop(){Ze.default.log("mediaOverlaysStop()"),this.mediaOverlaysPause(),this.mediaOverlayRoot=void 0,this.mediaOverlayTextAudioPair=void 0}mediaOverlaysPause(){Ze.default.log("mediaOverlaysPause()"),this.mediaOverlayHighlight(void 0),this.audioElement&&this.audioElement.pause()}findNextTextAudioPair(t,n,i,o){if(!t.Children||!t.Children.length){if(i?.prev===n)return Ze.default.log("findNextTextAudioPair() - prevMo === moToMatch"),t;Ze.default.log("findNextTextAudioPair() - set previous"),Ze.default.log(JSON.stringify(t)),i.prev=t;return}for(let a of t.Children){Ze.default.log("findNextTextAudioPair() - child"),Ze.default.log(JSON.stringify(a));let l=this.findNextTextAudioPair(a,n,i,o);if(l)return Ze.default.log("findNextTextAudioPair() - match"),Ze.default.log(JSON.stringify(l)),l}}async playMediaOverlaysAudio(t,n,i){if(Ze.default.log("playMediaOverlaysAudio()"),this.mediaOverlayTextAudioPair=t,!t.Audio)return;let o=new URL(t.Audio,this.publication.manifestUrl),a=o.toString(),l=new URL(a);l.hash="",l.search="";let u=l.toString(),d=typeof n!="undefined",h=typeof i!="undefined";if(this.previousAudioEnd=this.currentAudioEnd,this.currentAudioBegin=void 0,this.currentAudioEnd=void 0,!d&&!h){if(o.hash){let b=o.hash.match(/t=([0-9.]+)(,([0-9.]+))?/);if(b&&b.length>=1){let w=b[1];try{this.currentAudioBegin=parseFloat(w)}catch(p){Ze.default.error(p)}if(b.length>=3){let p=b[3];try{this.currentAudioEnd=parseFloat(p)}catch(m){Ze.default.error(m)}}}}}else this.currentAudioBegin=n,this.currentAudioEnd=i;Ze.default.log(`${a} => [${this.currentAudioBegin}-${this.currentAudioEnd}]`);let y=async b=>{if(!this.audioElement)return;let w=this.currentAudioBegin?this.currentAudioBegin:0;if(b||this.audioElement.paused)if(b&&!w||this.audioElement.currentTime===w){if(Ze.default.log("playMediaOverlaysAudio() - playClip() - _currentAudioElement.play()"),this.ensureOnTimeUpdate(!1,!1),this.audioElement.playbackRate=this.settings.rate,this.audioElement.volume=this.settings.volume,this.settings.playing){let m=function(){p.settings.resourceReady?setTimeout(async()=>{await p.audioElement.play(),p.ensureOnTimeUpdate(!1,!0)},p.settings.wait*1e3):setTimeout(m,200)},p=this;m()}}else{Ze.default.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked");let p=async m=>{if(this.audioElement.removeEventListener("timeupdate",p),Ze.default.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked - .play()"),this.ensureOnTimeUpdate(!1,!1),this.audioElement&&(this.audioElement.playbackRate=this.settings.rate,this.audioElement.volume=this.settings.volume,this.settings.playing)){let g=function(){f.settings.resourceReady?setTimeout(async()=>{await f.audioElement.play(),f.ensureOnTimeUpdate(!1,!0)},f.settings.wait*1e3):setTimeout(g,200)},f=this;g()}};this.audioElement.addEventListener("timeupdate",p),this.audioElement.currentTime=w}else{let p=this.previousAudioUrl===this.currentAudioUrl&&typeof this.previousAudioEnd!="undefined"&&this.previousAudioEnd>w-.02&&this.previousAudioEnd<=w&&this.audioElement.currentTime>=w-.1;this.ensureOnTimeUpdate(!1,!1),p?Ze.default.log("playMediaOverlaysAudio() - playClip() - ensureOnTimeUpdate"):(Ze.default.log("playMediaOverlaysAudio() - playClip() - currentTime = timeToSeekTo"),this.audioElement.currentTime=w)}};if(this.previousAudioUrl=this.currentAudioUrl,!this.currentAudioUrl||u!==this.currentAudioUrl){this.currentAudioUrl=u,Ze.default.log("playMediaOverlaysAudio() - RESET: "+this.previousAudioUrl+" => "+this.currentAudioUrl),this.audioElement=document.getElementById("AUDIO_MO_ID"),this.audioElement&&(this.audioElement.pause(),this.audioElement.setAttribute("src",""),this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement)),this.audioElement=document.createElement("audio"),this.audioElement.setAttribute("style","display: none"),this.audioElement.setAttribute("id","AUDIO_MO_ID"),this.audioElement.setAttribute("role","media-overlays"),this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate,document.body.appendChild(this.audioElement),this.audioElement.addEventListener("error",p=>{Ze.default.log("-1) error: "+(this.currentAudioUrl!==p.currentTarget.src?this.currentAudioUrl+" -- ":"")+p.currentTarget.src.substr(p.currentTarget.src.lastIndexOf("/"))),this.audioElement&&this.audioElement.error&&(Ze.default.log(this.audioElement.error.code),Ze.default.log(this.audioElement.error.message))});let b=async p=>{p.currentTarget.removeEventListener("canplaythrough",b),Ze.default.log("oncanplaythrough"),await y(!0)};this.audioElement.addEventListener("canplaythrough",b);let w=async p=>{Ze.default.log("onended"),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.navigator.nextResource()):this.stopReadAloud()};this.audioElement.addEventListener("ended",w),this.audioElement.playbackRate=this.settings.rate,this.audioElement.setAttribute("src",this.currentAudioUrl)}else Ze.default.log("playMediaOverlaysAudio() - playClip()"),await y(!1)}async playMediaOverlays(t,n,i){Ze.default.log("playMediaOverlays()");let o=i?i.filter(l=>l):void 0;o&&o.length===0&&(o=void 0);let a=this.findDepthFirstTextAudioPair(t,n,o);!a&&o&&(Ze.default.log("playMediaOverlays() - findDepthFirstTextAudioPair() SECOND CHANCE "),Ze.default.log(JSON.stringify(o,null,4)),Ze.default.log(JSON.stringify(n,null,4)),a=this.findDepthFirstTextAudioPair(t,n,void 0)),a?a.Audio&&(Ze.default.log("playMediaOverlays() - playMediaOverlaysAudio()"),this.mediaOverlayRoot=n,await this.playMediaOverlaysAudio(a,void 0,void 0)):Ze.default.log("playMediaOverlays() - !moTextAudioPair "+t)}mediaOverlayHighlight(t){Ze.default.log("moHighlight: ## "+t);let n=this.publication.Metadata?.MediaOverlay?.ActiveClass;n||(n=this.settings.color);let i=this.navigator.iframes[0].contentDocument?.documentElement.getAttribute("style"),o=i?i.indexOf("readium-night-on")>0:!1,a=i?i.indexOf("readium-sepia-on")>0:!1;if((this.publication.Metadata.Rendition?.Layout??"unknown")!=="fixed"&&(n=o||a?Z0:n||Z0),this.pid){let u;this.currentLinkIndex===0?u=this.navigator.iframes[0].contentDocument?.getElementById(this.pid):u=this.navigator.iframes[1].contentDocument?.getElementById(this.pid),u&&u.classList.remove(n)}let l;t&&(this.currentLinkIndex===0?l=this.navigator.iframes[0].contentDocument?.getElementById(t):l=this.navigator.iframes[1].contentDocument?.getElementById(t),l&&l.classList.add(n),this.pid=t),l&&(this.publication.Metadata.Rendition?.Layout??"unknown")!=="fixed"&&l.scrollIntoView({block:"center",behavior:"smooth"})}};H();var eg=nt(Jt()),Rl=class{static async create(t){let n=new this(t.publication);return await n.start(),n}constructor(t){this.publication=t}async stop(){eg.default.log("Timeline module stop")}async start(){this.timelineContainer=Ie(document,"#container-view-timeline"),this.positionSlider=Ie(document,"#positionSlider"),this.publication.positions?this.positionSlider&&(this.positionSlider.style.display="block"):this.positionSlider&&(this.positionSlider.style.display="none")}async initialize(){return new Promise(async t=>{await document.fonts.ready;let n=this.navigator.currentLocator();(this.navigator.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions)&&(this.positionSlider&&(this.positionSlider.value=(n.locations.position??0).toString()),this.positionSlider&&(this.positionSlider.max=((n.locations.totalRemainingPositions??0)+(n.locations.position??0)).toString())),this.timelineContainer&&(this.timelineContainer.innerHTML=""),this.publication.readingOrder?.forEach(i=>{let o=this.publication.getAbsoluteHref(i.Href),a=this.publication.getTOCItemAbsolute(o),l=a?.Href.indexOf("#")!==-1?a?.Href.slice(0,a?.Href.indexOf("#")):a.Href,u=this.publication.getAbsoluteHref(l??"");var d;this.publication.positions&&this.navigator.view?.layout!=="fixed"?i.contentWeight?d=i.contentWeight:d=1:d=100/(this.publication.readingOrder?.length??0);var h=document.createElement("div");if(h.style.height=d+"%",h.style.width="100%",h.className="chapter",a?.Title!==void 0){var y=document.createElement("span");y.innerHTML=a.Title,y.className="chapter-tooltip",h.appendChild(y)}Ee(h,"click",b=>{b.preventDefault(),b.stopPropagation();var w;this.publication.positions||this.navigator.rights.autoGeneratePositions&&this.publication.positions?(w=et({},this.publication.positions.filter(p=>p.href===i.Href)[0]),w.href=this.publication.getAbsoluteHref(w.href)):w={href:u,locations:{progression:0},type:i.TypeLink,title:i.Title},eg.default.log(w),this.navigator.navigate(w)}),u===this.navigator.currentChapterLink.href?h.className+=" active":h.className=h.className.replace(" active",""),this.timelineContainer&&this.timelineContainer.appendChild(h)}),t()})}};H();var wg=nt(So());H();var nS=nt(Jt());function iS(r,t){return new Promise(function(n){setTimeout(n.bind(null,t),r)})}var a8=!1;nS.default.setLevel(a8?"trace":"warn",!0);var LA=nt(MA()),hh=nt(kA()),On=nt(Jt());var ya=class{constructor(t){this.hasEventListener=!1;this.isHacked=!1;this.properties=t}static async setupPreloadProtection(t){if(this.isCurrentBrowserSupported(t))t.detectInspect&&await this.startInspectorProtection(t);else throw new Error("Browser not supported")}static async create(t){let n=new this(t);return await n.start(),n}static async startInspectorProtection(t){(0,hh.addListener)(i=>{i&&(t.clearOnInspect&&(console.clear(),window.localStorage.clear(),window.sessionStorage.clear(),window.location.replace(window.location.origin)),t.detectInspect&&typeof t.api?.inspectDetected=="function"&&t.api.inspectDetected())}),(0,hh.launch)(),await iS(t.detectInspectInitDelay??100)}static isCurrentBrowserSupported(t){if(!t.enforceSupportedBrowsers)return!0;let n=[];return(t.supportedBrowsers??[]).forEach(o=>{n.push("last 1 "+o+" version")}),(0,LA.getUserAgentRegExp)({browsers:n,allowHigherVersions:!0}).test(navigator.userAgent)}async start(){if(this.properties?.enableObfuscation){this.wrapper=mt(document,"#iframe-wrapper"),this.securityContainer=Ie(document,"#container-view-security");var t=this;this.mutationObserver=new MutationObserver(function(n){n.forEach(function(i){On.default.log(i.type),t.isHacked=!0})})}}async stop(){if(On.default.log("Protection module stop"),this.properties?.enableObfuscation&&this.mutationObserver.disconnect(),this.properties?.disableKeys){je(this.navigator.mainElement,"keydown",this.disableSave),je(this.navigator.headerMenu,"keydown",this.disableSave);for(let t of this.navigator.iframes)je(t.contentDocument,"keydown",this.disableSave),je(t.contentWindow,"keydown",this.disableSave);je(window,"keydown",this.disableSave),je(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){je(this.navigator.mainElement,"copy",this.preventCopy),je(this.navigator.headerMenu,"copy",this.preventCopy);for(let t of this.navigator.iframes)je(t.contentDocument,"copy",this.preventCopy),je(t.contentWindow,"copy",this.preventCopy);je(window,"copy",this.preventCopy),je(document,"copy",this.preventCopy),je(this.navigator.mainElement,"cut",this.preventCopy),je(this.navigator.headerMenu,"cut",this.preventCopy);for(let t of this.navigator.iframes)je(t.contentDocument,"cut",this.preventCopy),je(t.contentWindow,"cut",this.preventCopy);je(window,"cut",this.preventCopy),je(document,"cut",this.preventCopy),je(this.navigator.mainElement,"keydown",this.preventCopyKey),je(this.navigator.headerMenu,"keydown",this.preventCopyKey);for(let t of this.navigator.iframes)je(t.contentDocument,"keydown",this.preventCopyKey),je(t.contentWindow,"keydown",this.preventCopyKey);je(window,"keydown",this.preventCopyKey),je(document,"keydown",this.preventCopyKey)}else if(this.properties?.canCopy){je(this.navigator.mainElement,"copy",this.restrictCopy),je(this.navigator.headerMenu,"copy",this.restrictCopy);for(let t of this.navigator.iframes)je(t.contentDocument,"copy",this.restrictCopy),je(t.contentWindow,"copy",this.restrictCopy);je(window,"copy",this.restrictCopy),je(document,"copy",this.restrictCopy),je(this.navigator.mainElement,"cut",this.restrictCopy),je(this.navigator.headerMenu,"cut",this.restrictCopy);for(let t of this.navigator.iframes)je(t.contentDocument,"cut",this.restrictCopy),je(t.contentWindow,"cut",this.restrictCopy);je(window,"cut",this.restrictCopy),je(document,"cut",this.restrictCopy),je(this.navigator.mainElement,"keydown",this.restrictCopyKey),je(this.navigator.headerMenu,"keydown",this.restrictCopyKey);for(let t of this.navigator.iframes)je(t.contentDocument,"keydown",this.restrictCopyKey),je(t.contentWindow,"keydown",this.restrictCopyKey);je(window,"keydown",this.restrictCopyKey),je(document,"keydown",this.restrictCopyKey)}if(this.properties?.disablePrint){je(this.navigator.mainElement,"beforeprint",this.beforePrint.bind(this)),je(this.navigator.headerMenu,"beforeprint",this.beforePrint.bind(this));for(let t of this.navigator.iframes)je(t.contentDocument,"beforeprint",this.beforePrint),je(t.contentWindow,"beforeprint",this.beforePrint);je(window,"beforeprint",this.beforePrint),je(document,"beforeprint",this.beforePrint),je(this.navigator.mainElement,"afterprint",this.afterPrint.bind(this)),je(this.navigator.headerMenu,"afterprint",this.afterPrint.bind(this));for(let t of this.navigator.iframes)je(t.contentDocument,"afterprint",this.afterPrint.bind(this)),je(t.contentWindow,"afterprint",this.afterPrint.bind(this));je(window,"afterprint",this.afterPrint.bind(this)),je(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){je(this.navigator.mainElement,"contextmenu",this.disableContext),je(this.navigator.headerMenu,"contextmenu",this.disableContext);for(let t of this.navigator.iframes)je(t.contentDocument,"contextmenu",this.disableContext),je(t.contentWindow,"contextmenu",this.disableContext);je(window,"contextmenu",this.disableContext),je(document,"contextmenu",this.disableContext)}this.properties?.hideTargetUrl&&this.hideTargetUrls(!1),this.properties?.disableDrag&&this.preventDrag(!1),je(this.wrapper,"scroll",this.handleScroll.bind(this))}observe(){if(this.properties?.enableObfuscation){this.securityContainer.hasAttribute("style")&&(this.isHacked=!0),this.mutationObserver.disconnect();var t={attributes:!0,childList:!0,characterData:!0};this.mutationObserver.observe(this.securityContainer,t)}}async deactivate(){this.properties?.enableObfuscation&&(this.observe(),this.rects.forEach(t=>this.deactivateRect(t,this.securityContainer,this.isHacked)))}async activate(){if(this.properties?.enableObfuscation){this.observe();for(let t of this.navigator.iframes)if(t.contentDocument){let n=Gr(t.contentDocument,"body");this.rects=this.findRects(n),this.rects.forEach(i=>this.toggleRect(i,this.securityContainer,this.isHacked))}}}setupEvents(){if(this.properties?.disableKeys){Ee(this.navigator.mainElement,"keydown",this.disableSave),Ee(this.navigator.headerMenu,"keydown",this.disableSave);for(let t of this.navigator.iframes)Ee(t,"keydown",this.disableSave),Ee(t.ownerDocument,"keydown",this.disableSave),Ee(t.contentDocument,"keydown",this.disableSave),Ee(t.contentWindow,"keydown",this.disableSave),Ee(t.contentWindow?.document,"keydown",this.disableSave);Ee(window,"keydown",this.disableSave),Ee(document,"keydown",this.disableSave)}if(this.properties?.disableCopy){Ee(this.navigator.mainElement,"copy",this.preventCopy),Ee(this.navigator.headerMenu,"copy",this.preventCopy);for(let t of this.navigator.iframes)Ee(t,"copy",this.preventCopy),Ee(t.ownerDocument,"copy",this.preventCopy),Ee(t.contentDocument,"copy",this.preventCopy),Ee(t.contentWindow,"copy",this.preventCopy),Ee(t.contentWindow?.document,"copy",this.preventCopy);Ee(window,"copy",this.preventCopy),Ee(document,"copy",this.preventCopy),Ee(this.navigator.mainElement,"cut",this.preventCopy),Ee(this.navigator.headerMenu,"cut",this.preventCopy);for(let t of this.navigator.iframes)Ee(t,"cut",this.preventCopy),Ee(t.ownerDocument,"cut",this.preventCopy),Ee(t.contentDocument,"cut",this.preventCopy),Ee(t.contentWindow,"cut",this.preventCopy),Ee(t.contentWindow?.document,"cut",this.preventCopy);Ee(window,"cut",this.preventCopy),Ee(document,"cut",this.preventCopy),Ee(this.navigator.mainElement,"keydown",this.preventCopyKey),Ee(this.navigator.headerMenu,"keydown",this.preventCopyKey);for(let t of this.navigator.iframes)Ee(t,"keydown",this.preventCopyKey),Ee(t.ownerDocument,"keydown",this.preventCopyKey),Ee(t.contentDocument,"keydown",this.preventCopyKey),Ee(t.contentWindow,"keydown",this.preventCopyKey),Ee(t.contentWindow?.document,"keydown",this.preventCopyKey);Ee(window,"keydown",this.preventCopyKey),Ee(document,"keydown",this.preventCopyKey)}else if(this.properties?.canCopy){Ee(this.navigator.mainElement,"copy",this.restrictCopy.bind(this)),Ee(this.navigator.headerMenu,"copy",this.restrictCopy.bind(this));for(let t of this.navigator.iframes)Ee(t,"copy",this.restrictCopy),Ee(t.ownerDocument,"copy",this.restrictCopy.bind(this)),Ee(t.contentDocument,"copy",this.restrictCopy.bind(this)),Ee(t.contentWindow,"copy",this.restrictCopy.bind(this)),Ee(t.contentWindow?.document,"copy",this.restrictCopy.bind(this));Ee(window,"copy",this.restrictCopy.bind(this)),Ee(document,"copy",this.restrictCopy.bind(this)),Ee(this.navigator.mainElement,"cut",this.restrictCopy.bind(this)),Ee(this.navigator.headerMenu,"cut",this.restrictCopy.bind(this));for(let t of this.navigator.iframes)Ee(t,"cut",this.restrictCopy.bind(this)),Ee(t.ownerDocument,"cut",this.restrictCopy.bind(this)),Ee(t.contentDocument,"cut",this.restrictCopy.bind(this)),Ee(t.contentWindow,"cut",this.restrictCopy.bind(this)),Ee(t.contentWindow?.document,"cut",this.restrictCopy.bind(this));Ee(window,"cut",this.restrictCopy.bind(this)),Ee(document,"cut",this.restrictCopy.bind(this)),Ee(this.navigator.mainElement,"keydown",this.restrictCopyKey.bind(this)),Ee(this.navigator.headerMenu,"keydown",this.restrictCopyKey.bind(this));for(let t of this.navigator.iframes)Ee(t,"keydown",this.restrictCopyKey.bind(this)),Ee(t.ownerDocument,"keydown",this.restrictCopyKey.bind(this)),Ee(t.contentDocument,"keydown",this.restrictCopyKey.bind(this)),Ee(t.contentWindow,"keydown",this.restrictCopyKey.bind(this)),Ee(t.contentWindow?.document,"keydown",this.restrictCopyKey.bind(this));Ee(window,"keydown",this.restrictCopyKey.bind(this)),Ee(document,"keydown",this.restrictCopyKey.bind(this))}if(this.properties?.disablePrint){Ee(this.navigator.mainElement,"beforeprint",this.beforePrint),Ee(this.navigator.headerMenu,"beforeprint",this.beforePrint);for(let t of this.navigator.iframes)Ee(t,"beforeprint",this.beforePrint.bind(this)),Ee(t.ownerDocument,"beforeprint",this.beforePrint.bind(this)),Ee(t.contentDocument,"beforeprint",this.beforePrint.bind(this)),Ee(t.contentWindow,"beforeprint",this.beforePrint.bind(this)),Ee(t.contentWindow?.document,"beforeprint",this.beforePrint.bind(this));Ee(window,"beforeprint",this.beforePrint.bind(this)),Ee(document,"beforeprint",this.beforePrint.bind(this)),Ee(this.navigator.mainElement,"afterprint",this.afterPrint),Ee(this.navigator.headerMenu,"afterprint",this.afterPrint);for(let t of this.navigator.iframes)Ee(t,"afterprint",this.afterPrint.bind(this)),Ee(t.ownerDocument,"afterprint",this.afterPrint.bind(this)),Ee(t.contentDocument,"afterprint",this.afterPrint.bind(this)),Ee(t.contentWindow,"afterprint",this.afterPrint.bind(this)),Ee(t.contentWindow?.document,"afterprint",this.afterPrint.bind(this));Ee(window,"afterprint",this.afterPrint.bind(this)),Ee(document,"afterprint",this.afterPrint.bind(this))}if(this.properties?.disableContextMenu){Ee(this.navigator.mainElement,"contextmenu",this.disableContext),Ee(this.navigator.headerMenu,"contextmenu",this.disableContext);for(let t of this.navigator.iframes)Ee(t,"contextmenu",this.disableContext),Ee(t.ownerDocument,"contextmenu",this.disableContext),Ee(t.contentDocument,"contextmenu",this.disableContext),Ee(t.contentWindow,"contextmenu",this.disableContext),Ee(t.contentWindow?.document,"contextmenu",this.disableContext);Ee(window,"contextmenu",this.disableContext),Ee(document,"contextmenu",this.disableContext)}}initializeResource(){this.properties?.hideTargetUrl&&this.hideTargetUrls(!0),this.properties?.disableDrag&&this.preventDrag(!0)}async initialize(){if(this.properties?.enableObfuscation)return new Promise(async t=>{await document.fonts.ready;for(let n of this.navigator.iframes)if(n.contentDocument){let i=Gr(n.contentDocument,"body");this.observe(),setTimeout(()=>{this.rects=this.findRects(i),this.rects.forEach(o=>this.toggleRect(o,this.securityContainer,this.isHacked)),this.setupEvents(),this.hasEventListener||(this.hasEventListener=!0,Ee(this.wrapper,"scroll",this.handleScroll.bind(this))),t()},10)}})}handleScroll(){this.rects.forEach(t=>this.toggleRect(t,this.securityContainer,this.isHacked))}handleResize(){if(this.properties?.enableObfuscation){let t=(0,wg.debounce)(()=>{this.calcRects(this.rects),this.rects!==void 0&&this.rects.forEach(n=>this.toggleRect(n,this.securityContainer,this.isHacked))},10);this.rects&&(this.observe(),t())}}disableContext(t){return t.preventDefault(),t.stopPropagation(),!1}disableSave(t){return(navigator.platform==="MacIntel"||navigator.platform.match("Mac")?t.metaKey:t.ctrlKey&&(t.key==="s"||t.keyCode===83))?(t.preventDefault(),t.stopPropagation(),!1):!0}preventCopy(t){return On.default.log("copy action initiated"),t.clipboardData.setData("text/plain","copy not allowed"),t.stopPropagation(),t.preventDefault(),!1}preventCopyKey(t){return(navigator.platform==="MacIntel"||navigator.platform.match("Mac")?t.metaKey:t.ctrlKey&&(t.key==="c"||t.keyCode===67))?(t.preventDefault(),t.stopPropagation(),!1):!0}restrictCopy(t){if(this.citation)return;On.default.log("copy action initiated");let n=this.navigator.iframes[0].contentWindow;if(n){let o=function(l){let u={className:h=>Ai.indexOf(h)<0,idName:h=>Ai.indexOf(h)<0},d=i.navigator.iframes[0].contentDocument;if(d)return wn(l,d,u)},i=this,a=Er(n,o);if(a===void 0){let l=this.navigator.iframes[0].contentDocument;a=this.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(l)}t.clipboardData.setData("text/plain",a?.cleanText?.substring(0,this.properties?.charactersToCopy??0))}else t.clipboardData.setData("text/plain","");return t.stopPropagation(),t.preventDefault(),!1}restrictCopyKey(t){if(navigator.platform==="MacIntel"||navigator.platform.match("Mac")?t.metaKey:t.ctrlKey&&(t.key==="c"||t.keyCode===67)){let n=this.navigator.iframes[0].contentWindow;if(n){let o=function(l){let u={className:h=>Ai.indexOf(h)<0,idName:h=>Ai.indexOf(h)<0},d=i.navigator.iframes[0].contentDocument;if(d)return wn(l,d,u)},i=this,a=Er(n,o);if(a===void 0){let l=this.navigator.iframes[0].contentDocument;a=this.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(l)}this.copyToClipboard(a?.cleanText?.substring(0,this.properties?.charactersToCopy??0))}else this.copyToClipboard("");return t.stopPropagation(),t.preventDefault(),!1}return!0}copyToClipboard(t){if(t=t.substring(0,this.properties?.charactersToCopy??0),window.clipboardData)window.clipboardData.setData("text/plain",t);else{let n=this.createElementForExecCommand(t);this.selectContent(n);try{window.netscape&&netscape.security&&netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"),document.execCommand("copy",!1)}catch(i){}document.body.removeChild(n)}}createElementForExecCommand(t){let n=document.createElement("div");return n.style.position="absolute",n.style.left="-10000px",n.style.top="-10000px",n.innerHTML=t,document.body.appendChild(n),n.contentEditable=!0,n}selectContent(t){let n=document.createRange();n.selectNodeContents(t);let i=window.getSelection();i?.removeAllRanges(),i?.addRange(n)}beforePrint(t){return On.default.log("before print"),this.navigator&&this.navigator.headerMenu&&(this.navigator.headerMenu.style.display="none",this.navigator.mainElement.style.display="none"),t.stopPropagation(),t.preventDefault(),!1}afterPrint(t){return On.default.log("after print"),this.navigator&&this.navigator.headerMenu&&(this.navigator.headerMenu.style.removeProperty("display"),this.navigator.mainElement.style.removeProperty("display")),t.stopPropagation(),t.preventDefault(),!1}hideTargetUrls(t){function n(i){i.preventDefault();let o=i.currentTarget.getAttribute("data-href-resolved"),a=document.createElement("a");a.setAttribute("href",o),a.click()}for(let i of this.navigator.iframes){let o=i.contentDocument?.querySelectorAll("a");o?.forEach(a=>{let l=a.getAttribute("data-href"),u=a.getAttribute("href");!l&&u&&(a.setAttribute("data-href",u),a.setAttribute("data-href-resolved",a.href))}),t?o?.forEach(a=>{a.setAttribute("href",""),a.addEventListener("click",n)}):o?.forEach(a=>{let l=a.getAttribute("data-href");l&&a.setAttribute("href",l),a.removeEventListener("click",n)})}}preventDrag(t){let n="-webkit-user-drag: none; -khtml-user-drag: none; -moz-user-drag: none; -ms-user-drag: none; user-drag: none; -webkit-pointer-events: none; -khtml-pointer-events: none; -moz-pointer-events: none; -ms-pointer-events: none; pointer-events: none;",i=o=>{o.preventDefault()};for(let o of this.navigator.iframes){let a=o.contentDocument?.body.getAttribute("style")||"";t?(o.contentDocument?.body.addEventListener("dragstart",i),o.contentDocument?.body.setAttribute("style",a+n)):(o.contentDocument?.body.removeEventListener("dragstart",i),o.contentDocument?.body.setAttribute("style",a.replace(n,"")))}}recalculate(t=0){return new Promise(n=>{if(this.properties?.enableObfuscation){let i=(0,wg.debounce)(()=>{this.calcRects(this.rects),this.rects!==void 0&&this.rects.forEach(o=>this.toggleRect(o,this.securityContainer,this.isHacked)),n(!0)},t);this.rects?(this.observe(),i()):n(!1)}else n(!1)})}calcRects(t){t!==void 0&&t.forEach(n=>{try{let{top:i,height:o,left:a,width:l}=this.measureTextNode(n.node);n.top=i,n.height=o,n.width=l,n.left=a}catch(i){On.default.log("error "+i),On.default.log(n),On.default.log(n.node),On.default.log("scrambledTextContent "+n.scrambledTextContent),On.default.log("textContent "+n.textContent),On.default.log("isObfuscated "+n.isObfuscated)}})}deactivateRect(t,n,i){this.isBeingHacked(n)||i?(t.node.textContent=t.scrambledTextContent,t.isObfuscated=!0):(t.node.textContent=t.textContent,t.isObfuscated=!1)}toggleRect(t,n,i){let o=this.isOutsideViewport(t),a=this.isBeingHacked(n);t.isObfuscated&&!o&&!a&&!i&&(t.node.textContent=t.textContent,t.isObfuscated=!1),!t.isObfuscated&&(o||a||i)&&(t.node.textContent=t.scrambledTextContent,t.isObfuscated=!0)}findRects(t){return this.findTextNodes(t).map(i=>{let{top:o,height:a,left:l,width:u}=this.measureTextNode(i),d=i.parentElement?.nodeName==="option"||i.parentElement?.nodeName==="script"?i.textContent:this.obfuscateText(i.textContent??"");return{top:o,height:a,width:u,left:l,node:i,textContent:i.textContent??"",scrambledTextContent:d??"",isObfuscated:!1}})}obfuscateText(t){return this.scramble(t,!0)}measureTextNode(t){try{let n=document.createRange();n.selectNode(t);let i=n.getBoundingClientRect();return n.detach(),i}catch(n){On.default.log("measureTextNode "+n),On.default.log("measureTextNode "+t),On.default.log(t.textContent)}}isBeingHacked(t){return t.style.animation||t.style.transition||t.style.position||t.hasAttribute("style")?(On.default.log("content being hacked"),!0):!1}isOutsideViewport(t){let n=this.wrapper.scrollLeft,i=n+this.wrapper.clientWidth,o=t.left+t.width,a=t.top+t.height,l=this.wrapper.scrollTop,u=l+this.wrapper.clientHeight,d=a<l,h=t.top>u,y=o<n-window.innerWidth,b=t.left>i+window.innerWidth;return d||h||y||b}findTextNodes(t,n=[]){let i=t.firstChild;for(;i;)i.nodeType===1&&this.findTextNodes(i,n),i.nodeType===3&&i.textContent?.trim()&&n.push(i),i=i.nextSibling;return n}scramble(t,n=!1,i=!1){var o=t.split(" ");function a(l){for(var u=l.length,d,h;u>0;)h=Math.floor(Math.random()*u),u--,d=l[u],l[u]=l[h],l[h]=d;return l}return n&&(o=o.map(function(l){return l.includes("-")?l:a(l.split("")).join("")})),i?a(o).join(" "):o.join(" ")}};H();var FA=nt(BA());H();var fh=r=>r.replace(/\n/g," ").replace(/\s\s+/g," "),A8=r=>fh(r).trim(),NA=/[\\^$.*+?()[\]{}|]/g,x8=RegExp(NA.source);function DA(r){return r&&x8.test(r)?r.replace(NA,"\\$&"):r||""}var ph=0,C8=()=>()=>Number.isSafeInteger(++ph)?ph:ph=1,jA=()=>{ph=0},T8=C8(),O8=r=>t=>{try{return wn(t,r,Co)}catch(n){return console.error("uniqueCssSelector:",n),""}};async function Mo(r,t,n,i,o=!1){if(!t)return[];let a=t.body?.textContent;if(!a)return[];if(r=A8(r),!r.length)return[];let l=t.createNodeIterator(t.body,NodeFilter.SHOW_TEXT,{acceptNode:p=>NodeFilter.FILTER_ACCEPT}),u=new RegExp(DA(r).replace(/ /g,"\\s+"),"gim");o&&(u=new RegExp("\\b"+DA(r).replace(/ /g,"\\s+")+"\\b","gim"));let d=[],h=100,y=30,b=0,w;for(;w=u.exec(a);){let p=Math.max(0,w.index-h),m=Math.min(h,w.index),f=fh(a.substr(p,m));f=f.substr(f.length-y),p=u.lastIndex,m=Math.min(h,a.length-p);let g=fh(a.substr(p,m)).substr(0,y),v=new Range,A=w.index;for(;b<=A;){let E=l.nextNode();E&&E.nodeValue&&(b+=E.nodeValue.length)}let C=l.referenceNode.nodeValue?l.referenceNode.nodeValue?.length-(b-A):0;for(v.setStart(l.referenceNode,C),A=w.index+w[0].length;b<=A;){let T=l.nextNode()?.nodeValue;T&&(b+=T.length)}C=l.referenceNode.nodeValue?l.referenceNode.nodeValue?.length-(b-A):0,v.setEnd(l.referenceNode,C),t.getCssSelector||(t.getCssSelector=O8(t));let O=Xr(v,t.getCssSelector);O&&d.push({textMatch:fh(w[0]),textBefore:f,textAfter:g,rangeInfo:O,href:n,title:i,uuid:T8().toString()})}return d}var HA=nt(Jt()),Il=class{constructor(t,n,i,o,a){this.currentChapterSearchResult=[];this.bookSearchResult=[];this.currentSearchHighlights=[];this.headerMenu=a,this.publication=t,this.properties=n,this.api=o,this.highlighter=i}static async create(t){let n=new this(t.publication,t,t.highlighter,t.api,t.headerMenu);return await n.start(),n}async stop(){HA.default.log("Search module stop"),je(this.searchInput,"keypress",this.handleSearch.bind(this)),je(this.searchGo,"click",this.handleSearch.bind(this))}async start(){if(this.headerMenu){this.searchInput=Ie(this.headerMenu,"#searchInput"),Ee(this.searchInput,"keypress",this.handleSearch.bind(this)),this.searchGo=Ie(this.headerMenu,"#searchGo"),Ee(this.searchGo,"click",this.handleSearch.bind(this));var t=Ie(this.headerMenu,"#menu-button-search");t&&t.parentElement?.style.removeProperty("display")}setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("search"):this.navigator.showLayer("search")},10)}async handleSearch(t){(t.key==="Enter"||t.type==="click")&&(await this.handleSearchChapter(),await this.handleSearchBook())}async handleSearchChapter(t){var n=this,i=this.searchInput.value;let o=this.navigator.currentChapterLink.href,a=this.publication.getSpineItem(o);if(this.headerMenu)var l=Ie(document,"#searchResultChapter");n.currentChapterSearchResult=[],n.currentSearchHighlights=[];var u=[];await this.searchAndPaintChapter(i,t,async h=>{u=h,d(1),this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)});async function d(h){l.innerHTML="";var y;if(y=n.paginate(u,h,10),y.total===0){let b=document.createElement("a");b.className="collection-item",b.innerHTML="nothing found",l.appendChild(b)}else{for(let f=0;f<y.data.length;f++){let g=document.createElement("a"),v=y.data[f];g.className="collection-item",g.href=a?.Href??"",g.innerHTML="..."+v.textBefore+"<mark>"+v.textMatch+"</mark>"+v.textAfter+"...",Ee(g,"click",A=>{A.preventDefault(),A.stopPropagation(),n.jumpToMark(f+h*10-10)}),l.appendChild(g)}let b=document.createElement("div");b.style.textAlign="center",b.style.marginTop="10px";let w=document.createElement("ul");w.className="pagination";let p=document.createElement("li");if(p.className="disabled",p.innerHTML='<a href="#!"> < </a>',y.pre_page!==void 0){let f=y.pre_page;p.className="waves-effect",Ee(p,"click",g=>{g.preventDefault(),g.stopPropagation(),d(f)})}w.appendChild(p);for(let f=1;f<=y.total_pages;f++){let g,v=document.createElement("li");v.className="waves-effect",f===y.page&&(v.className="active",g=v),v.innerHTML='<a href="#!">'+f+"</a>",Ee(v,"click",A=>{A.preventDefault(),A.stopPropagation(),g&&(g.className="waves-effect"),v.className="active",g=v,d(f)}),w.appendChild(v)}let m=document.createElement("li");if(m.className="disabled",m.innerHTML='<a href="#!"> > </a>',y.next_page!==void 0){let f=y.next_page;m.className="waves-effect",Ee(m,"click",g=>{g.preventDefault(),g.stopPropagation(),d(f)})}w.appendChild(m),b.appendChild(w),l.appendChild(b)}}}async searchAndPaintChapter(t,n=0,i){this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.deactivate();let o=this.publication.getAbsoluteHref(this.publication.readingOrder[this.navigator.currentResource()??0].Href),a=this.publication.getTOCItem(o);a===null&&(a=this.publication.readingOrder[this.navigator.currentResource()??0]);let l=[];this.highlighter?.destroyHighlights(it.Search),this.navigator.rights.enableSearch&&this.drawSearch();let u=0;if(a){let d=this.navigator.iframes[0].contentDocument;d&&a&&Mo(t,d,a.Href,a.Title).then(h=>{h.forEach(y=>{let b={rangeInfo:y.rangeInfo};setTimeout(()=>{let w;u===n?(w=this.createSearchHighlight(b,this.properties?.current),this.jumpToMark(n)):w=this.createSearchHighlight(b,this.properties?.color),y.highlight=w,l.push(y),this.currentChapterSearchResult.push(y),this.currentSearchHighlights.push(w),u++},500)}),setTimeout(()=>{i(l)},500)})}}createSearchHighlight(t,n){try{var i=n;Qe.isHexColor(i)&&(i=Qe.hexToRgbChannels(i));let a=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,l=FA.SHA256.hash(a),u="R2_SEARCH_"+l;var o=!1;let d={color:i||ls,id:u,pointerInteraction:o,selectionInfo:t,marker:Ve.Highlight,type:it.Search},h=this.highlighter?.createHighlightDom(this.navigator.iframes[0].contentWindow,d);return d.position=parseInt((h?.hasChildNodes()?h.childNodes[0]:h).style.top.replace("px","")),d}catch(a){throw"Can't create highlight: "+a}}clearSearch(){this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.highlighter?.destroyHighlights(it.Search)}async search(t,n){return this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.bookSearchResult=[],jA(),await this.searchAndPaintChapter(t,0,async()=>{this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)}),n?(await this.searchBook(t),await this.searchChapter(t)):(await this.searchChapter(t),await this.searchBook(t))}async goToSearchID(t,n,i){var o=n,a;let l=this.navigator.currentChapterLink.href;var u=this.publication.getAbsoluteHref(t);let d=this.bookSearchResult.filter(h=>h.href===t);if(i?(a=this.currentChapterSearchResult.filter(h=>h.uuid===n)[0],o=this.currentChapterSearchResult.findIndex(h=>h.uuid===n)):(a=d.filter(h=>h.uuid===n)[0],o=d.findIndex(h=>h.uuid===n)),a!==void 0)if(l===u)this.jumpToMark(o);else{let y={href:u,locations:{progression:0},title:"title"};this.navigator.navigate(y),setTimeout(()=>{this.searchAndPaintChapter(a.textMatch,o,async()=>{this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)})},300)}}async goToSearchIndex(t,n,i){var o=n,a;let l=this.navigator.currentChapterLink.href;var u=this.publication.getAbsoluteHref(t);let d=this.bookSearchResult.filter(h=>h.href===t);if(i?a=this.currentChapterSearchResult[o]:a=d[o],a!==void 0)if(l===u)this.jumpToMark(o);else{let y={href:u,locations:{progression:0},title:"title"};this.navigator.navigate(y),setTimeout(()=>{this.searchAndPaintChapter(a.textMatch,o,async()=>{this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)})},300)}}async handleSearchBook(){var t=this,n=this.searchInput.value;if(t.headerMenu)var i=Ie(document,"#searchResultBook");o(1);async function o(l){i.innerHTML="";var u,d=await t.searchBook(n);if(u=t.paginate(d,l,10),u.total===0){let h=document.createElement("a");h.className="collection-item",h.innerHTML="nothing found",i.appendChild(h)}else{a(u.data,m=>m.href).forEach(m=>{let f=document.createElement("div");if(f.style.marginBottom="10px",m[0].title){let g=document.createElement("span");g.className="collection-item",g.style.display="block",g.innerHTML=m[0].title,f.appendChild(g)}i.appendChild(f),m.forEach(g=>{let v=document.createElement("a");v.className="collection-item";var A=t.publication.getAbsoluteHref(g.href);v.innerHTML="..."+g.textBefore+"<mark>"+g.textMatch+"</mark>"+g.textAfter+"...",Ee(v,"click",C=>{C.preventDefault(),C.stopPropagation();let E=d.filter(I=>I.href===g.href).findIndex(I=>I===g);if(t.navigator.currentChapterLink.href===A)t.jumpToMark(E);else{let M={href:A,locations:{progression:0},title:"title"};t.navigator.navigate(M),setTimeout(()=>{t.handleSearchChapter(E)},300)}}),f.appendChild(v)})});let y=document.createElement("div");y.style.textAlign="center",y.style.marginTop="10px";let b=document.createElement("ul");b.className="pagination";let w=document.createElement("li");if(w.className="disabled",w.innerHTML='<a href="#!"> < </a>',u.pre_page!=null){let m=u.pre_page;w.className="waves-effect",Ee(w,"click",f=>{f.preventDefault(),f.stopPropagation(),o(m)})}b.appendChild(w);for(let m=1;m<=u.total_pages;m++){let f,g=document.createElement("li");g.className="waves-effect",m===u.page&&(g.className="active",f=g),g.innerHTML='<a href="#!">'+m+"</a>",Ee(g,"click",v=>{v.preventDefault(),v.stopPropagation(),f&&(f.className="waves-effect"),g.className="active",f=g,o(m)}),b.appendChild(g)}let p=document.createElement("li");if(p.className="disabled",p.innerHTML='<a href="#!"> > </a>',u.next_page!=null){let m=u.next_page;p.className="waves-effect",Ee(p,"click",f=>{f.preventDefault(),f.stopPropagation(),o(m)})}b.appendChild(p),y.appendChild(b),i.appendChild(y)}}function a(l,u){let d=new Map;return l.forEach(h=>{let y=u(h),b=d.get(y);b?b.push(h):d.set(y,[h])}),Array.from(d.values())}}async searchBook(t){this.bookSearchResult=[];let n=[];for(let i=0;i<this.publication.readingOrder.length;i++){let o=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[i].Href:""),a=this.publication.getTOCItem(o);if(a===void 0&&this.publication.readingOrder&&(a=this.publication.readingOrder[i]),a){let l=this.publication.getAbsoluteHref(a.Href);this.navigator.api?.getContent?await this.navigator.api?.getContent(l).then(u=>{let h=new DOMParser().parseFromString(u,"application/xhtml+xml");a&&Mo(t,h,a.Href,a.Title).then(y=>{y.forEach(b=>{n.push(b),this.bookSearchResult.push(b)})})}):await fetch(l,this.navigator.requestConfig).then(u=>u.text()).then(async u=>{let h=new DOMParser().parseFromString(this.navigator.requestConfig?.encoded?this.decodeBase64(u):u,"application/xhtml+xml");a&&Mo(t,h,a.Href,a.Title).then(y=>{y.forEach(b=>{n.push(b),this.bookSearchResult.push(b)})})})}if(i===this.publication.readingOrder.length-1)return n}}decodeBase64(t){let n=atob(t),i=n.length,o=new Uint8Array(i);for(let l=0;l<i;l++)o[l]=n.charCodeAt(l);return new TextDecoder().decode(o)}async searchChapter(t){let n=[],i=this.publication.getAbsoluteHref(this.publication.readingOrder[this.navigator.currentResource()??0].Href),o=this.publication.getTOCItem(i);if(o===null&&(o=this.publication.readingOrder[this.navigator.currentResource()??0]),o){let a=this.publication.getAbsoluteHref(o.Href);this.navigator.api?.getContent?await this.navigator.api?.getContent(a).then(l=>{let d=new DOMParser().parseFromString(l,"application/xhtml+xml");o&&Mo(t,d,o.Href,o.Title).then(h=>{h.forEach(y=>{n.push(y)})})}):await fetch(a,this.navigator.requestConfig).then(l=>l.text()).then(async l=>{let d=new DOMParser().parseFromString(this.navigator.requestConfig?.encoded?this.decodeBase64(l):l,"application/xhtml+xml");o&&Mo(t,d,o.Href,o.Title).then(h=>{h.forEach(y=>{n.push(y)})})})}return n}drawSearch(){setTimeout(()=>{this.currentSearchHighlights=[],this.currentChapterSearchResult.forEach(t=>{let n={rangeInfo:t.rangeInfo};if(this.properties?.color){let i=this.createSearchHighlight(n,this.properties?.color);t.highlight=i,this.currentSearchHighlights.push(i)}})},100)}async handleResize(){await this.highlighter?.destroyHighlights(it.Search),this.drawSearch()}jumpToMark(t){setTimeout(()=>{if(this.currentChapterSearchResult.length){var n=this.currentChapterSearchResult[t];this.currentSearchHighlights.forEach(o=>{var a=this.properties?.color;Qe.isHexColor(a)&&(a=Qe.hexToRgbChannels(a)),o.color=a});var i=this.properties?.current;Qe.isHexColor(i)&&(i=Qe.hexToRgbChannels(i)),n.highlight.color=i,this.highlighter?.setAndResetSearchHighlight(n.highlight,this.currentSearchHighlights),this.navigator.view?.goToCssSelector(n.rangeInfo.startContainerElementCssSelector),this.navigator.updatePositionInfo()}},200)}paginate(t,n,i){let o=n||1,a=i||10,l=(o-1)*a,u=t.slice(l).slice(0,a),d=Math.ceil(t.length/a);return{page:o,per_page:a,pre_page:o-1?o-1:void 0,next_page:d>o?o+1:void 0,total:t.length,total_pages:d,data:u}}};H();var oi=nt(Jt()),ko=class{},Ke=ko;Ke.COLOR_REF="color",Ke.AUTO_SCROLL_REF="autoscroll",Ke.RATE_REF="rate",Ke.PITCH_REF="pitch",Ke.VOLUME_REF="volume",Ke.VOICE_REF="voice",Ke.COLOR_KEY="tts-"+ko.COLOR_REF,Ke.AUTO_SCROLL_KEY="tts-"+ko.AUTO_SCROLL_REF,Ke.RATE_KEY="tts-"+ko.RATE_REF,Ke.PITCH_KEY="tts-"+ko.PITCH_REF,Ke.VOLUME_KEY="tts-"+ko.VOLUME_REF,Ke.VOICE_KEY="tts-"+ko.VOICE_REF;var _g=class{constructor(t,n,i){this.TTSSETTINGS="ttsSetting";this.color="orange";this.autoScroll=!0;this.rate=1;this.pitch=1;this.volume=1;this.voice={usePublication:!0};this.settingsChangeCallback=()=>{};this.restartCallback=()=>{};this.store=t,this.api=n,this.headerMenu=i,this.initialise()}static create(t){let n=new this(t.store,t.api,t.headerMenu);if(t.initialTTSSettings){let i=t.initialTTSSettings;i?.rate&&(n.rate=i.rate,oi.default.log(n.rate)),i?.pitch&&(n.pitch=i.pitch,oi.default.log(n.pitch)),i?.volume&&(n.volume=i.volume,oi.default.log(n.volume)),i?.color&&(n.color=i.color,oi.default.log(n.color)),i?.autoScroll&&(n.autoScroll=i.autoScroll,oi.default.log(n.autoScroll)),i?.voice&&(n.voice=i.voice,oi.default.log(n.voice))}return n.initializeSelections(),n}stop(){oi.default.log("tts settings stop")}initialise(){this.autoScroll=this.getProperty(Ke.AUTO_SCROLL_KEY)!=null?this.getProperty(Ke.AUTO_SCROLL_KEY).value:this.autoScroll,this.rate=this.getProperty(Ke.RATE_KEY)!=null?this.getProperty(Ke.RATE_KEY).value:this.rate,this.pitch=this.getProperty(Ke.PITCH_KEY)!=null?this.getProperty(Ke.PITCH_KEY).value:this.pitch,this.volume=this.getProperty(Ke.VOLUME_KEY)!=null?this.getProperty(Ke.VOLUME_KEY).value:this.volume,this.color=this.getProperty(Ke.COLOR_KEY)!=null?this.getProperty(Ke.COLOR_KEY).value:this.color,this.voice=this.getProperty(Ke.VOICE_REF)!=null?this.getProperty(Ke.VOICE_REF).value:this.voice,this.userProperties=this.getTTSSettings()}reset(){this.color="orange",this.autoScroll=!0,this.rate=1,this.pitch=1,this.volume=1,this.voice={usePublication:!0},this.userProperties=this.getTTSSettings()}initializeSelections(){this.headerMenu&&(this.settingsView=Ie(this.headerMenu,"#container-view-tts-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(t){this.headerMenu&&(this.speechRate=Ie(this.headerMenu,"#speechRate")),this.headerMenu&&(this.speechPitch=Ie(this.headerMenu,"#speechPitch")),this.headerMenu&&(this.speechVolume=Ie(this.headerMenu,"#speechVolume")),this.headerMenu&&(this.speechAutoScroll=Ie(this.headerMenu,"#autoScroll")),this.speechRate&&(this.speechRate.value=this.rate.toString()),this.speechPitch&&(this.speechPitch.value=this.pitch.toString()),this.speechVolume&&(this.speechVolume.value=this.volume.toString()),this.speechAutoScroll&&(this.speechAutoScroll.checked=this.autoScroll),Ee(Ie(t,"ul"),"click",n=>{n.stopPropagation()})}onSettingsChange(t){this.settingsChangeCallback=t}onRestart(t){this.restartCallback=t}storeProperty(t){this.updateUserSettings(),this.saveProperty(t)}updateUserSettings(){var t={rate:this.userProperties.getByRef(Ke.RATE_REF)?.value,pitch:this.userProperties.getByRef(Ke.PITCH_REF)?.value,volume:this.userProperties.getByRef(Ke.VOLUME_REF)?.value,voice:this.userProperties.getByRef(Ke.VOLUME_REF)?.value,color:this.userProperties.getByRef(Ke.COLOR_REF)?.value,autoScroll:this.userProperties.getByRef(Ke.AUTO_SCROLL_REF)?.value};this.applyTTSSettings(t),this.api?.updateSettings&&this.api?.updateSettings(t).then(async n=>{oi.default.log("api updated tts settings",n)})}getTTSSettings(){var t=new Wr;return t.addSwitchable("tts-auto-scroll-off","tts-auto-scroll-on",this.autoScroll,Ke.AUTO_SCROLL_REF,Ke.AUTO_SCROLL_KEY),t.addIncremental(this.rate,.1,10,.1,"",Ke.RATE_REF,Ke.RATE_KEY),t.addIncremental(this.pitch,.1,2,.1,"",Ke.PITCH_REF,Ke.PITCH_KEY),t.addIncremental(this.volume,.1,1,.1,"",Ke.VOLUME_REF,Ke.VOLUME_KEY),t.addStringable(this.color,Ke.COLOR_REF,Ke.COLOR_KEY),t.addJSONable(JSON.stringify(this.voice),Ke.VOICE_REF,Ke.VOICE_KEY),t}saveProperty(t){let n=this.store.get(this.TTSSETTINGS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.name!==t.name),i.push(t),this.store.set(this.TTSSETTINGS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(this.TTSSETTINGS,JSON.stringify(i))}return t}getProperty(t){let n=this.store.get(this.TTSSETTINGS);if(n){let i=JSON.parse(n);return i=i.filter(o=>o.name===t),i.length===0?void 0:i[0]}}resetTTSSettings(){this.store.remove(this.TTSSETTINGS),this.reset(),this.settingsChangeCallback(),this.restartCallback()}applyTTSSettings(t){if(t.rate){oi.default.log("rate "+this.rate),this.rate=t.rate;let n=this.userProperties.getByRef(Ke.RATE_REF);n&&(n.value=this.rate,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.pitch){oi.default.log("pitch "+this.pitch),this.pitch=t.pitch;let n=this.userProperties.getByRef(Ke.PITCH_REF);n&&(n.value=this.pitch,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.volume){oi.default.log("volume "+this.volume),this.volume=t.volume;let n=this.userProperties.getByRef(Ke.VOLUME_REF);n&&(n.value=this.volume,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}if(t.color){this.color=t.color;let n=this.userProperties.getByRef(Ke.COLOR_REF);n&&(n.value=this.color,this.saveProperty(n)),this.settingsChangeCallback()}if(t.autoScroll!==void 0){oi.default.log("autoScroll "+this.autoScroll),this.autoScroll=t.autoScroll;let n=this.userProperties.getByRef(Ke.AUTO_SCROLL_REF);n&&(n.value=this.autoScroll,this.saveProperty(n)),this.settingsChangeCallback()}if(t.voice){oi.default.log("voice "+this.voice),this.voice=t.voice;let n=this.userProperties.getByRef(Ke.VOICE_REF);n&&(n.value=this.voice,this.saveProperty(n)),this.settingsChangeCallback(),this.restartCallback()}}applyPreferredVoice(t){var n=t.indexOf(":")!==-1?t.slice(0,t.indexOf(":")):void 0,i=t.indexOf(":")!==-1?t.slice(t.indexOf(":")+1):t;n!==void 0&&i!==void 0?this.applyTTSSettings({voice:{usePublication:!0,name:n,lang:i}}):i!==void 0&&n===void 0&&this.applyTTSSettings({voice:{usePublication:!0,lang:i}})}increase(t){if(t==="rate"){this.userProperties.getByRef(Ke.RATE_REF).increment();let n=this.userProperties.getByRef(Ke.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="pitch"){this.userProperties.getByRef(Ke.PITCH_REF).increment();let n=this.userProperties.getByRef(Ke.PITCH_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="volume"){this.userProperties.getByRef(Ke.VOLUME_REF).increment();let n=this.userProperties.getByRef(Ke.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}}decrease(t){if(t==="rate"){this.userProperties.getByRef(Ke.RATE_REF).decrement();let n=this.userProperties.getByRef(Ke.RATE_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="pitch"){this.userProperties.getByRef(Ke.PITCH_REF).decrement();let n=this.userProperties.getByRef(Ke.PITCH_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}else if(t==="volume"){this.userProperties.getByRef(Ke.VOLUME_REF).decrement();let n=this.userProperties.getByRef(Ke.VOLUME_REF);n&&this.storeProperty(n),this.settingsChangeCallback(),this.restartCallback()}}};H();H();var gh=`${nr.loading}`,UA=`
|
|
80
80
|
<span>
|
|
81
81
|
${nr.error}
|
|
82
82
|
</span>
|
|
83
83
|
<span>There was an error loading this page.</span>
|
|
84
84
|
<button class="go-back">Go back</button>
|
|
85
85
|
<button class="try-again">Try again</button>
|
|
86
|
-
`;var vh=nt(So());H();var ba=class{constructor(t){this.onBackwardSwipe=()=>{};this.onForwardSwipe=()=>{};this.setupEvents=t=>{let n=null,i=null,o=this;t&&(t.addEventListener("touchstart",function(a){a.changedTouches.length===1&&(n=a)},!1),t.addEventListener("touchend",function(a){if(a.changedTouches.length!==1||!n)return;let l=n.changedTouches[0],u=a.changedTouches[0];if(!l)return;let d=window.devicePixelRatio,h=(l.clientX-u.clientX)/d,y=(l.clientY-u.clientY)/d;if(Math.abs(h)<ba.TAP_TOLERANCE&&Math.abs(y)<ba.TAP_TOLERANCE){if(i){n=null,i=null;return}if(a.timeStamp-n.timeStamp>ba.LONG_PRESS_MS){n=null,i=null;return}n=null,i=a;return}if(i=null,a.timeStamp-n.timeStamp>ba.SLOW_SWIPE_MS){n=null;return}let b=(l.clientY-u.clientY)/(l.clientX-u.clientX);if(Math.abs(b)>.5){n=null;return}h<0?o.onBackwardSwipe(a):o.onForwardSwipe(a),n=null},!1))};this.navigator=t}},ys=ba;ys.TAP_TOLERANCE=10,ys.LONG_PRESS_MS=500,ys.SLOW_SWIPE_MS=500;H();var mh=class{constructor(t){this.onBackwardSwipe=()=>{};this.onForwardSwipe=()=>{};this.setupEvents=t=>{t&&(this.focusin(t),this.keydown(t))};this.focusin=t=>{let n=this;t.addEventListener("focusin",function(i){n.navigator.view?.snap(i.target)},!0)};this.keydown=t=>{let n=this;this.navigator.rights.customKeyboardEvents||t.addEventListener("keydown",function(i){let o=i.target;if(/input|select|option|textarea/i.test(o.tagName)||!(o.ownerDocument||o).defaultView.getSelection().isCollapsed)return;switch(i.key){case"ArrowRight":n.onForwardSwipe(i);break;case"ArrowLeft":n.onBackwardSwipe(i);break}switch(i.code){case"Space":i.ctrlKey?n.onBackwardSwipe(i):n.onForwardSwipe(i);break}},!1)};this.navigator=t}};H();var $A=nt(So()),yh=class{constructor(t){this.enforceSampleRead=(0,$A.debounce)(t=>{let n=Math.round(t.locations.totalProgression*100),i=!1;this.navigator.sample?.limit&&(i=n<=this.navigator.sample?.limit,this.navigator.view?.layout==="fixed"&&!i&&this.navigator.sample?.minimum&&t.locations.position<=this.navigator.sample?.minimum&&(i=!0));let o={37:1,38:0,39:1,40:1,32:1,33:1,34:1,35:1,36:1};function a(m){m.preventDefault()}function l(m){o[m.keyCode]&&!i&&a(m)}let u=!1,d=Object.defineProperty&&Object.defineProperty({},"passive",{get:function(){u=!0}});window.addEventListener("test",function(){},d);let h=u?{passive:!1}:!1;function y(m){m=m||window.event;let f=Math.max(-1,Math.min(1,m.wheelDelta||-m.detail));return f===-1&&!i&&m.preventDefault(),!1}let b;function w(m){m=m||window.event;let f=m.target||m.srcElement,g=m.touches[0].clientY;if(!(g>b)){if(g<b&&!i)return f.className.match(/\baltNav\b/)||(m.returnValue=!1,m.cancelable&&(m.cancelBubble=!0),m.preventDefault&&m.cancelable&&(m.preventDefault(),m.stopPropagation())),!1}return b=g,!1}function p(m){return m=m||window.event,b=m.touches[0].clientY,!1}window.addEventListener("mousewheel",y,h),window.addEventListener("DOMMouseScroll",y,h),window.addEventListener("keydown",l,h),window.addEventListener("touchmove",w,h),window.addEventListener("touchstart",p,h),i?(this.navigator.iframes[0].focus(),this.navigator.errorMessage&&(this.navigator.errorMessage.style.display="none",this.navigator.errorMessage.style.removeProperty("background-color"))):(this.navigator.iframes[0].blur(),this.navigator.errorMessage&&(this.navigator.errorMessage.style.display="block",this.navigator.errorMessage.style.backgroundColor="rgb(255, 255, 255)",this.navigator.errorMessage.innerHTML=this.navigator.sample?.popup??""))},300);this.navigator=t}};H();var Bl=nt(Jt()),Nl=class{static async create(t){let n=new this(t.publication,t,t.headerMenu);return await n.start(),n}constructor(t,n,i){this.headerMenu=i,this.publication=t,this.properties=n}async stop(){Bl.default.log("Page Break module stop")}async start(){this.headerMenu&&(this.goToPageView=Ie(this.headerMenu,"#sidenav-section-gotopage")),this.headerMenu&&(this.goToPageNumberInput=Ie(this.headerMenu,"#goToPageNumberInput")),this.headerMenu&&(this.goToPageNumberButton=Ie(this.headerMenu,"#goToPageNumberButton")),Ee(this.goToPageNumberInput,"keypress",this.goToPageNumber.bind(this)),Ee(this.goToPageNumberButton,"click",this.goToPageNumber.bind(this)),this.goToPageView&&(this.publication.pageList?.length||this.goToPageView.parentElement?.removeChild(this.goToPageView)),setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("pagebreak"):this.navigator.showLayer("pagebreak")},10)}async goToPageNumber(t){if(this.goToPageNumberInput.value&&(t.key==="Enter"||t.type==="click")){var n=this.publication.pageList?.filter(o=>o.Href.slice(o.Href.indexOf("#")+1).replace(/[^0-9]/g,"")===this.goToPageNumberInput.value);if(n&&n.length>0){var i=n[0];let o={progression:0};if(i.Href.indexOf("#")!==-1){let l=i.Href.slice(i.Href.indexOf("#")+1);l!==null&&(o={fragment:l})}let a={href:this.publication.getAbsoluteHref(i.Href),locations:o,type:i.TypeLink,title:i.Title};this.navigator.goTo(a)}}}async handleResize(){await this.navigator.highlighter?.destroyHighlights(it.PageBreak),await this.drawPageBreaks()}async drawPageBreaks(){setTimeout(()=>{let t=this.navigator.iframes[0].contentDocument?.body,n=t?.querySelectorAll('[*|type="pagebreak"]');n?.length===0&&(n=t?.querySelectorAll("[epub\\:type='pagebreak']"));let i=this;function o(a){try{let l=i.navigator.iframes[0].contentDocument;return l?wn(a,l,Co):""}catch(l){return Bl.default.log("uniqueCssSelector:"),Bl.default.error(l),""}}if(n)for(let a=0;a<n.length;a++){let l=n[a];Bl.default.log(l);let u=l.innerHTML,d=!1;l.innerHTML.length===0&&(u=l.getAttribute("title")??"",l.innerHTML=u,d=!0),l.innerHTML.length===0&&(u=(l.getAttribute("id")??"").replace(/[^0-9]/g,""),l.innerHTML=u,d=!0);let h=this.navigator.iframes[0].contentDocument;if(h){let y=this.navigator.highlighter?.dom(h.body).getWindow().document.createRange(),b=this.navigator.highlighter?.dom(h.body).getSelection();if(b.removeAllRanges(),y.selectNodeContents(l),b.addRange(y),!b.isCollapsed){let w=Xr(y,o);b.removeAllRanges(),w&&this.createPageBreakHighlight({rangeInfo:w,cleanText:"",rawText:""},u)}}d&&(l.innerHTML="")}},200)}createPageBreakHighlight(t,n){try{let o=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,a=Fi.hash(o),l="R2_PAGEBREAK_"+a;var i=!1;let u={color:"#000000",id:l,pointerInteraction:i,selectionInfo:t,marker:Ve.Custom,icon:{id:"pageBreak",title:n,color:"#000000",position:"left"},type:it.PageBreak};tn.push(u);let d=this.navigator.highlighter?.createHighlightDom(this.navigator.iframes[0].contentWindow,u);return u.position=parseInt((d?.hasChildNodes()?d.childNodes[0]:d).style.top.replace("px","")),u}catch(o){throw"Can't create highlight: "+o}}};H();var qA=nt(E0());var WA=nt(So());var Ct=nt(Jt()),va=class{constructor(t,n,i,o,a,l){this.voices=[];this.hasEventListener=!1;this.startX=0;this.startY=0;this.index=0;this.userScrolled=!1;this.scrollPartial=!1;this.speaking=!1;this.restartIndex=-1;this.ttsQueueIndex=-1;this.ttsQueue=void 0;this.ttsPlayQueueIndexDebounced=(0,WA.debounce)((t,n)=>{this.restartIndex>=0?(this.ttsQueueIndex=this.restartIndex,this.restartIndex=-1):this.ttsQueueIndex=t,this.ttsQueue=n,this.ttsPlayQueueIndex(this.ttsQueueIndex,n)},150);this.tts=t,this.headerMenu=l,this.rights=n,this.highlighter=i,this.properties=o,this.api=a}initialize(t){this.highlighter!==void 0&&(this.tts.setControls(),this.tts.onRestart(this.restart.bind(this)),this.body=t,this.clean=(0,qA.default)(this.body.innerHTML,{allowedTags:[],allowedAttributes:{}}),this.wrapper=mt(document,"#iframe-wrapper"),window.speechSynthesis.getVoices(),this.initVoices(!0),this.hasEventListener||(this.hasEventListener=!0,Ee(document,"wheel",this.wheel.bind(this)),Ee(this.body,"wheel",this.wheel.bind(this)),Ee(document,"keydown",this.wheel.bind(this)),Ee(this.navigator.iframes[0].contentDocument,"keydown",this.wheel.bind(this))),Ee(this.body,"mousedown",this.clickStart.bind(this)),Ee(this.body,"mouseup",this.click.bind(this)))}clickStart(t){"clientX"in t&&(this.startX=t.clientX),"clientY"in t&&(this.startY=t.clientY)}click(t){let n=0,i=0;if("clientX"in t&&(n=t.clientX),"clientY"in t&&(i=t.clientY),window.speechSynthesis.speaking&&this.speaking&&n===this.startX&&i===this.startY){let o=this.navigator.iframes[0].contentDocument;if(o){let a=this.highlighter.dom(o.body).getSelection(),l=a.getRangeAt(0),u=a.anchorNode;for(;l.toString().indexOf(" ")!==0;)try{l.setStart(u,l.startOffset-1)}catch(y){break}l.setStart(u,l.startOffset+1);do l.setEnd(u,u.length<l.endOffset?l.endOffset+1:u.length);while(l.toString().indexOf(" ")===-1&&l.toString().trim()!=="");let h=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body;if(this.ttsQueue&&h){let y=this.findTtsQueueItemIndex(this.ttsQueue,a.anchorNode,a.anchorNode,a.anchorOffset,h);a.removeAllRanges(),y>=0&&(window.speechSynthesis.cancel(),this.restartIndex=y,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}}}}initVoices(t){function n(){return new Promise(function(o,a){let l=window.speechSynthesis,u;u=setInterval(()=>{l.getVoices().length!==0&&(o(l.getVoices()),clearInterval(u))},10)})}n().then(async o=>{if(Ct.default.log(o),this.voices=[],o.forEach(l=>{l.localService===!0&&this.voices.push(l)}),Ct.default.log(this.voices),t&&this.headerMenu){var a=Ie(this.headerMenu,"#preferred-languages");a&&this.voices.forEach(l=>{var u=document.createElement("option");u.value=l.name+":"+l.lang,u.innerHTML=l.name+" ("+l.lang+")",a.add(u)})}})}cancel(t=!0){t&&(this.api?.stopped&&this.api?.stopped(),this.navigator.emit("readaloud.stopped","stopped")),this.userScrolled=!1,this.speaking=!1,setTimeout(()=>{window.speechSynthesis.cancel()},0),this._ttsQueueItemHighlightsWord&&(this.navigator.highlighter?.destroyHighlights(it.ReadAloud),this._ttsQueueItemHighlightsWord=void 0)}async speak(t,n,i){n||this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.deactivate(),this.api?.started&&this.api?.started(),this.navigator.emit("readaloud.started","started");let o=this;this.userScrolled=!1,this.cancel(!1);let a;if(n){let w=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body,p=this.navigator.iframes[0].contentDocument;if(p){let m=this.highlighter.dom(p.body).getSelection();if(m.isCollapsed){let f=o.navigator.iframes[0].contentDocument,g=o.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(f);m.addRange(g.range)}if(w){var l=this.generateTtsQueue(w);if(!l.length)return;var u=this.findTtsQueueItemIndex(l,m.anchorNode,m.anchorNode,m.anchorOffset,w),d=this.findTtsQueueItemIndex(l,m.focusNode,m.focusNode,m.focusOffset,w);let f=bs(l,u),g=bs(l,d);var h;if(f&&t&&t.cleanText){let v=vs(f),A=t.rangeInfo.startOffset,C=t.cleanText;if(g&&u+1===d){let E=vs(g);A=(v+" "+E).indexOf(t.cleanText),C=v.slice(A,v.length),h=t.cleanText.replace(C,"").trim()}else if(d>u){let E="";for(let T=u+1;T<d;T++){let I=bs(l,T);if(I){let M=vs(I);E+=M,h=t.cleanText.replace(M,"")}}if(g){let T=vs(g);E+=" "+T}A=(v+" "+E).indexOf(t.cleanText),C=v.slice(A,v.length),h=h.replace(C,"").trim()}a=new SpeechSynthesisUtterance(C),a.rate=this.tts.rate,a.pitch=this.tts.pitch,a.volume=this.tts.volume,this.setVoice(this,a),Ct.default.log(t),Ct.default.log(C,t.range?.commonAncestorContainer.textContent),Ct.default.log(f),Ct.default.log(f.item.textNodes),Ct.default.log(A),Ct.default.log(f.item.combinedText);let O=f.item.textNodes.filter(E=>E===t.range?.commonAncestorContainer)[0];Ct.default.log(O),a.onboundary=E=>{this.updateTTSInfo(f,E.charIndex,E.charLength,A,a.text)}}}}}else a=new SpeechSynthesisUtterance(this.clean);a.rate=this.tts.rate,a.pitch=this.tts.pitch,a.volume=this.tts.volume,this.setVoice(o,a),this.index=0;function y(){a.onend=function(){if(d>u)if(u=u+1,u!==d){let b=bs(l,u);if(b){let w=vs(b);a=new SpeechSynthesisUtterance(w),a.rate=o.tts.rate,a.pitch=o.tts.pitch,a.volume=o.tts.volume,o.setVoice(o,a),a.onboundary=p=>{o.updateTTSInfo(b,p.charIndex,p.charLength,0,a.text)},setTimeout(()=>{window.speechSynthesis.speak(a)},0),y()}}else{let b=bs(l,u);b&&(a=new SpeechSynthesisUtterance(h),a.rate=o.tts.rate,a.pitch=o.tts.pitch,a.volume=o.tts.volume,o.setVoice(o,a),a.onboundary=w=>{o.updateTTSInfo(b,w.charIndex,w.charLength,0,a.text)},setTimeout(()=>{window.speechSynthesis.speak(a)},0),y()),u>d&&(Ct.default.log("utterance ended"),o.highlighter.doneSpeaking(),o.api?.finished(),o.navigator.emit("readaloud.finished","finished"))}else Ct.default.log("utterance ended"),o.highlighter.doneSpeaking(),o.api?.finished(),o.navigator.emit("readaloud.finished","finished")}}setTimeout(()=>{window.speechSynthesis.speak(a),n||this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)},0),y(),i()}setVoice(t,n){Ct.default.log("this.tts.voice.lang",this.tts.voice.lang);let i=!0;this.tts.voice&&this.tts.voice.lang&&(i=this.tts.voice.lang.indexOf("-")!==-1,i||(this.tts.voice.lang=this.tts.voice.lang.replace("_","-"),i=!0)),Ct.default.log("initialVoiceHasHyphen",i),Ct.default.log("voices",this.voices);let o;i?(o=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(h=>{var y=h.lang.replace("_","-");return y===this.tts.voice.lang&&h.name===this.tts.voice.name})[0]:void 0,o===void 0&&(o=this.tts.voice&&this.tts.voice.lang?this.voices.filter(h=>h.lang.replace("_","-")===this.tts.voice.lang)[0]:void 0)):(o=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(h=>h.lang===this.tts.voice.lang&&h.name===this.tts.voice.name)[0]:void 0,o===void 0&&(o=this.tts.voice&&this.tts.voice.lang?this.voices.filter(h=>h.lang===this.tts.voice.lang)[0]:void 0)),Ct.default.log("initialVoice",o);let a=t.navigator.publication.Metadata.Language[0].indexOf("-")!==-1;Ct.default.log("publicationVoiceHasHyphen",a);let l;a?l=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(h=>{var y=h.lang.replace("_","-");return y.startsWith(t.navigator.publication.Metadata.Language[0])||y.endsWith(t.navigator.publication.Metadata.Language[0].toUpperCase())})[0]:void 0:l=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(h=>h.lang.startsWith(t.navigator.publication.Metadata.Language[0])||h.lang.endsWith(t.navigator.publication.Metadata.Language[0].toUpperCase()))[0]:void 0,Ct.default.log("publicationVoice",l);let u=navigator.language.indexOf("-")!==-1;Ct.default.log("defaultVoiceHasHyphen",u);let d;u?d=this.voices.filter(h=>h.lang.replace("_","-")===navigator.language&&h.localService)[0]:d=this.voices.filter(h=>h.lang===navigator.language&&h.localService)[0],d===void 0&&(d=this.voices.filter(h=>h.lang.includes(navigator.language)&&h.localService)[0]),Ct.default.log("defaultVoice",d),o?(Ct.default.log("initialVoice"),n.voice=o):l?(Ct.default.log("publicationVoice"),n.voice=l):d&&(Ct.default.log("defaultVoice"),n.voice=d),n.voice!==void 0&&n.voice!==null&&(n.lang=n.voice.lang,Ct.default.log("utterance.voice.lang",n.voice.lang),Ct.default.log("utterance.lang",n.lang)),Ct.default.log("navigator.language",navigator.language)}speakPlay(){this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.deactivate(),this.scrollPartial=!0,this.cancel(!1),this.api?.started&&this.api?.started(),this.navigator.emit("readaloud.started","started");let t=this,i=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body;if(i){let l=function(){let u=t.highlighter.visibleTextRects[0],d=t.navigator.iframes[0].contentDocument;if(d){let h=t.highlighter.dom(d.body).getWindow().document.createRange(),y=t.highlighter.dom(t.navigator.iframes[0].contentDocument?.body).getSelection();y.removeAllRanges(),h.selectNodeContents(u.node),y.addRange(h);let b=0,w=y.focusNode,p=y.focusOffset;y.collapse(y.anchorNode,y.anchorOffset);for(let m=0;m<b;m++)y.modify("move","forward","line");if(y.extend(w,p),y.collapse(y.anchorNode,y.anchorOffset),i){let m=t.findTtsQueueItemIndex(o,y.anchorNode,y.anchorNode,y.anchorOffset,i);m>=0&&(a=m)}y.removeAllRanges()}},o=this.generateTtsQueue(i);if(!o.length)return;let a=0;l(),a<0&&(a=0),setTimeout(()=>{this.startTTSSession(o,a)},200)}this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)}speakPause(){window.speechSynthesis.speaking&&(this.api?.paused&&this.api?.paused(),this.navigator.emit("readaloud.paused","paused"),this.userScrolled=!1,window.speechSynthesis.pause(),this.speaking=!1,this._ttsQueueItemHighlightsWord&&(this.navigator.highlighter?.destroyHighlights(it.ReadAloud),this._ttsQueueItemHighlightsWord=void 0))}speakResume(){window.speechSynthesis.speaking&&(this.api?.resumed&&this.api?.resumed(),this.navigator.emit("readaloud.resumed","resumed"),this.userScrolled=!1,window.speechSynthesis.resume(),this.speaking=!0)}static async create(t){let n=new this(t.tts,t.rights,t.highlighter,t,t.api,t.headerMenu);return await n.start(),n}async start(){if(this.headerMenu){var t=Ie(this.headerMenu,"#menu-button-tts");t&&t.parentElement?.style.removeProperty("display")}setTimeout(()=>{this.properties?.hideLayer?this.navigator.hideLayer("readaloud"):this.navigator.showLayer("readaloud")},10)}wheel(t){if(t instanceof KeyboardEvent)switch(t.key){case"ArrowUp":this.userScrolled=!0;break;case"ArrowDown":this.userScrolled=!0;break}else this.userScrolled=!0}stop(){Ct.default.log("TTS module stop"),je(document,"wheel",this.wheel.bind(this)),je(this.body,"wheel",this.wheel.bind(this)),je(document,"keydown",this.wheel.bind(this)),je(this.navigator.iframes[0].contentDocument,"keydown",this.wheel.bind(this)),je(this.body,"click",this.click.bind(this))}generateTtsQueue(t){let n=[],i=[];function o(d){if(d.nodeType!==Node.TEXT_NODE||!d.nodeValue||!d.nodeValue.trim().length)return;let h=i[i.length-1];if(!h)return;let y=d.parentElement?GA(d.parentElement):void 0,b=d.parentElement?R8(d.parentElement):void 0,w=n[n.length-1];(!w||w.parentElement!==h||w.lang!==y||w.dir!==b)&&(w={combinedText:"",dir:b,lang:y,parentElement:h,textNodes:[]},n.push(w)),w.textNodes.push(d)}let a=!0;function l(d){if(d.nodeType!==Node.ELEMENT_NODE)return;let h=a||d.matches("h1, h2, h3, h4, h5, h6, p, th, td, caption, li, blockquote, q, dt, dd, figcaption, div, pre");a=!1,h&&i.push(d);for(let y of d.childNodes)switch(y.nodeType){case Node.ELEMENT_NODE:let b=y;if(!b.matches("img, sup, sub, audio, video, source, button, canvas, del, dialog, embed, form, head, iframe, meter, noscript, object, s, script, select, style, textarea"))l(b);else if(b.tagName&&b.tagName.toLowerCase()==="img"&&b.src){let p=b.getAttribute("alt");if(p){let m=p.trim();if(m){let f=GA(b),g=void 0;n.push({combinedText:m,dir:g,lang:f,parentElement:b,textNodes:[]})}}}break;case Node.TEXT_NODE:i.length!==0&&o(y);break;default:break}h&&i.pop()}l(t);function u(d){if(!d.textNodes||!d.textNodes.length){(!d.combinedText||!d.combinedText.length)&&(d.combinedText="");return}d.combinedText=P8(d.textNodes,!0).replace(/[\r\n]/g," ");let h=d.parentElement;for(;h;){if(h.tagName){let y=h.tagName.toLowerCase();if(y==="pre"||y==="code"||y==="video"||y==="audio")break}h=h.parentElement}}for(let d of n)u(d);return n}findTtsQueueItemIndex(t,n,i,o,a){let l=0;for(let u of t){if(i&&u.textNodes){if(u.textNodes.includes(i))return l}else if(n===u.parentElement||u.parentElement!==n.ownerDocument.body&&u.parentElement!==a&&u.parentElement.contains(n)||n.contains(u.parentElement))return l;l++}return-1}restart(){window.speechSynthesis.speaking&&(window.speechSynthesis.cancel(),this.restartIndex=this.ttsQueueIndex,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}startTTSSession(t,n){if(!bs(t,n)){this.cancel();return}this.speaking=!0,this.ttsPlayQueueIndexDebounced(n,t)}ttsPlayQueueIndex(t,n){if(t<0){this.cancel();return}let i=bs(n,t);if(!i){this.cancel();return}let o=vs(i);if(!o){this.cancel();return}let a=new SpeechSynthesisUtterance(o);a.rate=this.tts.rate,a.pitch=this.tts.pitch,a.volume=this.tts.volume;let l=this;this.setVoice(l,a),a.onboundary=u=>{Ct.default.log(u.name),this.updateTTSInfo(i,u.charIndex,u.charLength,0,a.text)},setTimeout(()=>{window.speechSynthesis.speak(a),l.speaking||window.speechSynthesis.pause()},0),a.onend=function(){l.speaking&&l.ttsPlayQueueIndexDebounced(t+1,n)}}updateTTSInfo(t,n,i,o,a){if(!t)return;Ct.default.log(t,n,i,a);let l=a||vs(t);if(n>=0&&a){let u=a.slice(0,n+1).search(/\S+$/),d=a.slice(n).search(/\s/),h=d<0?a.slice(u):a.slice(u,d+n),y=u+h.length;if(i===void 0){let b=a.substring(n).match(/^[a-z\d']*/i);b&&(i=b[0].length)}i===void 0&&(i=h.length),this.wrapHighlightWord(t,a,n+o,i,h,u,y)}return l}wrapHighlightWord(t,n,i,o,a,l,u){Ct.default.log(t),Ct.default.log(n),Ct.default.log(i,o,a,l,u),this._ttsQueueItemHighlightsWord&&(this.navigator.highlighter?.destroyHighlights(it.ReadAloud),this._ttsQueueItemHighlightsWord=void 0);let d=t.item,h=i,y=0,b,w=-1,p,m=-1,f=h+o;for(let g of d.textNodes){if(!g.nodeValue&&g.nodeValue!=="")continue;let v=g.nodeValue.length;if(y+=v,b||h<y&&(b=g,w=v-(y-h)),b&&f<=y&&(p=g,m=v-(y-f)),p)break}if(b&&p){let A=function(E){try{let T=v.navigator.iframes[0].contentDocument;return T?wn(E,T,Co):""}catch(T){return Ct.default.log("uniqueCssSelector:"),Ct.default.error(T),""}},g=new Range;g.setStart(b,w),g.setEnd(p,m);let v=this,C=Xr(g,A);if(!C)return;let O=this.navigator.highlighter?.createHighlight(this.navigator.iframes[0].contentWindow,{rangeInfo:C,cleanText:"",rawText:"",range:void 0},this.tts.color,!1,Ve.Custom,{id:"tts",title:"",position:"right"},void 0,{defaultClass:this.tts.color},it.ReadAloud,"R2_READALOUD_");if(O){this._ttsQueueItemHighlightsWord=O[0];let I=(O[1]?.firstChild?.getBoundingClientRect()).top-this.wrapper.scrollTop>window.innerHeight/2-65;this.navigator.view?.isScrollMode()&&this.tts.autoScroll&&!this.userScrolled&&this.scrollPartial&&I?O[1]?.firstChild?.scrollIntoView({block:"center",behavior:"smooth"}):this.navigator.view?.isPaginated()&&v.navigator.view?.snap(O[1]?.firstChild)}}}};function GA(r){let t=r;for(;t&&t.nodeType===Node.ELEMENT_NODE;){let n=t.getAttribute("xml:lang");if(n||(n=t.getAttributeNS("http://www.w3.org/XML/1998/namespace","lang")),n||(n=t.getAttribute("lang")),n)return n;t=t.parentNode}}function R8(r){let t=r;for(;t&&t.nodeType===Node.ELEMENT_NODE;){let n=t.getAttribute("dir");if(n)return n;t=t.parentNode}}function P8(r,t){if(r&&r.length){let n="";for(let i of r)i.nodeValue&&(n+=t?i.nodeValue:k8(i.nodeValue));return n}return""}function M8(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function k8(r){return M8(r).replace(/\n/g," ").replace(/\s\s+/g," ")}function bs(r,t){let n=-1,i=-1;for(let o of r)if(i++,n++,t===n)return{item:o,iArray:i,iGlobal:n,iSentence:-1}}function vs(r){return r.item.combinedText}H();var Dl=nt(Yd());var zA=nt(So());var VA=nt(Jt()),jl=class{constructor(t,n,i,o){this.currentChapterPopupResult=[];this.currentPopupHighlights=[];this.definitions=(0,zA.debounce)(async()=>{if(await this.highlighter.destroyHighlights(it.Definition),this.properties.definitions)for(let t of this.properties.definitions)await this.define(t)},200);this.publication=t,this.properties=n,this.api=o,this.highlighter=i}static async create(t){let n=new this(t.publication,t,t.highlighter,t.api);return await n.start(),n}async stop(){VA.default.log("Definitions module stop")}async start(){setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("definitions"):this.navigator.showLayer("definitions")},10)}async searchAndPaint(t,n){let i=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[this.navigator.currentResource()??0].Href:""),o=this.publication.getTOCItem(i);o===void 0&&this.publication.readingOrder&&(o=this.publication.readingOrder[this.navigator.currentResource()??0]);let a=[];if(o)for(let l of t.terms){let u=t.terms.indexOf(l);o&&await Mo(l,this.navigator.iframes[0].contentDocument,o.Href,o.Title,this.navigator.definitionsModule?.properties.fullWordSearch).then(d=>{let h;t.result===1?h=0:t.result===2&&(h=Math.floor(Math.random()*d.length-1)+1),d.forEach((y,b)=>{if(h===void 0||h===b){let w={rangeInfo:y.rangeInfo},p=this.createDefinitionHighlight(w,t);y.highlight=p,a.push(Dl.omit(p,"definition")),this.currentChapterPopupResult.push(y),this.currentPopupHighlights.push(p)}}),u===t.terms.length-1&&n(a)})}}async define(t){await this.searchAndPaint(t,async n=>{this.api?.success&&(this.api?.success(Dl.omit(t,"callbacks"),n),this.navigator.emit("definition.success",n),this.api?.visible&&n.forEach(i=>{let a=this.navigator.iframes[0].contentDocument?.querySelector(`#${i.id}`)?.querySelectorAll(`.${Tn}`),l=new IntersectionObserver((u,d)=>{u.forEach(h=>{h.intersectionRatio===1&&(this.api?.visible(Dl.omit(t,"callbacks"),Dl.omit(i,"definition")),this.navigator.emit("definition.visible",t,i))})},{threshold:1});a&&a.length>0&&l.observe(a[0])}))})}async drawDefinitions(){setTimeout(async()=>{await this.definitions()},100)}async handleResize(){await this.drawDefinitions()}createDefinitionHighlight(t,n){try{let i=this.navigator.definitionsModule?.properties.color;Qe.isHexColor(i)&&(i=Qe.hexToRgbChannels(i));let o=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,a=Fi.hash(o),l="R2_DEFINITION_"+a;this.highlighter.destroyHighlight(this.navigator.iframes[0].contentDocument,l);let u={color:i||ls,id:l,pointerInteraction:!0,selectionInfo:t,marker:Ve.Underline,type:it.Definition};tn.push(u);let d=this.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,u);return d&&(n.definition&&(d.dataset.definition=n.definition),d.dataset.order=String(n.order),u.definition=n,u.position=parseInt((d?.hasChildNodes()?d.childNodes[0]:d).style.top.replace("px",""))),u}catch(i){throw"Can't create definitions highlight: "+i}}async addDefinition(t){await this.define(t)}async clearDefinitions(){await this.highlighter.destroyHighlights(it.Definition)}};var QA=nt(Ag());H();var Lo=nt(Jt()),KA=.5,wa=class{constructor(t,n,i){this.hasEventListener=!1;this.lines=[];this.index=0;this.isActive=!1;this.isDebug=!1;this.lineFocusContainer=document.getElementById("lineFocusContainer");this.readerContainer=document.getElementById("D2Reader-Container");this.lineFocusTopBlinder=document.getElementById("lineFocusTopBlinder");this.lineFocusBottomBlinder=document.getElementById("lineFocusBottomBlinder");this.wrapperHeight=void 0;this.properties=t,this.api=i,this.highlighter=n}static async create(t){let n=new this(t,t.highlighter,t.api);return await n.start(),n}async stop(){Lo.default.log("Definitions module stop"),this.hasEventListener=!1,je(document,"keydown",this.keydown.bind(this)),je(document,"keyup",this.keyup.bind(this)),je(this.navigator.iframes[0].contentDocument,"keydown",this.keydown.bind(this)),je(this.navigator.iframes[0].contentDocument,"keyup",this.keyup.bind(this))}async start(){let t=mt(document,"#iframe-wrapper");t.style.height.length>0&&(this.wrapperHeight=t.style.height,this.lineFocusContainer&&this.lineFocusContainer.style.height.length===0&&(this.lineFocusContainer.style.height=this.wrapperHeight),this.readerContainer&&this.readerContainer.style.height.length===0&&(this.readerContainer.style.height=this.wrapperHeight),this.readerContainer&&(this.readerContainer.style.overflow="hidden"))}initialize(){return new Promise(async t=>{await document.fonts.ready,this.hasEventListener||(this.hasEventListener=!0,Ee(document,"keydown",this.keydown.bind(this)),Ee(document,"keyup",this.keyup.bind(this)),Ee(this.navigator.iframes[0].contentDocument,"keydown",this.keydown.bind(this)),Ee(this.navigator.iframes[0].contentDocument,"keyup",this.keyup.bind(this))),t(null)})}keydown(t){if(t instanceof KeyboardEvent&&this.isActive)switch(t.key){case"ArrowUp":t.stopPropagation();break;case"ArrowDown":t.stopPropagation();break}}keyup(t){if(t instanceof KeyboardEvent&&this.isActive)switch(t.key){case"ArrowUp":this.lineUp();break;case"ArrowDown":this.lineDown();break}}handleResize(){this.isActive&&this.lineFocus()}async enableLineFocus(){this.isActive=!0,await this.navigator.settings.scroll(!0),this.lineFocus()}disableLineFocus(t=!0){this.isActive=!1;let n=mt(document,"#iframe-wrapper");this.wrapperHeight&&(n.style.height=this.wrapperHeight),t||(this.index=0);let i=this.navigator.iframes[0].contentDocument;un(i,"html").style.removeProperty("--USER__maxMediaHeight"),this.wrapperHeight=void 0,this.lineFocusContainer&&(this.lineFocusContainer.style.display="none");let a=document.getElementById("container-view-timeline");a&&a.style.removeProperty("display");let l=document.getElementById("divBefore");l&&l.remove();let u=document.getElementById("divAfter");u&&u.remove(),this.highlighter.destroyHighlights(it.LineFocus)}lineFocus(){let t=mt(document,"#iframe-wrapper"),n=this.navigator.iframes[0].contentDocument,i=un(n,"html"),o=this.properties.maxHeight?tr()*this.properties.maxHeight/100:tr()/2;i.style.setProperty("--USER__maxMediaHeight",o+"px");function a(y,b){y.parentNode.insertBefore(b,y.nextSibling)}function l(y,b){y.parentNode.insertBefore(b,y)}let u=document.getElementById("container-view-timeline");u&&(u.style.display="none"),this.lineFocusContainer&&this.lineFocusContainer.style.removeProperty("display");let d=document.getElementById("divBefore");if(d)d.style.height=t.clientHeight/2+"px";else{let y=document.createElement("div");y.style.height=t.clientHeight/2+"px",y.id="divBefore",l(t,y)}let h=document.getElementById("divAfter");if(h)h.style.height=t.clientHeight/2+"px";else{let y=document.createElement("div");y.style.height=t.clientHeight/2+"px",y.id="divAfter",a(t,y)}if(this.lines=[],n){let w=function(){let A=Math.round,C=Math.random,O=255;return{blue:A(C()*O),green:A(C()*O),red:A(C()*O)}},p=function(A,C){let O=[];for(let E=0,T=0;E<A.length;E++)E>=C&&E%C==0&&T++,O[T]=O[T]||[],O[T].push(A[E]);return O},m=function(A,C){let O=Math.min(A.left,C.left),E=Math.max(A.right,C.right),T=Math.min(A.top,C.top),I=Math.max(A.bottom,C.bottom);return{bottom:I,height:I-T,left:O,right:E,top:T,width:E-O}},f=function(A){if(A.length>1){let C=m(A[0],A[1]);if(A.length>2){let O=m(C,A[2]);if(A.length>3){let E=m(O,A[3]);return A.length>4?m(E,A[4]):E}return O}return C}return A[0]},y=this.findRects(n.body);y=T0(y,!0),y=y.sort(function(A,C){return A.top-C.top});let b=[];y=y.filter(function(A){let C=A.top;return b.indexOf(C)===-1&&b.indexOf(C+1)===-1&&b.indexOf(C+2)===-1&&b.indexOf(C+3)===-1&&b.indexOf(C+4)===-1&&b.indexOf(C-1)===-1&&b.indexOf(C-2)===-1&&b.indexOf(C-3)===-1&&b.indexOf(C-4)===-1?(b.push(C),!0):!1}),this.highlighter.destroyHighlights(it.LineFocus);let g=[];this.properties.lines&&this.properties.lines>1?p(y,this.properties.lines).forEach(C=>{g.push(f(C))}):g=y;let v=Ie(n,"#"+qe.R2_ID_LINEFOCUS_CONTAINER);if(v)for(let A of g){let C=document.createElement("div");C.setAttribute("class",Tn);let O=w();if(Qe.isHexColor(O)&&(O=Qe.hexToRgbChannels(O)),this.isDebug){let le=`border-bottom: 1px solid rgba(${O.red}, ${O.green}, ${O.blue}, ${KA}) !important`;C.setAttribute("style",`mix-blend-mode: multiply; border-radius: 1px !important; background-color: rgba(${O.red}, ${O.green}, ${O.blue}, ${KA}) !important; ${le}`)}C.style.outline="none",C.tabIndex=0;let E=this.navigator.iframes[0].contentWindow.document,T=this.navigator.view.isPaginated();T?E.body.style.position="revert":E.body.style.position="relative";let I=E.body.getBoundingClientRect(),M=this.highlighter.getScrollingElement(E),j=T?-M.scrollLeft:I.left,U=T?-M.scrollTop:I.top,B=1,N=24,q,z,ne=this.navigator.iframes[0].contentWindow?.innerWidth,oe=parseInt(getComputedStyle(n.documentElement).getPropertyValue("column-count")),ae=parseInt(getComputedStyle(n.documentElement).getPropertyValue("column-width")),te=parseInt(getComputedStyle(n.body).getPropertyValue("padding-left"));if(ne){let le=ne/(oe||1);le<ae&&(le=ne),T||(le=parseInt(getComputedStyle(n.body).width.replace("px","")));let xe=this.navigator.settings.fontSize/100,fe=20*xe;xe<=1&&(fe=-60);let J=0;xe<=1&&(J=-60),q=Math.floor(A.left/le)*le+le-(N<40?40:N)+J,z=Math.floor(A.left/le)*le+(N<40?40:N)-fe;let D=parseInt(n.documentElement.style.getPropertyValue("--USER__pageMargins"));D>=2&&(z=z+te/oe,q=q-te/oe),T||(q=parseInt(getComputedStyle(n.body).width.replace("px","")),z=parseInt(getComputedStyle(n.body).width.replace("px",""))-le,D>=2&&(z=z+te/2,q=q-te/2))}C.style.setProperty("pointer-events","none"),C.style.position="absolute",C.scale=B,C.rect={height:A.height,left:A.left-j,top:A.top-U,width:A.width},C.style.width=`${C.rect.width*B}px`,C.style.height=`${C.rect.height*B}px`,C.style.left=`${C.rect.left*B}px`,C.style.top=`${C.rect.top*B}px`,this.lines.push(C),v.append(C)}setTimeout(()=>{this.currentLine()},100)}}currentLine(){let t=this.lines[this.index],n=t.style.top,o=parseInt(t.style.top.replace("px",""))+parseInt(t.style.height.replace("px",""))-parseInt(n.replace("px",""));if(this.lineFocusContainer){let l=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=l+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=l+"px")}t.scrollIntoView({block:"center",behavior:"smooth"})}lineDown(){if(this.index<this.lines.length-1){this.index+=1,this.index>this.lines.length-1&&(this.index=this.lines.length-1);let t=this.lines[this.index],n=t.style.top,o=parseInt(t.style.top.replace("px",""))+parseInt(t.style.height.replace("px",""))-parseInt(n.replace("px",""));if(this.lineFocusContainer){let l=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=l+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=l+"px")}t.scrollIntoView({block:"center",behavior:"smooth"})}}lineUp(){if(this.index>0){this.index-=1,this.index<0&&(this.index=0);let t=this.lines[this.index],n=t.style.top,o=parseInt(t.style.top.replace("px",""))+parseInt(t.style.height.replace("px",""))-parseInt(n.replace("px",""));if(this.lineFocusContainer){let l=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=l+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=l+"px")}t.scrollIntoView({block:"center",behavior:"smooth"})}}almostEqual(t,n,i){return Math.abs(t-n)<=i}findRects(t){let n=this.findTextNodes(t),i=Array.from(t.getElementsByTagName("img")),o=[];return n.forEach(a=>{o.push(...this.measureTextNodes(a))}),i.forEach(a=>{o.push(...this.measureImageNodes(a))}),o}findTextNodes(t,n=[]){let i=t.firstChild;for(;i;)i.nodeType===1&&this.findTextNodes(i,n),i.nodeType===3&&i.textContent?.trim()&&(i.textContent.trim().length>1||i.parentElement?.tagName.toLowerCase()==="h1"||i.parentElement?.tagName.toLowerCase()==="h2"||i.parentElement?.tagName.toLowerCase()==="h3"||i.parentElement?.tagName.toLowerCase()==="h4"||i.parentElement?.tagName.toLowerCase()==="h5"||i.parentElement?.tagName.toLowerCase()==="h6")&&i.parentElement&&getComputedStyle(i.parentElement).verticalAlign==="baseline"&&n.push(i),i=i.nextSibling;return n}measureTextNodes(t){try{let n=document.createRange();n.selectNodeContents(t);let i=Array.from(n.getClientRects());return n.detach(),i}catch(n){Lo.default.log("measureTextNode "+n),Lo.default.log("measureTextNode "+t),Lo.default.log(`${t.textContent}`)}}measureImageNodes(t){try{let n=document.createRange();n.selectNode(t);let i=Array.from(n.getClientRects());return n.detach(),i}catch(n){Lo.default.log("measureTextNode "+n),Lo.default.log("measureTextNode "+t),Lo.default.log(`${t.textContent}`)}}};H();var YA=nt(Jt()),Hl=class{constructor(t,n,i,o){this.history=[];this.headerMenu=o,this.publication=n,this.properties=i,this.annotator=t}static async create(t){let n=new this(t.annotator,t.publication,t,t.headerMenu);return await n.start(),n}async stop(){YA.default.log("Page Break module stop"),je(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),je(this.historyBackAnchorElement,"click",this.handleHistoryBackClick.bind(this))}async handleResize(){await this.setup()}setup(){this.history.length>0&&(this.historyForwardAnchorElement&&this.historyCurrentIndex+1<this.history.length?this.historyForwardAnchorElement.className=this.historyForwardAnchorElement.className.replace(" disabled",""):this.historyForwardAnchorElement&&(this.historyForwardAnchorElement.removeAttribute("href"),this.historyForwardAnchorElement.className+=" disabled"),this.historyBackAnchorElement&&this.historyCurrentIndex>0?this.historyBackAnchorElement.className=this.historyBackAnchorElement.className.replace(" disabled",""):this.historyBackAnchorElement&&(this.historyBackAnchorElement.removeAttribute("href"),this.historyBackAnchorElement.className+=" disabled"))}async push(t,n){let i;if(n&&this.annotator){let o=await this.annotator.getLastReadingPosition();if(o){let a=this.publication.getAbsoluteHref(o.href);o.href=a,this.historyCurrentIndex<this.history.length-1?(this.history=this.history.slice(0,this.historyCurrentIndex),this.history.push(o),this.historyCurrentIndex=this.history.length-1):o?.locations.progression&&o?.locations.progression>0&&(this.history.push(o),this.historyCurrentIndex=this.history.length-1)}this.historyCurrentIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyCurrentIndex)),i=this.history[this.history.length-1],(i&&i.href!==t.href||i===void 0)&&(this.history.push(t),this.historyCurrentIndex=this.history.length-1)}}async start(){this.headerMenu&&(this.historyForwardAnchorElement=Ie(this.headerMenu,"#history-forward")),this.headerMenu&&(this.historyBackAnchorElement=Ie(this.headerMenu,"#history-back")),this.historyCurrentIndex=this.history.length-1,Ee(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),Ee(this.historyBackAnchorElement,"click",this.handleHistoryBackClick.bind(this))}async handleHistoryForwardClick(t){await this.historyForward(),t.preventDefault(),t.stopPropagation()}async historyForward(){this.history.length>0&&this.historyCurrentIndex+1<this.history.length&&(this.historyCurrentIndex=this.historyCurrentIndex+1,await this.navigator.navigate(this.history[this.historyCurrentIndex],!1))}async handleHistoryBackClick(t){await this.historyBack(),t.preventDefault(),t.stopPropagation()}async historyBack(){this.history.length>0&&this.historyCurrentIndex>0&&(this.historyCurrentIndex=this.historyCurrentIndex-1,await this.navigator.navigate(this.history[this.historyCurrentIndex],!1))}};H();var XA=nt(Jt()),yt;(function(i){i[i.Chicago=0]="Chicago",i[i.MLA=1]="MLA",i[i.APA=2]="APA"})(yt||(yt={}));var ZA;(function(o){o.Author="Author",o.Editor="Editor",o.Translator="Translator",o.Compiler="Compiler"})(ZA||(ZA={}));var Ea=class{constructor(t,n,i,o){this.highlighter=n,this.properties=i,this.publication=t,this.api=o}static async create(t){let n=new this(t.publication,t.highlighter,t,t.api);return await n.start(),n}async stop(){XA.default.log("Citation module stop")}copyToClipboard(t){this.navigator?.contentProtectionModule&&(this.navigator.contentProtectionModule.citation=!0);let n=!0;if(window.clipboardData)window.clipboardData.setData("text/plain",t);else{let i=this.createElementForExecCommand(t);this.selectContent(i);try{window.netscape&&netscape.security&&netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"),n=document.execCommand("copy",!1)}catch(o){n=!1}document.body.removeChild(i)}n?this.api?.citationCreated("The text was copied to the clipboard!"):this.api?.citationFailed("Your browser doesn't allow clipboard access!")}createElementForExecCommand(t){let n=document.createElement("div");return n.style.position="absolute",n.style.left="-10000px",n.style.top="-10000px",n.innerHTML=t,document.body.appendChild(n),n.contentEditable=!0,n}selectContent(t){let n=document.createRange();n.selectNodeContents(t);let i=window.getSelection();i?.removeAllRanges(),i?.addRange(n)}async start(){let t=this,n={id:"citationIcon",callback:function(i){let o=function(){let M="",j="",U="";return t.properties.author?(U=U+t.properties.author,j=j+t.properties.author,M=M+t.properties.author):t.publication.Metadata.Author?.length>0&&0===0&&t.publication.Metadata.Author[0].Name&&t.publication.Metadata.Author[0].Name.length>0&&(U=U+t.publication.Metadata.Author[0].Name,j=j+t.publication.Metadata.Author[0].Name,M=M+t.publication.Metadata.Author[0].Name),U.length>0&&j.length>0&&M.length>0?[M+". ",j+". ",U+". "]:["","",""]},a=function(){let M="",j="",U="";return t.properties.publisher?(j=j+t.properties.publisher,M=M+t.properties.publisher):t.publication.Metadata.Publisher&&t.publication.Metadata.Publisher[0].Name&&(j=j+t.publication.Metadata.Publisher[0].Name,M=M+t.publication.Metadata.Publisher[0].Name),t.properties.published?(U=U+"("+t.properties.published+")",j=j+", "+t.properties.published,M=M+", "+t.properties.published):t.publication.Metadata.PublicationDate&&t.publication.Metadata.PublicationDate.getFullYear()>0&&(U=U+"("+t.publication.Metadata.PublicationDate.getFullYear()+")",j=j+", "+t.publication.Metadata.PublicationDate.getFullYear(),M=M+", "+t.publication.Metadata.PublicationDate.getFullYear()),U.length>0&&j.length>0&&M.length>0?[M+". ",j+". ",U+". "]:["","",""]},l=function(){return t.properties.title?["<em>"+t.properties.title+"</em>. ","<em>"+t.properties.title+"</em>. ","<em>"+t.properties.title+"</em>. "]:t.publication.Metadata.Title?["<em>"+t.publication.Metadata.Title+"</em>. ","<em>"+t.publication.Metadata.Title+"</em>. ","<em>"+t.publication.Metadata.Title+"</em>. "]:["","",""]},u=function(){return["","",""]},d=function(){let M="",j="",U="";return t.properties.publisher?(j=j+t.properties.publisher+", ",M=M+t.properties.publisher+", ",U=U+t.properties.publisher):t.publication.Metadata.Publisher&&t.publication.Metadata.Publisher[0].Name&&(j=j+t.publication.Metadata.Publisher[0].Name+", ",M=M+t.publication.Metadata.Publisher[0].Name+", ",U=U+t.publication.Metadata.Publisher[0].Name),U.length>0&&j.length>0&&M.length>0?[M+". ",j+". ",U+". "]:["","",""]},h=function(){return["","",""]},y=function(){return["","",""]},b=function(){return["","",""]},w=function(){return t.properties.library?["Retrieved from "+t.properties.library+". ","Retrieved from "+t.properties.library+". ","Retrieved from "+t.properties.library+". "]:["","",""]},p=function(){return t.properties.appName?[t.properties.appName+". ",t.properties.appName+". ",t.properties.appName+". "]:["","",""]},m=function(){return t.properties.appLink?[t.properties.appLink+". ",t.properties.appLink+". ",t.properties.appLink+". "]:["","",""]},f=function(){return["","",""]},g=function(M,j){return M.length>j?M.substring(0,j)+"...":M},v=o()[0]+l()[0]+h()[0]+u()[0]+b()[0]+a()[0]+y()[0]+w()[0]+p()[0]+m()[0],A=o()[2]+a()[2]+l()[2]+u()[2]+d()[2]+h()[2]+y()[2]+b()[2]+w()[2]+p()[2]+m()[2],C=o()[1]+l()[1]+h()[1]+u()[1]+b()[1]+a()[1]+f()[1]+w()[1]+p()[1]+m()[1],O="\u201C"+g(i,t.properties.characters)+"\u201C<br><br>"+v,E="\u201C"+g(i,t.properties.characters)+"\u201C<br><br>"+A,T="\u201C"+g(i,t.properties.characters)+"\u201C<br><br>"+C,I="";t.properties.styles?.includes(yt[0])&&(t.properties.styles.length>1&&(I=I+"Chicago: <br>"),I=I+O+"<br><br>"),t.properties.styles?.includes(yt[2])&&(t.properties.styles.length>1&&(I=I+"APA: <br>"),I=I+E+"<br><br>"),t.properties.styles?.includes(yt[1])&&(t.properties.styles.length>1&&(I=I+"MLA: <br>"),I=I+T+"<br><br>"),t.copyToClipboard(I)}};this.highlighter?.addSelectionMenuItem(n)}};var si=nt(Jt());var ut=class extends QA.default{constructor(t,n=void 0,i=void 0,o,a,l,u,d,h,y,b,w,p,m){super();this.iframes=[];this.sideNavExpanded=!1;this.currentChapterLink={href:""};this.currentSpreadLinks={};this.rights={autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1};this.didInitKeyboardEventHandler=!1;this.onResize=()=>{clearTimeout(this.timeout),this.timeout=setTimeout(this.handleResize.bind(this),200)};this.reload=async()=>{let t;if(this.annotator&&(t=await this.annotator.getLastReadingPosition()),t){let n=this.publication.getAbsoluteHref(t.href);si.default.log(t.href),si.default.log(n),t.href=n,await this.navigate(t)}};this.savePosition=(0,vh.debounce)(()=>{this.annotator&&this.saveCurrentReadingPosition()},200);this.checkResourcePosition=(0,vh.debounce)(()=>{this.view?.atStart()&&this.view?.atEnd()?(this.api?.resourceFitsScreen&&this.api?.resourceFitsScreen(),this.emit("resource.fits")):this.view?.atEnd()?(this.api?.resourceAtEnd&&this.api?.resourceAtEnd(),this.emit("resource.end")):this.view?.atStart()&&(this.api?.resourceAtStart&&this.api?.resourceAtStart(),this.emit("resource.start"))},200);this.highlighter=p,this.highlighter&&(this.highlighter.navigator=this);for(let f in m){let g=m[f];g&&(g.navigator=this),m[f]instanceof us&&(this.annotationModule=g),m[f]instanceof ds&&(this.bookmarkModule=g),m[f]instanceof va&&(this.ttsModule=g),m[f]instanceof va&&(this.ttsModule=g),m[f]instanceof Il&&(this.searchModule=g),m[f]instanceof jl&&(this.definitionsModule=g),m[f]instanceof Rl&&(this.timelineModule=g),m[f]instanceof ya&&(this.contentProtectionModule=g),m[f]instanceof Ea&&(this.citationModule=g),m[f]instanceof Ol&&(this.mediaOverlayModule=g),m[f]instanceof Nl&&(this.pageBreakModule=g),m[f]instanceof wa&&(this.lineFocusModule=g),m[f]instanceof Hl&&(this.historyModule=g),m[f]instanceof Tl&&(this.consumptionModule=g)}this.settings=t,this.annotator=n,this.view=t.view,this.view.attributes=h,this.view.navigator=this,this.eventHandler=new qd(this),this.touchEventHandler=new ys(this),this.keyboardEventHandler=new mh(this),this.initialLastReadingPosition=i,this.publication=o,this.api=a,this.rights=l??{autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1},this.tts=u,this.injectables=d,this.attributes=h||{margin:0},this.services=y,this.sample=b,this.requestConfig=w,this.sampleReadEventHandler=new yh(this)}static async create(t){let n=new this(t.settings,t.annotator||void 0,t.initialLastReadingPosition||void 0,t.publication,t.api,t.rights,t.tts,t.injectables,t.attributes||{margin:0},t.services,t.sample,t.requestConfig,t.highlighter,t.modules);return await n.start(t.mainElement,t.headerMenu,t.footerMenu),new Promise(i=>i(n))}stop(){si.default.log("Iframe navigator stop"),je(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),je(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),je(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),je(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),je(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),je(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),je(this.tryAgainButton,"click",this.tryAgain.bind(this)),je(this.goBackButton,"click",ut.goBack.bind(this)),je(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),je(window,"resize",this.onResize),this.iframes.forEach(t=>{je(t,"resize",this.onResize)})}async start(t,n,i){this.headerMenu=n,this.mainElement=t;try{let p=mt(t,"main#iframe-wrapper");p.style.overflow="auto";let m=Ie(t,"main#iframe-wrapper iframe"),f=Ie(t,"#second");if(m&&this.iframes.push(m),f&&this.iframes.push(f),window.matchMedia("screen and (max-width: 600px)").matches&&(this.settings.columnCount=1),this.iframes.length===0){p.style.overflow="auto";let g=document.createElement("iframe");if(g.setAttribute("SCROLLING","no"),g.setAttribute("allowtransparency","true"),this.iframes.push(g),this.publication.isFixedLayout?(this.spreads=document.createElement("div"),this.firstSpread=document.createElement("div"),this.spreads.style.display="flex",this.spreads.style.alignItems="center",this.spreads.style.justifyContent="center",this.spreads.appendChild(this.firstSpread),this.firstSpread.appendChild(this.iframes[0]),p.appendChild(this.spreads)):(g.setAttribute("height","100%"),g.setAttribute("width","100%"),p.appendChild(this.iframes[0])),this.publication.isFixedLayout)if(this.settings.columnCount!==1&&!window.matchMedia("screen and (max-width: 600px)").matches){let v=document.createElement("div");this.spreads.appendChild(v);let A=document.createElement("iframe");A.setAttribute("SCROLLING","no"),A.setAttribute("allowtransparency","true"),A.style.opacity="1",A.style.border="none",A.style.overflow="hidden",this.iframes.push(A),v.appendChild(this.iframes[1]),this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 100% 120%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc",v.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, 0% 120%)",v.style.boxShadow="0 0 8px 2px #ccc"}else this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc";else this.iframes[0].style.paddingTop=(this.attributes?.iframePaddingTop??0)+"px"}if(this.publication.isFixedLayout){let g=p.clientHeight;var o=this.iframes[0].parentElement?.parentElement;o.style.height=g+40+"px"}else this.iframes.length===2&&this.iframes.pop();if(this.loadingMessage=Ie(t,"#reader-loading"),this.loadingMessage&&(this.loadingMessage.innerHTML=gh,this.loadingMessage.style.display="none"),this.errorMessage=Ie(t,"#reader-error"),this.errorMessage&&(this.errorMessage.innerHTML=UA,this.errorMessage.style.display="none"),this.tryAgainButton=Ie(t,"button[class=try-again]"),this.goBackButton=Ie(t,"button[class=go-back]"),this.infoTop=Ie(t,"div[class='info top']"),this.infoBottom=Ie(t,"div[class='info bottom']"),this.headerMenu&&(this.bookTitle=Ie(this.headerMenu,"#book-title")),this.infoBottom&&(this.chapterTitle=Ie(this.infoBottom,"span[class=chapter-title]")),this.infoBottom&&(this.chapterPosition=Ie(this.infoBottom,"span[class=chapter-position]")),this.infoBottom&&(this.remainingPositions=Ie(this.infoBottom,"span[class=remaining-positions]")),this.headerMenu&&(this.espandMenuIcon=Ie(this.headerMenu,"#expand-menu")),this.headerMenu&&(this.links=Ie(this.headerMenu,"ul.links.top")),this.headerMenu&&(this.linksTopLeft=Ie(this.headerMenu,"#nav-mobile-left")),this.headerMenu&&(this.tocView=Ie(this.headerMenu,"#container-view-toc")),this.headerMenu&&(this.landmarksView=Ie(this.headerMenu,"#container-view-landmarks")),this.headerMenu&&(this.landmarksSection=Ie(this.headerMenu,"#sidenav-section-landmarks")),this.headerMenu&&(this.pageListView=Ie(this.headerMenu,"#container-view-pagelist")),i&&(this.linksBottom=Ie(i,"ul.links.bottom")),i&&(this.linksMiddle=Ie(i,"ul.links.middle")),this.headerMenu&&(this.nextChapterAnchorElement=Ie(this.headerMenu,"a[rel=next]")),this.headerMenu&&(this.nextChapterBottomAnchorElement=Ie(t,"#next-chapter")),i&&(this.nextPageAnchorElement=Ie(i,"a[rel=next]")),this.headerMenu&&(this.previousChapterAnchorElement=Ie(this.headerMenu,"a[rel=prev]")),this.headerMenu&&(this.previousChapterTopAnchorElement=Ie(t,"#previous-chapter")),i&&(this.previousPageAnchorElement=Ie(i,"a[rel=prev]")),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.newPosition=void 0,this.newElementId=void 0,this.isBeingStyled=!0,this.isLoading=!0,this.settings.setIframe(this.iframes[0]),this.settings.onSettingsChange(this.handleResize.bind(this)),this.settings.onColumnSettingsChange(this.handleNumberOfIframes.bind(this)),this.settings.onViewChange(this.updateBookView.bind(this)),this.initialLastReadingPosition&&this.annotator?.initLastReadingPosition(this.initialLastReadingPosition),this.headerMenu){var a=Ie(this.headerMenu,"#menu-button-search"),l=Ie(this.headerMenu,"#menu-button-tts"),u=Ie(this.headerMenu,"#menu-button-bookmark"),d=Ie(this.headerMenu,"#menu-button-play"),h=Ie(this.headerMenu,"#menu-button-pause"),y=Ie(this.headerMenu,"#menu-button-mediaoverlay");if(!this.rights.enableBookmarks){u&&u.parentElement?.style.setProperty("display","none");var b=Ie(this.headerMenu,"#sidenav-section-bookmarks");b&&b.style.setProperty("display","none")}if(!this.rights.enableAnnotations){var w=Ie(this.headerMenu,"#sidenav-section-highlights");w&&w.style.setProperty("display","none")}this.rights.enableTTS||l&&l.parentElement?.style.setProperty("display","none"),this.rights.enableSearch||a&&a.parentElement?.style.setProperty("display","none"),a&&this.view?.navigator.publication.isFixedLayout&&a.parentElement?.style.setProperty("display","none"),this.hasMediaOverlays?(d&&d.parentElement?.style.removeProperty("display"),h&&h.parentElement?.style.removeProperty("display"),y&&y.parentElement?.style.removeProperty("display")):(d&&d.parentElement?.style.setProperty("display","none"),h&&h.parentElement?.style.setProperty("display","none"),y&&y.parentElement?.style.setProperty("display","none"))}else a&&a.parentElement?.style.setProperty("display","none"),l&&l.parentElement?.style.setProperty("display","none"),u&&u.parentElement?.style.setProperty("display","none");return this.setupEvents(),await this.loadManifest()}catch(p){return si.default.error(p),this.abortOnError(p),Promise.reject(p)}}setupEvents(){for(let t of this.iframes)Ee(t,"load",this.handleIFrameLoad.bind(this));Ee(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),Ee(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),Ee(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Ee(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),Ee(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Ee(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),Ee(this.tryAgainButton,"click",this.tryAgain.bind(this)),Ee(this.goBackButton,"click",ut.goBack.bind(this)),Ee(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),Ee(window,"resize",this.onResize);for(let t of this.iframes)Ee(t,"resize",this.onResize)}updateBookView(t){this.view?.layout==="fixed"?(this.nextPageAnchorElement&&(this.nextPageAnchorElement.style.display="none"),this.previousPageAnchorElement&&(this.previousPageAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.keyboardEventHandler&&(this.keyboardEventHandler.onBackwardSwipe=this.handlePreviousChapterClick.bind(this),this.keyboardEventHandler.onForwardSwipe=this.handleNextChapterClick.bind(this)),this.touchEventHandler&&(this.touchEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.touchEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this))):(this.settings.isPaginated().then(n=>{if(n)this.view.height=tr()-40-(this.attributes?.margin??0),this.infoBottom&&this.infoBottom.style.removeProperty("display"),document.body.onscroll=()=>{},this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextPageAnchorElement&&(this.nextPageAnchorElement.style.display="unset"),this.previousPageAnchorElement&&(this.previousPageAnchorElement.style.display="unset"),this.chapterTitle&&(this.chapterTitle.style.display="inline"),this.chapterPosition&&(this.chapterPosition.style.display="inline"),this.remainingPositions&&(this.remainingPositions.style.display="inline"),this.eventHandler&&(this.eventHandler.onInternalLink=this.handleInternalLink.bind(this),this.eventHandler.onClickThrough=this.handleClickThrough.bind(this)),this.touchEventHandler&&(this.touchEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.touchEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this)),this.keyboardEventHandler&&(this.keyboardEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.keyboardEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this));else{this.infoBottom&&(this.infoBottom.style.display="none"),this.nextPageAnchorElement&&(this.nextPageAnchorElement.style.display="none"),this.previousPageAnchorElement&&(this.previousPageAnchorElement.style.display="none"),this.view?.layout==="fixed"?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")):this.view?.atStart()&&this.view?.atEnd()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):this.view?.atEnd()?(this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset")):this.view?.atStart()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"));let i=(0,vh.debounce)(()=>{this.isScrolling=!1},200),o=mt(document,"#iframe-wrapper");o.onscroll=async()=>{this.isScrolling=!0,await this.savePosition(),this.view?.atEnd(),this.view?.layout==="fixed"?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")):(this.settings.isPaginated().then(a=>{a||(this.view?.atStart()&&this.view?.atEnd()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):this.view?.atEnd()?(this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset")):this.view?.atStart()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")))}),this.checkResourcePosition()),i()},this.chapterTitle&&(this.chapterTitle.style.display="none"),this.chapterPosition&&(this.chapterPosition.style.display="none"),this.remainingPositions&&(this.remainingPositions.style.display="none"),this.eventHandler&&(this.eventHandler.onInternalLink=this.handleInternalLink.bind(this),this.eventHandler.onClickThrough=this.handleClickThrough.bind(this)),this.touchEventHandler&&(this.touchEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.touchEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this)),this.keyboardEventHandler&&(this.keyboardEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.keyboardEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this))}}),t?.skipDrawingAnnotations||setTimeout(async()=>{await this.highlighter?.prepareContainers(this.iframes[0].contentWindow),this.highlighter&&(this.rights.enableAnnotations&&this.annotationModule&&await this.annotationModule.drawHighlights(),this.rights.enableBookmarks&&this.bookmarkModule&&await this.bookmarkModule.drawBookmarks(),this.rights.enableSearch&&this.searchModule&&(await this.highlighter.destroyHighlights(it.Search),this.searchModule.drawSearch()),this.rights.enablePageBreaks&&this.pageBreakModule&&(await this.highlighter.destroyHighlights(it.PageBreak),await this.pageBreakModule.drawPageBreaks()),this.rights.enableDefinitions&&this.definitionsModule&&await this.definitionsModule.drawDefinitions())},200))}async loadManifest(){try{let t=(d,h,y=!1)=>{var b=document.createElement("ul");y&&(b=document.createElement("ol")),b.className="sidenav-toc";for(let w of h){let p=document.createElement("li"),m=document.createElement("a"),f=document.createElement("span");m.className="chapter-link",m.tabIndex=-1;let g="";w.Href?(g=this.publication.getAbsoluteHref(w.Href),m.href=g,m.innerHTML=w.Title||"",p.appendChild(m)):(f.innerHTML=w.Title||"",f.className="chapter-title",p.appendChild(f)),w.Children&&w.Children.length>0&&t(p,w.Children,!0),b.appendChild(p)}Ee(b,"click",w=>{if(w.preventDefault(),w.stopPropagation(),w.target&&w.target.tagName.toLowerCase()==="a"){let p=w.target;if(p.className.indexOf("active")!==-1)this.hideView();else{let m={progression:0};if(p.href.indexOf("#")!==-1){let g=p.href.slice(p.href.indexOf("#")+1);g!==void 0&&(m={fragment:g})}let f={href:p.href,locations:m,type:p.type,title:p.title};this.hideView(),this.navigate(f)}}}),d.appendChild(b)},n=this.publication.tableOfContents,i=this.publication.landmarks,o=this.publication.pageList;this.tocView&&(n.length?t(this.tocView,n):this.tocView.parentElement?.parentElement?.removeChild(this.tocView.parentElement)),this.pageListView&&(o?.length?t(this.pageListView,o):this.pageListView.parentElement?.parentElement?.removeChild(this.pageListView.parentElement)),this.landmarksView&&(i?.length?t(this.landmarksView,i):this.landmarksSection.parentElement?.removeChild(this.landmarksSection));let a;this.annotator&&(a=await this.annotator.getLastReadingPosition());let l=this.publication.getStartLink(),u;if(l&&l.Href&&(u=this.publication.getAbsoluteHref(l.Href)),a){let d=this.publication.getAbsoluteHref(a.href);si.default.log(a.href),si.default.log(d),a.href=d,await this.navigate(a)}else if(u){let d={href:u,locations:{progression:0},created:new Date,title:l?.Title};await this.navigate(d)}return new Promise(d=>d())}catch(t){return si.default.error(t),this.abortOnError(t),new Promise((n,i)=>i(t)).catch(()=>{})}}async handleIFrameLoad(){this.errorMessage&&(this.errorMessage.style.display="none"),this.showLoadingMessageAfterDelay();try{let t=0;this.newPosition&&(t=this.newPosition.locations.progression),await this.handleResize(),this.updateBookView({skipDrawingAnnotations:!0}),await this.settings.applyProperties();let n=this.currentChapterLink.href;if(n){let d=this.publication.getPreviousSpineItem(n);d&&d.Href&&(this.previousChapterLink={href:d.Href,title:d.Title,type:d.TypeLink})}this.previousChapterAnchorElement&&(this.previousChapterLink&&this.previousChapterLink.href?(this.previousChapterAnchorElement.href=this.publication.getAbsoluteHref(this.previousChapterLink.href),this.previousChapterAnchorElement.className=this.previousChapterAnchorElement.className.replace(" disabled","")):(this.previousChapterAnchorElement.removeAttribute("href"),this.previousChapterAnchorElement.className+=" disabled"));let i=this.publication.getNextSpineItem(n);i?this.nextChapterLink={href:i.Href,title:i.Title,type:i.TypeLink}:this.nextChapterLink=void 0,this.nextChapterAnchorElement&&(this.nextChapterLink&&this.nextChapterLink.href?(this.nextChapterAnchorElement.href=this.publication.getAbsoluteHref(this.nextChapterLink.href),this.nextChapterAnchorElement.className=this.nextChapterAnchorElement.className.replace(" disabled","")):(this.nextChapterAnchorElement.removeAttribute("href"),this.nextChapterAnchorElement.className+=" disabled")),this.historyModule&&this.historyModule.setup(),this.currentTocUrl!==void 0?this.setActiveTOCItem(this.currentTocUrl):this.setActiveTOCItem(n),this.publication.Metadata.Title&&this.bookTitle&&(this.bookTitle.innerHTML=this.publication.Metadata.Title.toString());let o=this.publication.getSpineItem(n);o!==void 0&&(this.currentChapterLink.title=o.Title,this.currentChapterLink.type=o.TypeLink);let a=this.publication.getTOCItem(n);this.currentTocUrl!==void 0&&(a=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&a!==void 0&&a.Title&&(this.currentChapterLink.title=a.Title),!this.currentChapterLink.type&&a!==void 0&&a.TypeLink&&(this.currentChapterLink.title=a.Title),this.currentChapterLink.title?this.chapterTitle&&(this.chapterTitle.innerHTML="("+this.currentChapterLink.title+")"):this.chapterTitle&&(this.chapterTitle.innerHTML="(Current Chapter)"),await this.injectInjectablesIntoIframeHead(),this.highlighter!==void 0&&await this.highlighter.initialize();let u=this.iframes[0].contentDocument?.body?.querySelector("details");if(u){let d=this;u.addEventListener("toggle",async h=>{await d.view?.setIframeHeight?.(this.iframes[0])})}if(this.eventHandler){for(let d of this.iframes)this.eventHandler.setupEvents(d.contentDocument),this.touchEventHandler.setupEvents(d.contentDocument),this.keyboardEventHandler.setupEvents(d.contentDocument);this.touchEventHandler.setupEvents(this.errorMessage),this.didInitKeyboardEventHandler||(this.keyboardEventHandler.keydown(document),this.didInitKeyboardEventHandler=!0)}if(this.view?.layout!=="fixed"&&this.view?.isScrollMode()&&(this.iframes[0].height="0",this.view?.setIframeHeight?.(this.iframes[0])),this.rights.enableContentProtection&&this.contentProtectionModule&&await this.contentProtectionModule.initialize(),this.rights.enableConsumption&&this.consumptionModule&&await this.consumptionModule.initialize(),this.rights.enableAnnotations&&this.annotationModule&&await this.annotationModule.initialize(),this.rights.enableBookmarks&&this.bookmarkModule&&await this.bookmarkModule.initialize(),this.rights.enableLineFocus&&this.lineFocusModule&&await this.lineFocusModule.initialize(),this.rights.enableTTS&&this.ttsModule){let d=this.iframes[0].contentDocument?.body;await this.ttsModule.initialize(d)}return this.rights.enableTimeline&&this.timelineModule&&await this.timelineModule.initialize(),this.rights.enableMediaOverlays&&this.mediaOverlayModule&&this.hasMediaOverlays&&await this.mediaOverlayModule.initialize(),setTimeout(async()=>{if(this.newElementId){let d=this.iframes[0].contentDocument.getElementById(this.newElementId);this.view?.goToElement?.(d),this.newElementId=void 0}else if(this.newPosition&&this.newPosition.highlight){let d=this.newPosition.highlight?.selectionInfo.rangeInfo.startContainerElementCssSelector;d&&this.view?.goToCssSelector(d)}else t&&t>=0&&this.view?.goToProgression(t);if(this.newPosition=void 0,this.rights?.enableContentProtection&&this.contentProtectionModule!==void 0&&await this.contentProtectionModule.recalculate(10),this.hideLoadingMessage(),this.showIframeContents(),this.rights.enableMediaOverlays&&this.mediaOverlayModule&&this.hasMediaOverlays){let d=this.currentLink();await this.mediaOverlayModule?.initializeResource(d)}await this.updatePositionInfo(),await this.view?.setSize(),setTimeout(()=>{this.mediaOverlayModule&&(this.mediaOverlayModule.settings.resourceReady=!0)},300)},200),new Promise(d=>d())}catch(t){return si.default.error(t),this.abortOnError(t),Promise.reject(t)}}async injectInjectablesIntoIframeHead(){let t=[],n=i=>{let o=new Promise((a,l)=>{i.onload=()=>{a(!0)},i.onerror=u=>{let d=typeof u=="string"?u:`Injectable failed to load at: ${"href"in i?i.href:i.src}`;l(new Error(d))}});t.push(o)};for(let i of this.iframes){let o=i.contentDocument?.head;o&&(i.contentDocument.getElementsByTagName("base").length===0&&o.insertBefore(ut.createBase(this.currentChapterLink.href),o.firstChild),this.injectables?.forEach(l=>{if(l.type==="style"){if(l.fontFamily){if(this.settings.initAddedFont(),!l.systemFont&&l.url){let u=ut.createCssLink(l.url);o.appendChild(u),n(u)}}else if(l.r2before&&l.url){let u=ut.createCssLink(l.url);o.insertBefore(u,o.firstChild),n(u)}else if(l.r2default&&l.url){let u=ut.createCssLink(l.url);o.insertBefore(u,o.childNodes[1]),n(u)}else if(l.r2after&&l.url){l.appearance&&this.settings.initAddedAppearance();let u=ut.createCssLink(l.url);o.appendChild(u),n(u)}else if(l.url){let u=ut.createCssLink(l.url);o.appendChild(u),n(u)}}else if(l.type==="script"&&l.url){let u=ut.createJavascriptLink(l.url,l.async??!1);o.appendChild(u),n(u)}}))}t.length!==0&&await Promise.all(t)}abortOnError(t){if(this.api?.onError){let n=t instanceof Error?t:typeof t=="string"?new Error(t):new Error("An unknown error occurred in the IFrameNavigator.");this.api.onError(n)}else this.errorMessage&&(this.errorMessage.style.display="block"),this.isLoading&&this.hideLoadingMessage()}tryAgain(){this.precessContentForIframe()}precessContentForIframe(){let t=this;var n=this.publication.getSpineIndex(this.currentChapterLink.href),i=(n??0)%2==1;this.showLoadingMessageAfterDelay();function o(d,h){let b=new DOMParser().parseFromString(d,"application/xhtml+xml");b.head&&b.getElementsByTagName("base").length===0&&b.head.insertBefore(ut.createBase(h),b.head.firstChild);let w=b.documentElement.outerHTML,p=t.iframes[0].contentDocument;p&&(p.open(),p.write(w),p.close())}function a(d,h){let b=new DOMParser().parseFromString(d,"application/xhtml+xml");b.head&&b.getElementsByTagName("base").length===0&&b.head.insertBefore(ut.createBase(h),b.head.firstChild);let w=b.documentElement.outerHTML,p=t.iframes[1].contentDocument;p&&(p.open(),p.write(w),p.close())}let l=new URL(this.currentChapterLink.href),u=window.location.protocol===l.protocol&&window.location.port===l.port&&window.location.hostname===l.hostname;if(this.api?.getContent)if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(i){if(this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.api?.getContent(this.currentChapterLink.href).then(d=>{d===void 0?u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(h=>h.text()).then(async h=>{o.call(this,h,this.currentChapterLink.href)}):o.call(this,d,this.currentChapterLink.href)}),this.iframes.length===2)if((n??0)<this.publication.readingOrder.length-1){let d=this.publication.getNextSpineItem(this.currentChapterLink.href);if(d){let h=this.publication.getAbsoluteHref(d.Href);this.currentSpreadLinks.right={href:h},this.api?.getContent(h).then(y=>{y===void 0?u?this.iframes[1].src=h:fetch(h,this.requestConfig).then(b=>b.text()).then(async b=>{a.call(this,b,h),this.currentSpreadLinks.right={href:h}}):a.call(this,y,h)})}}else this.iframes[1].src="about:blank"}else{if((n??0)>0){let d=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(d){let h=this.publication.getAbsoluteHref(d.Href);this.currentSpreadLinks.left={href:h},this.api?.getContent(h).then(y=>{y===void 0?u?this.iframes[0].src=h:fetch(h,this.requestConfig).then(b=>b.text()).then(async b=>{o.call(this,b,h)}):o.call(this,y,h)})}}else this.iframes[0].src="about:blank";this.iframes.length===2&&this.publication.isFixedLayout&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},this.api.getContent(this.currentChapterLink.href).then(d=>{d===void 0?u?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(h=>h.text()).then(async h=>{a.call(this,h,this.currentChapterLink.href)}):a.call(this,d,this.currentChapterLink.href)}))}else this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.api?.getContent(this.currentChapterLink.href).then(d=>{d===void 0?u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(h=>h.text()).then(async h=>{o.call(this,h,this.currentChapterLink.href)}):o.call(this,d,this.currentChapterLink.href)});else this.api?.getContent(this.currentChapterLink.href).then(d=>{this.currentSpreadLinks.left={href:this.currentChapterLink.href},d===void 0?u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(h=>h.text()).then(async h=>{o.call(this,h,this.currentChapterLink.href)}):o.call(this,d,this.currentChapterLink.href)});else if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(i){if(u){if(this.iframes[0].src=this.currentChapterLink.href,this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.iframes.length===2)if((n??0)<this.publication.readingOrder.length-1){let d=this.publication.getNextSpineItem(this.currentChapterLink.href);if(d){let h=this.publication.getAbsoluteHref(d.Href);this.iframes[1].src=h,this.currentSpreadLinks.right={href:h}}}else this.iframes[1].src="about:blank"}else if(fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{o.call(this,d,this.currentChapterLink.href)}),this.iframes.length===2)if((n??0)<this.publication.readingOrder.length-1){let d=this.publication.getNextSpineItem(this.currentChapterLink.href);if(d){let h=this.publication.getAbsoluteHref(d.Href);this.currentSpreadLinks.right={href:h},fetch(h,this.requestConfig).then(y=>y.text()).then(async y=>{a.call(this,y,h)})}}else this.iframes[1].src="about:blank"}else{if((n??0)>0){let d=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(d){let h=this.publication.getAbsoluteHref(d.Href);this.currentSpreadLinks.left={href:h},u?(this.iframes[0].src=h,this.iframes.length===2&&(this.iframes[1].src=this.currentChapterLink.href)):(fetch(h,this.requestConfig).then(y=>y.text()).then(async y=>{o.call(this,y,h)}),this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},fetch(this.currentChapterLink.href,this.requestConfig).then(y=>y.text()).then(async y=>{a.call(this,y,this.currentChapterLink.href)})))}}else this.iframes[0].src="about:blank";this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},u?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{a.call(this,d,this.currentChapterLink.href)}))}else this.currentSpreadLinks.left={href:this.currentChapterLink.href},u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{o.call(this,d,this.currentChapterLink.href)});else this.currentSpreadLinks.left={href:this.currentChapterLink.href},u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{o.call(this,d,this.currentChapterLink.href)});this.publication.isFixedLayout&&setTimeout(()=>{let d,h,y;if(n===0&&this.iframes?.length===2?y=this.iframes[1].contentDocument:y=this.iframes[0].contentDocument,y&&y.body&&(d=getComputedStyle(y.body).height,h=getComputedStyle(y.body).width,parseInt(d?.replace("px",""))===0||parseInt(h?.replace("px",""))===0)){let v=un(y,"head");if(v){let A=Ie(v,"meta[name=viewport]");if(A){var b=A.content,w=b.split(",").reduce((C,O)=>{var[E,T]=O.match(/[^\s;=]+/g);return C[E]=isNaN(Number(T))?T:+T,C},{});d=w.height+"px",h=w.width+"px"}}}var p=n===0&&this.iframes.length===2?this.iframes[1].parentElement?.parentElement:this.iframes[0].parentElement?.parentElement;if(p&&h){var m=(parseInt(getComputedStyle(p).width)-100)/(this.iframes.length===2?parseInt(h?.replace("px",""))*2+200:parseInt(h?.replace("px",""))),f=(parseInt(getComputedStyle(p).height)-100)/parseInt(d?.replace("px","")),g=Math.min(m,f);p.style.transform="scale("+g+")";for(let v of this.iframes)v.style.height=d,v.style.width=h,v.parentElement&&(v.parentElement.style.height=d)}},400)}static goBack(){window.history.back()}handleEditClick(t){var n=t.target;if(this.headerMenu){var i=Ie(document,".sidenav");n.className.indexOf(" active")===-1?(n.className+=" active",i.className+=" expanded",n.innerText="unfold_less",this.sideNavExpanded=!0,this.bookmarkModule?.showBookmarks(),this.annotationModule?.showHighlights()):(n.className=n.className.replace(" active",""),i.className=i.className.replace(" expanded",""),n.innerText="unfold_more",this.sideNavExpanded=!1,this.bookmarkModule?.showBookmarks(),this.annotationModule?.showHighlights())}t.preventDefault(),t.stopPropagation()}get hasMediaOverlays(){return this.publication.hasMediaOverlays}startReadAloud(){this.rights.enableTTS&&this.ttsModule.speakPlay()}startReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.startReadAloud()}stopReadAloud(){this.rights.enableTTS&&this.highlighter?.stopReadAloud()}stopReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.stopReadAloud()}pauseReadAloud(){this.rights.enableTTS&&(this.ttsModule.speakPause(),this.annotationModule!==void 0&&this.annotationModule.drawHighlights())}pauseReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.pauseReadAloud()}resumeReadAloud(){this.rights.enableTTS&&this.ttsModule.speakResume()}resumeReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.resumeReadAloud()}totalResources(){return this.publication.readingOrder.length}mostRecentNavigatedTocItem(){return this.publication.getRelativeHref(this.currentTOCRawLink)}currentResource(){let t=this.currentChapterLink.href;return this.publication.getSpineIndex(t)}currentLink(){if(this.settings.columnCount!==1&&this.currentSpreadLinks.left!==void 0&&this.currentSpreadLinks.right!==void 0){let n=this.publication.getSpineItem(this.currentSpreadLinks.left.href),i=this.publication.getSpineItem(this.currentSpreadLinks.right.href);return[n,i]}let t=this.currentChapterLink.href;return[this.publication.getSpineItem(t)]}tableOfContents(){return this.publication.tableOfContents}readingOrder(){return this.publication.readingOrder}atStart(){return this.view?.atStart()??!1}atEnd(){return this.view?.atEnd()??!1}previousPage(){this.handlePreviousPageClick(void 0)}nextPage(){this.handleNextPageClick(void 0)}previousResource(){this.handlePreviousChapterClick(void 0)}nextResource(){this.handleNextChapterClick(void 0)}goTo(t){let n=t.locations??{progression:0};if(t.href.indexOf("#")!==-1){let a=t.href.slice(t.href.indexOf("#")+1);a!==void 0&&(n=Yt(et({},n),{fragment:a}))}let i=et({},t);i.locations=n;let o=this.publication.getAbsoluteHref(t.href);si.default.log(t.href),si.default.log(o),i.href=o,this.stopReadAloud(),this.navigate(i)}currentLocator(){let t;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let n=this.publication.positionsByHref(this.publication.getRelativeHref(this.currentChapterLink.href)),i=Math.ceil((this.view?.getCurrentPosition()??0)*(n.length-1));t=n[i]}else{let n=this.publication.getTOCItem(this.currentChapterLink.href);n&&(this.currentTocUrl!==void 0&&(n=this.publication.getTOCItem(this.currentTocUrl)),n===void 0&&(n=this.publication.getTOCItemAbsolute(this.currentChapterLink.href)),n&&(t={href:n.Href,type:this.currentChapterLink.type,title:this.currentChapterLink.title,locations:{}}))}return t&&(t.locations.progression=this.view?.getCurrentPosition(),t.displayInfo={resourceScreenIndex:Math.round(this.view?.getCurrentPage()??0),resourceScreenCount:Math.round(this.view?.getPageCount()??0)}),t}positions(){return this.publication.positions?this.publication.positions:[]}goToPosition(t){if(this.publication.positions){let n=this.publication.positions.filter(i=>i.locations.position===parseInt(String(t)))[0];this.goTo(n)}}async goToPage(t){this.pageBreakModule!==void 0&&await this.pageBreakModule.goToPageNumber(t)}snapToSelector(t){let n=this.iframes[0].contentDocument;if(n){si.default.log(t);let i=n.querySelectorAll(t);i.length>0&&this.view?.snap(i[0])}}applyAttributes(t){this.attributes=t,this.view.attributes=t,this.handleResize()}handlePreviousPageClick(t){this.stopReadAloud(),this.view?.layout==="fixed"?this.handlePreviousChapterClick(t):(this.view?.atStart()?this.handlePreviousChapterClick(t):(this.view?.goToPreviousPage?.(),this.updatePositionInfo(),this.savePosition()),t&&(t.preventDefault(),t.stopPropagation()))}handleNextPageClick(t){let n=!0;if(this.sample?.isSampleRead&&this.publication.positions){let i=this.currentLocator(),o=Math.round((i.locations.totalProgression??0)*100);this.sample?.limit&&(n=o<=this.sample?.limit,this.view?.layout==="fixed"&&((!n&&this.sample?.minimum&&i.locations.position)??0<=(this.sample?.minimum??0))&&(n=!0))}(n&&this.sample?.isSampleRead&&this.publication.positions||!this.sample?.isSampleRead||!this.publication.positions)&&(this.stopReadAloud(),this.view?.layout==="fixed"?this.handleNextChapterClick(t):(this.view?.atEnd()?this.handleNextChapterClick(t):(this.view?.goToNextPage?.(),this.updatePositionInfo(),this.savePosition()),t&&(t.preventDefault(),t.stopPropagation()))),!n&&this.sample?.isSampleRead&&this.publication.positions&&t&&(t.preventDefault(),t.stopPropagation())}handleClickThrough(t){}handleInternalLink(t){let n=t.target,i={progression:0},o=n;if(o.href.indexOf("#")!==-1){let l=o.href.slice(o.href.indexOf("#")+1);l!==void 0&&(i={fragment:l})}let a={href:o.href,locations:i,type:o.type,title:o.title};t.preventDefault(),t.stopPropagation(),this.stopReadAloud(),this.navigate(a)}handleNumberOfIframes(){if(this.publication.isFixedLayout){if(this.settings.columnCount!==1&&!window.matchMedia("screen and (max-width: 600px)").matches){if(this.iframes.length===1){var t=document.createElement("iframe");t.setAttribute("SCROLLING","no"),t.setAttribute("allowtransparency","true"),t.style.opacity="1",t.style.border="none",t.style.overflow="hidden",this.iframes.push(t)}let n=document.createElement("div");this.spreads.appendChild(n),n.appendChild(this.iframes[1]),this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 100% 120%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc",n.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, 0% 120%)",n.style.boxShadow="0 0 8px 2px #ccc"}else this.iframes.length===2&&(this.iframes.pop(),this.spreads.lastChild&&this.spreads.removeChild(this.spreads.lastChild)),this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc";this.precessContentForIframe()}}async handleResize(){if(this.isScrolling)return;if(this.publication.isFixedLayout){var t=this.publication.getSpineIndex(this.currentChapterLink.href);let h=tr()-40-(this.attributes?.margin??0);var n=t===0&&this.iframes.length===2?this.iframes[1].parentElement?.parentElement:this.iframes[0].parentElement?.parentElement;if(n){n.style.height=h+40+"px";let y,b,w;t===0&&this.iframes?.length===2?w=this.iframes[1].contentDocument:w=this.iframes[0].contentDocument,w&&w.body&&(y=getComputedStyle(w.body).height,b=getComputedStyle(w.body).width);let p=un(w,"head");if(p){let m=Ie(p,"meta[name=viewport]");if(m){var i=m.content,o=i.split(",").reduce((f,g)=>{var[v,A]=g.match(/[^\s;=]+/g);return f[v]=isNaN(Number(A))?A:+A,f},{});(parseInt(o.height)!==0||parseInt(o.width)!==0)&&(y=o.height+"px",b=o.width+"px")}}var a=(parseInt(getComputedStyle(n).width)-100)/(this.iframes.length===2?parseInt(b?.replace("px",""))*2+200:parseInt(b?.replace("px",""))),l=(parseInt(getComputedStyle(n).height)-100)/parseInt(y?.replace("px","")),u=Math.min(a,l);n.style.transform="scale("+u+")";for(let m of this.iframes)m.style.height=y,m.style.width=b,m.parentElement&&(m.parentElement.style.height=y)}}let d=this.view?.getCurrentPosition();await this.settings.applyProperties(),this.infoTop&&(this.infoTop.style.height=0+"px"),this.infoTop&&(this.infoTop.style.minHeight=0+"px"),this.infoBottom&&(this.infoBottom.style.height=this.attributes?.bottomInfoHeight?this.attributes.bottomInfoHeight+"px":40+"px"),this.view?.layout!=="fixed"&&this.settings.isPaginated().then(h=>{h?(this.view.height=tr()-40-(this.attributes?.margin??0),this.infoBottom&&this.infoBottom.style.removeProperty("display")):this.infoBottom&&(this.infoBottom.style.display="none")}),setTimeout(()=>{this.view?.layout!=="fixed"&&this.view?.isScrollMode()&&this.view?.setIframeHeight?.(this.iframes[0])},100),setTimeout(async()=>{d&&this.view?.goToProgression(d),await this.updatePositionInfo(!1),this.annotationModule!==void 0&&await this.annotationModule.handleResize(),this.bookmarkModule!==void 0&&await this.bookmarkModule.handleResize(),this.searchModule!==void 0&&await this.searchModule.handleResize(),this.definitionsModule!==void 0&&await this.definitionsModule.handleResize(),this.pageBreakModule!==void 0&&await this.pageBreakModule.handleResize(),this.contentProtectionModule!==void 0&&this.contentProtectionModule.handleResize(),this.lineFocusModule!==void 0&&this.lineFocusModule.handleResize(),this.historyModule!==void 0&&this.historyModule.handleResize()},150)}updatePositionInfo(t=!0){if(this.view?.layout==="fixed")this.chapterPosition&&(this.chapterPosition.innerHTML=""),this.remainingPositions&&(this.remainingPositions.innerHTML="");else if(this.view?.isPaginated()){let n=this.currentLocator();if(n){let i=n.displayInfo.resourceScreenIndex,o=n.displayInfo.resourceScreenCount;this.chapterPosition&&(this.chapterPosition.innerHTML="Page "+i+" of "+o)}}else this.chapterPosition&&(this.chapterPosition.innerHTML=""),this.remainingPositions&&(this.remainingPositions.innerHTML="");t&&this.savePosition()}handlePreviousChapterClick(t){if(this.view?.layout==="fixed"&&this.settings.columnCount!==1){let n=this.publication.getSpineIndex(this.currentChapterLink.href)??0;n=n-2,n<0&&(n=0);let i=this.publication.readingOrder[n],o={href:this.publication.getAbsoluteHref(i.Href),locations:{progression:0},type:i.TypeLink,title:i.Title};this.stopReadAloud(),this.navigate(o,!1)}else if(this.previousChapterLink){let n={href:this.publication.getAbsoluteHref(this.previousChapterLink.href),locations:{progression:1},type:this.previousChapterLink.type,title:this.previousChapterLink.title};this.stopReadAloud(),this.navigate(n,!1)}t&&(t.preventDefault(),t.stopPropagation())}handleNextChapterClick(t){if(this.view?.layout==="fixed"&&this.settings.columnCount!==1){let n=this.publication.getSpineIndex(this.currentChapterLink.href)??0;n=n+2,n>=this.publication.readingOrder.length-1&&(n=this.publication.readingOrder.length-1);let i=this.publication.readingOrder[n],o={href:this.publication.getAbsoluteHref(i.Href),locations:{progression:0},type:i.TypeLink,title:i.Title};this.stopReadAloud(),this.navigate(o,!1)}else if(this.nextChapterLink){let n={href:this.publication.getAbsoluteHref(this.nextChapterLink.href),locations:{progression:0},type:this.nextChapterLink.type,title:this.nextChapterLink.title};this.stopReadAloud(),this.navigate(n,!1)}t&&(t.preventDefault(),t.stopPropagation())}hideView(){this.view?.layout!=="fixed"&&this.view?.isScrollMode()&&(document.body.style.overflow="auto")}setActiveTOCItem(t){if(this.tocView){let n=Array.prototype.slice.call(this.tocView.querySelectorAll("li > a"));for(let o of n)o.className=o.className.replace(" active","");let i=this.tocView.querySelector('li > a[href^="'+t+'"]');i&&(i.className+=" active")}}async navigate(t,n=!0){if(this.rights.enableConsumption&&this.consumptionModule&&n&&this.consumptionModule.startReadingSession(t),this.historyModule&&await this.historyModule.push(t,n),this.publication.getTOCItem(t.href)){var o=!1;if(t.href.indexOf("#")!==-1){let a=t.href.slice(0,t.href.indexOf("#"));a===this.currentChapterLink.href&&(o=!0),this.currentChapterLink.href=a,this.currentChapterLink.type=t.type,this.currentChapterLink.title=t.title}else t.href===this.currentChapterLink.href&&(o=!0),this.currentChapterLink.href=t.href,this.currentChapterLink.type=t.type,this.currentChapterLink.title=t.title;if(this.currentSpreadLinks.left!==void 0&&this.currentSpreadLinks.right!==void 0&&(t.href===this.currentSpreadLinks.left.href||t.href===this.currentSpreadLinks.right.href))return;if(o){if(t.href.indexOf("#")!==-1){let y=t.href.slice(t.href.indexOf("#")+1);t.locations={fragment:y}}if(this.newPosition=t,this.currentTOCRawLink=t.href,t.locations.fragment===void 0?this.currentTocUrl=void 0:(this.newElementId=t.locations.fragment,this.currentTocUrl=this.currentChapterLink.href+"#"+this.newElementId),this.newElementId){for(let y of this.iframes){let b=y.contentDocument.getElementById(this.newElementId);this.view?.goToElement?.(b)}this.newElementId=void 0}else if(t.highlight){let y=t.highlight?.selectionInfo.rangeInfo.startContainerElementCssSelector;y&&this.view?.goToCssSelector(y)}else this.view?.goToProgression(t.locations.progression??0);let a=this.currentChapterLink.href,l=this.publication.getPreviousSpineItem(a);l&&l.Href&&(this.previousChapterLink={href:l.Href,type:l.TypeLink,title:l.Title}),this.previousChapterAnchorElement&&(this.previousChapterLink?(this.previousChapterAnchorElement.href=this.publication.getAbsoluteHref(this.previousChapterLink.href),this.previousChapterAnchorElement.className=this.previousChapterAnchorElement.className.replace(" disabled","")):(this.previousChapterAnchorElement.removeAttribute("href"),this.previousChapterAnchorElement.className+=" disabled"));let u=this.publication.getNextSpineItem(a);u?this.nextChapterLink={href:u.Href,type:u.TypeLink,title:u.Title}:this.nextChapterLink=void 0,this.nextChapterAnchorElement&&(this.nextChapterLink?(this.nextChapterAnchorElement.href=this.publication.getAbsoluteHref(this.nextChapterLink.href),this.nextChapterAnchorElement.className=this.nextChapterAnchorElement.className.replace(" disabled","")):(this.nextChapterAnchorElement.removeAttribute("href"),this.nextChapterAnchorElement.className+=" disabled")),this.currentTocUrl!==void 0?this.setActiveTOCItem(this.currentTocUrl):this.setActiveTOCItem(a),this.publication.Metadata.Title&&this.bookTitle&&(this.bookTitle.innerHTML=this.publication.Metadata.Title.toString());let d=this.publication.getSpineItem(a);d!==void 0&&(this.currentChapterLink.title=d.Title,this.currentChapterLink.type=d.TypeLink);let h=this.publication.getTOCItem(a);this.currentTocUrl!==void 0&&(h=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&h!==void 0&&h.Title&&(this.currentChapterLink.title=h.Title),!this.currentChapterLink.type&&h!==void 0&&h.TypeLink&&(this.currentChapterLink.title=h.Title),this.currentChapterLink.title?this.chapterTitle&&(this.chapterTitle.innerHTML="("+this.currentChapterLink.title+")"):this.chapterTitle&&(this.chapterTitle.innerHTML="(Current Chapter)"),await this.updatePositionInfo()}else this.lineFocusModule!==void 0&&this.lineFocusModule.disableLineFocus(!1),this.searchModule!==void 0&&this.searchModule.clearSearch(),t.locations.fragment===void 0?this.currentTocUrl=void 0:(this.newElementId=t.locations.fragment,this.currentTocUrl=this.currentChapterLink.href+"#"+this.newElementId),this.hideIframeContents(),this.showLoadingMessageAfterDelay(),t.locations===void 0&&(t.locations={progression:0}),this.newPosition=t,this.currentTOCRawLink=t.href,this.precessContentForIframe(),this.rights.enableContentProtection&&this.contentProtectionModule!==void 0&&await this.contentProtectionModule.initializeResource(),this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&await this.mediaOverlayModule.initializeResource(this.currentLink()),this.rights.enableContentProtection&&this.contentProtectionModule!==void 0&&await this.contentProtectionModule.recalculate(300),this.bookmarkModule&&(await this.bookmarkModule.drawBookmarks(),await this.bookmarkModule.showBookmarks()),this.pageBreakModule&&(await this.highlighter?.destroyHighlights(it.PageBreak),await this.pageBreakModule.drawPageBreaks()),this.rights.enableSearch&&this.searchModule!==void 0&&this.highlighter!==void 0&&(await this.highlighter.destroyHighlights(it.Search),this.searchModule.drawSearch()),this.rights.enableDefinitions&&this.definitionsModule&&this.highlighter&&await this.definitionsModule.drawDefinitions(),this.rights.enableConsumption&&this.consumptionModule&&this.consumptionModule.continueReadingSession(t),this.view?.layout==="fixed"?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.api?.resourceFitsScreen&&this.api?.resourceFitsScreen(),this.emit("resource.fits")):this.settings.isPaginated().then(a=>{a||(this.view?.atStart()&&this.view?.atEnd()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):this.view?.atEnd()?(this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset")):this.view?.atStart()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")))})}else{let a=this.publication.getStartLink(),l;if(a&&a.Href&&(l=this.publication.getAbsoluteHref(a.Href),l)){let u={href:l,locations:{progression:0},created:new Date,title:a.Title};await this.navigate(u)}}}showIframeContents(){this.isBeingStyled=!1,setTimeout(()=>{this.isBeingStyled||this.iframes.forEach(t=>{t.style.opacity="1",t.style.border="none",t.style.overflow="hidden"})},150)}showLoadingMessageAfterDelay(){this.isLoading=!0,this.isLoading&&this.loadingMessage&&(this.loadingMessage.style.display="block",this.loadingMessage.classList.add("is-loading")),this.mediaOverlayModule!==void 0&&(this.mediaOverlayModule.settings.resourceReady=!1)}hideIframeContents(){this.isBeingStyled=!0,this.iframes.forEach(t=>{t.style.opacity="0",t.style.border="none",t.style.overflow="hidden"})}hideLoadingMessage(){setTimeout(()=>{this.isLoading=!1,this.loadingMessage&&(this.loadingMessage.style.display="none",this.loadingMessage.classList.remove("is-loading")),this.view?.layout!=="fixed"&&(this.view?.atStart()&&this.view?.atEnd()?(this.api?.resourceFitsScreen&&this.api?.resourceFitsScreen(),this.emit("resource.fits")):this.view?.atEnd()?(this.api?.resourceAtEnd&&this.api?.resourceAtEnd(),this.emit("resource.end")):this.view?.atStart()&&(this.api?.resourceAtStart&&this.api?.resourceAtStart(),this.emit("resource.start"))),this.api?.resourceReady&&this.api?.resourceReady(),this.emit("resource.ready")},150)}saveCurrentReadingPosition(){if(this.annotator){var t=this.publication.getTOCItem(this.currentChapterLink.href);this.currentTocUrl!==void 0&&(t=this.publication.getTOCItem(this.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.currentChapterLink.href));let n={progression:this.view?.getCurrentPosition()};if(t){if(t.Href.indexOf("#")!==-1){let o=t.Href.slice(t.Href.indexOf("#")+1);o!==void 0&&(n={progression:this.view?.getCurrentPosition(),fragment:o})}let i;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let o=this.publication.positionsByHref(this.publication.getRelativeHref(t.Href));if(o.length>0){let a=Math.ceil((n.progression??0)*(o.length-1)),l=o[a];l&&(l.locations.fragment=n.fragment,i=Yt(et({},l),{href:t.Href,created:new Date,title:this.currentChapterLink.title}))}}else i={href:t.Href,locations:n,created:new Date,type:this.currentChapterLink.type,title:this.currentChapterLink.title};i&&(this.sample?.isSampleRead&&this.publication.positions&&this.sampleReadEventHandler?.enforceSampleRead(i),this.api?.updateCurrentLocation?this.api?.updateCurrentLocation(i).then(async o=>(si.default.log("api updated current location",i),this.annotator?.saveLastReadingPosition(i))):(si.default.log("save last reading position",i),this.annotator.saveLastReadingPosition(i)),this.consumptionModule&&this.consumptionModule.continueReadingSession(i))}}}static createBase(t){let n=document.createElement("base");return n.target="_self",n.href=t,n}static createCssLink(t){let n=document.createElement("link");return n.rel="stylesheet",n.type="text/css",n.href=t,n}static createJavascriptLink(t,n){let i=document.createElement("script");return i.type="text/javascript",i.src=t,i.async=n,i}activateMarker(t,n){this.annotationModule!==void 0&&(this.annotationModule.activeAnnotationMarkerId===void 0||this.annotationModule.activeAnnotationMarkerId!==t?(this.annotationModule.activeAnnotationMarkerId=t,this.annotationModule.activeAnnotationMarkerPosition=n,this.highlighter&&(this.highlighter.activeAnnotationMarkerId=t)):this.deactivateMarker())}deactivateMarker(){this.annotationModule!==void 0&&(this.annotationModule.activeAnnotationMarkerId=void 0,this.annotationModule.activeAnnotationMarkerPosition=void 0,this.highlighter&&(this.highlighter.activeAnnotationMarkerId=void 0))}showLayer(t){let n="#",i=new Xa("layer-on","layer-off",!0,t,"layer-"+t);switch(t){case"annotations":case"highlights":n+=qe.R2_ID_HIGHLIGHTS_CONTAINER,i.name=qe.R2_ID_HIGHLIGHTS_CONTAINER;break;case"readaloud":n+=qe.R2_ID_READALOUD_CONTAINER,i.name=qe.R2_ID_READALOUD_CONTAINER;break;case"pagebreak":n+=qe.R2_ID_PAGEBREAK_CONTAINER,i.name=qe.R2_ID_PAGEBREAK_CONTAINER;break;case"search":n+=qe.R2_ID_SEARCH_CONTAINER,i.name=qe.R2_ID_SEARCH_CONTAINER;break;case"definitions":n+=qe.R2_ID_DEFINITIONS_CONTAINER,i.name=qe.R2_ID_DEFINITIONS_CONTAINER;break}this.highlighter?.layerSettings.saveProperty(i);let o=this.iframes[0].contentDocument;if(o){let a=Ie(o,n);a&&(a.style.display="block")}}hideLayer(t){let n="#",i=new Xa("layer-on","layer-off",!1,t,"layer-"+t);switch(t){case"annotations":case"highlights":n+=qe.R2_ID_HIGHLIGHTS_CONTAINER,i.name=qe.R2_ID_HIGHLIGHTS_CONTAINER;break;case"readaloud":n+=qe.R2_ID_READALOUD_CONTAINER,i.name=qe.R2_ID_READALOUD_CONTAINER;break;case"pagebreak":n+=qe.R2_ID_PAGEBREAK_CONTAINER,i.name=qe.R2_ID_PAGEBREAK_CONTAINER;break;case"search":n+=qe.R2_ID_SEARCH_CONTAINER,i.name=qe.R2_ID_SEARCH_CONTAINER;break;case"definitions":n+=qe.R2_ID_DEFINITIONS_CONTAINER,i.name=qe.R2_ID_DEFINITIONS_CONTAINER;break}this.highlighter?.layerSettings.saveProperty(i);let o=this.iframes[0].contentDocument;if(o){let a=Ie(o,n);a&&(a.style.display="none")}}};H();var Rt=class{constructor(t){this.store=t.store}getLastReadingPosition(){let t=this.store.get(Rt.LAST_READING_POSITION);return t?JSON.parse(t):null}initLastReadingPosition(t){if(typeof t=="string")this.store.set(Rt.LAST_READING_POSITION,t);else{let n=JSON.stringify(t);this.store.set(Rt.LAST_READING_POSITION,n)}}saveLastReadingPosition(t){if(typeof t=="string")this.store.set(Rt.LAST_READING_POSITION,t);else{let n=JSON.stringify(t);this.store.set(Rt.LAST_READING_POSITION,n)}}initBookmarks(t){if(typeof t=="string"){let n=JSON.parse(t);this.store.set(Rt.BOOKMARKS,JSON.stringify(n))}else this.store.set(Rt.BOOKMARKS,JSON.stringify(t));return t}saveBookmark(t){let n=this.store.get(Rt.BOOKMARKS);if(n){let i=JSON.parse(n);i.push(t),this.store.set(Rt.BOOKMARKS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(Rt.BOOKMARKS,JSON.stringify(i))}return t}locatorExists(t,n){let i;switch(n){case Si.Bookmark:i=Rt.BOOKMARKS;break}let o=this.store.get(i);return o&&JSON.parse(o).filter(u=>u.href===t.href&&u.locations.progression===t.locations.progression).length>0?t:null}deleteBookmark(t){let n=this.store.get(Rt.BOOKMARKS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.id!==t.id),this.store.set(Rt.BOOKMARKS,JSON.stringify(i))}return t}getBookmarks(t){let n=this.store.get(Rt.BOOKMARKS);if(n){let i=JSON.parse(n);if(t){let o=i.filter(a=>a.href===t);return o=o.sort((a,l)=>{if(a.locations.progression&&l.locations.progression)return a.locations.progression-l.locations.progression}),o}return i=i.sort((o,a)=>{if(o.locations.progression&&a.locations.progression)return o.locations.progression-a.locations.progression}),i}return[]}initAnnotations(t){let n;typeof t=="string"?n=JSON.parse(t):n=t;let i=[];return n.forEach(o=>{let a=`${o.highlight.selectionInfo.rangeInfo.startContainerElementCssSelector}${o.highlight.selectionInfo.rangeInfo.startContainerChildTextNodeIndex}${o.highlight.selectionInfo.rangeInfo.startOffset}${o.highlight.selectionInfo.rangeInfo.endContainerElementCssSelector}${o.highlight.selectionInfo.rangeInfo.endContainerChildTextNodeIndex}${o.highlight.selectionInfo.rangeInfo.endOffset}`,l=Fi.hash(a);o.highlight.id="R2_HIGHLIGHT_"+l;let u;o.highlight.color?u=o.highlight.color:o.color&&(u=o.color),Qe.isHexColor(u)&&(u=Qe.hexToRgbString(u)),o.highlight.color=u,o.highlight.pointerInteraction=!0,o.highlight.selectionInfo.cleanText=o.highlight.selectionInfo.rawText.trim().replace(/\n/g," ").replace(/\s\s+/g," "),i.push(o)}),this.store.set(Rt.ANNOTATIONS,JSON.stringify(i)),i}saveTemporarySelectionInfo(t){this.store.set(Rt.SELECTIONINFO,JSON.stringify(t))}getTemporarySelectionInfo(t){let n=this.store.get(Rt.SELECTIONINFO);if(n){let i=JSON.parse(n);return i.range=Jd(t,i.rangeInfo),i}return[]}deleteTemporarySelectionInfo(){this.store.remove(Rt.SELECTIONINFO)}saveAnnotation(t){let n=this.store.get(Rt.ANNOTATIONS);if(n){let i=JSON.parse(n);i.push(t),this.store.set(Rt.ANNOTATIONS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(Rt.ANNOTATIONS,JSON.stringify(i))}return t}deleteAnnotation(t){let n=this.store.get(Rt.ANNOTATIONS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.id!==t),this.store.set(Rt.ANNOTATIONS,JSON.stringify(i))}return t}deleteSelectedAnnotation(t){let n=this.store.get(Rt.ANNOTATIONS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.highlight?.id!==t.highlight.id),this.store.set(Rt.ANNOTATIONS,JSON.stringify(i))}return t}getAnnotations(){let t=this.store.get(Rt.ANNOTATIONS);if(t){let n=JSON.parse(t);return n=n.sort((i,o)=>{if(i.locations.progression&&o.locations.progression)return i.locations.progression-o.locations.progression}),n}return[]}getAnnotationsByChapter(t){let n=this.store.get(Rt.ANNOTATIONS);if(n){let i=JSON.parse(n);return i=i.filter(o=>o.href===t),i=i.sort((o,a)=>{if(o.locations.progression&&a.locations.progression)return o.locations.progression-a.locations.progression}),i}return[]}getAnnotationPosition(t,n){let i=this.store.get(Rt.ANNOTATIONS);if(i){let a=JSON.parse(i).filter(l=>l.highlight?.id===t||l.id===t);if(a.length>0){let l=n.document.getElementById(`${a[0].highlight.id}`);if(l){let u=0;if(l.hasChildNodes)for(let d=0;d<l.childNodes.length;d++){let h=l.childNodes[d],y=parseInt(h.style.top.replace("px",""));(y<u||u===0)&&(u=y)}else u=parseInt(l.style.top.replace("px",""));return u}}}return null}getAnnotationElement(t,n){let i=this.store.get(Rt.ANNOTATIONS);if(i){let a=JSON.parse(i).filter(l=>l.highlight?.id===t);if(a.length>0){let l=n.document.getElementById(`${a[0].highlight.id}`);if(l){let u=0;if(l.hasChildNodes)for(let d=0;d<l.childNodes.length;d++){let h=l.childNodes[d],y=parseInt(h.style.top.replace("px",""));if(y<u||u===0)return u=y,h}else u=parseInt(l.style.top.replace("px",""));return l}}}return null}getAnnotation(t){let n=this.store.get(Rt.ANNOTATIONS);if(n){let o=JSON.parse(n).filter(a=>a.highlight?.id===t.id);if(o.length>0)return o[0]}return null}getAnnotationByID(t){let n=this.store.get(Rt.ANNOTATIONS);if(n){let o=JSON.parse(n).filter(a=>a.highlight?.id===t);if(o.length>0)return o[0]}return null}},Io=Rt;Io.LAST_READING_POSITION="last-reading-position",Io.BOOKMARKS="bookmarks",Io.ANNOTATIONS="annotations",Io.SELECTIONINFO="selectionInfo";H();H();var wh=class{constructor(){this.store={}}get(t){return this.store[t]||null}set(t,n){this.store[t]=n}remove(t){this.store[t]=null}};var _a=class{constructor(t){this.prefix=t.prefix,this.useLocalStorage=t.useLocalStorage;try{let n=t.prefix+"-"+String(Math.random());this.useLocalStorage?(window.localStorage.setItem(n,"test"),window.localStorage.removeItem(n)):(window.sessionStorage.setItem(n,"test"),window.sessionStorage.removeItem(n)),this.fallbackStore=null}catch(n){this.fallbackStore=new wh}}getLocalStorageKey(t){return this.prefix+"-"+t}get(t){let n;return this.fallbackStore?n=this.fallbackStore.get(t):this.useLocalStorage?n=window.localStorage.getItem(this.getLocalStorageKey(t)):n=window.sessionStorage.getItem(this.getLocalStorageKey(t)),n}set(t,n){this.fallbackStore?this.fallbackStore.set(t,n):this.useLocalStorage?window.localStorage.setItem(this.getLocalStorageKey(t),n):window.sessionStorage.setItem(this.getLocalStorageKey(t),n)}remove(t){this.fallbackStore?this.fallbackStore.remove(t):this.useLocalStorage?window.localStorage.removeItem(this.getLocalStorageKey(t)):window.sessionStorage.removeItem(this.getLocalStorageKey(t))}};H();var ex=nt(za()),tx=nt(Un());var Ul=class extends ex.Link{};Ul=Lc([(0,tx.JsonObject)()],Ul);function $l(r){let t,n,i,o;if(r instanceof Array)return r.map(function(a){return typeof a=="object"&&(a=$l(a)),a});t={};for(n in r)r.hasOwnProperty(n)&&(i=(n.charAt(0).toLowerCase()+n.slice(1)||n).toString(),o=r[n],(o instanceof Array||o!==null&&o.constructor===Object)&&(o=$l(o)),i==="href1"?t.href=o:i==="typeLink"?t.type=o:t[i]=o);return t}H();var nx=nt(Jt()),xg=class{constructor(t){this.LAYERSETTINGS="layerSetting";this.store=t,this.initialize()}static async create(t){let n=new this(t.store);return new Promise(i=>i(n))}async stop(){nx.default.log("MediaOverlay settings stop")}async initialize(){this.userProperties=await this.getLayerSettings()}async getLayerSettings(){let t=new Wr,n=await this.store.get(this.LAYERSETTINGS);if(n){let i=JSON.parse(n);t.properties=i}return t}async saveProperty(t){let n=await this.store.get(this.LAYERSETTINGS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.name!==t.name),i.push(t),await this.store.set(this.LAYERSETTINGS,JSON.stringify(i))}else{let i=[];i.push(t),await this.store.set(this.LAYERSETTINGS,JSON.stringify(i))}return new Promise(i=>i(t))}async getProperty(t){let n=await this.store.get(this.LAYERSETTINGS);if(n){let i=JSON.parse(n);return i=i.filter(o=>o.name===t),i.length===0?null:i[0]}return null}};H();var dx=nt(Ag()),Sa=nt(cx());H();var ux="grab-to-pan-grab",Eh,B8,_h,N8,Sh,D8,Cg=class{constructor(t){_n(this,Eh);_n(this,_h);_n(this,Sh);this.element=t.element,this.document=t.element.ownerDocument,typeof t.ignoreTarget=="function"&&(this.ignoreTarget=t.ignoreTarget),this.onActiveChanged=t.onActiveChanged,this.activate=this.activate.bind(this),this.deactivate=this.deactivate.bind(this),this.toggle=this.toggle.bind(this),this._onMouseDown=Dr(this,Eh,B8).bind(this),this._onMouseMove=Dr(this,_h,N8).bind(this),this._endPan=Dr(this,Sh,D8).bind(this);let n=this.overlay=document.createElement("div");n.className="grab-to-pan-grabbing"}activate(){this.active||(this.active=!0,this.element.addEventListener("mousedown",this._onMouseDown,!0),this.element.classList.add(ux),this.onActiveChanged?.(!0))}deactivate(){this.active&&(this.active=!1,this.element.removeEventListener("mousedown",this._onMouseDown,!0),this._endPan(),this.element.classList.remove(ux),this.onActiveChanged?.(!1))}toggle(){this.active?this.deactivate():this.activate()}ignoreTarget(t){return t.matches("a[href], a[href] *, input, textarea, button, button *, select, option")}};Eh=new WeakSet,B8=function(t){if(t.button!==0||this.ignoreTarget(t.target))return;if(t.originalTarget)try{t.originalTarget.tagName}catch(i){return}this.scrollLeftStart=this.element.scrollLeft,this.scrollTopStart=this.element.scrollTop,this.clientXStart=t.clientX,this.clientYStart=t.clientY,this.document.addEventListener("mousemove",this._onMouseMove,!0),this.document.addEventListener("mouseup",this._endPan,!0),this.element.addEventListener("scroll",this._endPan,!0),t.preventDefault(),t.stopPropagation();let n=document.activeElement;n&&!n.contains(t.target)&&n.blur()},_h=new WeakSet,N8=function(t){if(this.element.removeEventListener("scroll",this._endPan,!0),!(t.buttons&1)){this._endPan();return}let n=t.clientX-this.clientXStart,i=t.clientY-this.clientYStart,o=this.scrollTopStart-i,a=this.scrollLeftStart-n;this.element.scrollTo?this.element.scrollTo({top:o,left:a,behavior:"instant"}):(this.element.scrollTop=o,this.element.scrollLeft=a),this.overlay.parentNode||document.body.append(this.overlay)},Sh=new WeakSet,D8=function(){this.element.removeEventListener("scroll",this._endPan,!0),this.document.removeEventListener("mousemove",this._onMouseMove,!0),this.document.removeEventListener("mouseup",this._endPan,!0),this.overlay.remove()};var Aa;(function(n){n[n.Page=0]="Page",n[n.Width=1]="Width"})(Aa||(Aa={}));var Ar=class extends dx.default{constructor(t,n,i){super();this.pdfDoc=null;this.pageNum=1;this.scaleType=0;this.pageRendering=!1;this.pageNumPending=null;this.scale=1;this.resourceIndex=0;this.onResize=()=>{clearTimeout(this.timeout),this.timeout=setTimeout(this.handleResize.bind(this),200)};this.settings=t,this.publication=n,this.api=i}static async create(t){let n=new this(t.settings,t.publication,t.api);return await n.start(t.mainElement,t.headerMenu,t.footerMenu),new Promise(i=>i(n))}async start(t,n,i){this.headerMenu=n,this.footerMenu=i,this.mainElement=t,this.resourceIndex=0,this.resource=this.publication.readingOrder[this.resourceIndex],Sa.GlobalWorkerOptions.workerSrc="//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.14.305/pdf.worker.js",this.wrapper=mt(this.mainElement,"main#iframe-wrapper"),this.pdfContainer=mt(this.mainElement,"#pdf-container"),this.handTool=new Cg({element:this.pdfContainer});let o=this,a=document.createElement("div");a.id="loadingpdf",a.innerHTML=gh,a.style.width=getComputedStyle(this.wrapper).width,a.style.height=getComputedStyle(this.wrapper).height,a.style.display="flex",a.style.zIndex="100",a.style.position="absolute",a.style.alignItems="center",a.style.justifyContent="center",a.style.background="white",a.className="loading is-loading",this.pdfContainer.appendChild(a),(0,Sa.getDocument)(this.publication.getAbsoluteHref(this.resource.Href)).promise.then(function(l){o.pdfDoc=l,o.loadPDFJS(o.pageNum)}),this.setupEvents()}async handleResize(){this.loadPDFJS(this.pageNum)}setupEvents(){Ee(window,"resize",this.onResize)}loadPDFJS(t){let n=this,i=1;this.wrapper.style.height="calc(100vh - 10px)",this.pdfContainer.style.height="calc(100vh - 10px)",this.pdfContainer.style.flexDirection="column";let o=document.getElementsByTagName("canvas");Array.from(o).forEach(function(l){l?.parentNode?.removeChild(l)});function a(l){let u=document.createElement("canvas");u.id=String(i),u.style.border="1px solid gray",u.style.margin="1px";let d=l.getViewport({scale:n.scale});if(n.scale===1){let p=n.wrapper.clientHeight/d.height,m=n.wrapper.clientWidth/d.width;n.scaleType===0?d=l.getViewport({scale:p<m?p:m}):d=l.getViewport({scale:m})}n.pdfContainer.appendChild(u);let h=u.getContext("2d");u.height=d.height,u.width=d.width;let y={canvasContext:h,viewport:d},b=document.getElementById("loadingpdf");b.style.display="flex",b.style.width=getComputedStyle(n.wrapper).width,b.style.height=getComputedStyle(n.wrapper).height,l.render(y).promise.then(function(){i<n.pdfDoc.numPages?(i++,n.pdfDoc.getPage(i).then(a)):(document.getElementById(String(t))?.scrollIntoView(),b.style.display="none",n.api?.resourceReady&&n.api?.resourceReady(),n.emit("resource.ready"))})}this.pdfDoc.getPage(i).then(a)}queueRenderPage(t){let n=this;n.pageRendering?n.pageNumPending=t:(this.pageNum=t,document.getElementById(String(t))?.scrollIntoView())}readingOrder(){return this.publication.readingOrder}tableOfContents(){return this.publication.tableOfContents}currentResource(){}totalResources(){return this.publication.readingOrder.length}currentLocator(){}positions(){return this.publication.positions?this.publication.positions:[]}nextPage(){let t=this;if(t.pageNum>=t.pdfDoc.numPages){this.nextResource();return}this.pageNum++,this.queueRenderPage(t.pageNum)}previousPage(){let t=this;if(t.pageNum<=1){this.previousResource();return}t.pageNum--,t.queueRenderPage(t.pageNum)}nextResource(){let t=this;this.resourceIndex>=this.publication.readingOrder.length-1||(t.resourceIndex++,t.resource=this.publication.readingOrder[t.resourceIndex],(0,Sa.getDocument)(this.publication.getAbsoluteHref(this.resource.Href)).promise.then(function(n){t.pdfDoc=n,t.pageNum=1,t.loadPDFJS(t.pageNum)}))}previousResource(){let t=this;this.resourceIndex!==0&&(t.resourceIndex--,t.resource=this.publication.readingOrder[t.resourceIndex],(0,Sa.getDocument)(this.publication.getAbsoluteHref(this.resource.Href)).promise.then(function(n){t.pdfDoc=n,t.pageNum=t.pdfDoc.numPages,t.loadPDFJS(t.pageNum)}))}goTo(t){let n=new URL(t.href);if(n.searchParams.has("start")){let i=n.searchParams.get("start");i&&this.queueRenderPage(parseInt(i))}else this.queueRenderPage(1)}goToPosition(t){this.queueRenderPage(t)}async goToPage(t){this.queueRenderPage(t)}fitToWidth(){this.scale=1,this.scaleType=1,this.loadPDFJS(this.pageNum)}fitToPage(){this.scale=1,this.scaleType=0,this.loadPDFJS(this.pageNum)}zoomIn(){this.scale=this.scale+.2,this.loadPDFJS(this.pageNum)}zoomOut(){this.scale=this.scale-.2,this.loadPDFJS(this.pageNum)}activateHand(){this.handTool.activate()}deactivateHand(){this.handTool.deactivate()}async scroll(t,n){t?(n==="horizontal"?this.pdfContainer.style.flexDirection="row":this.pdfContainer.style.flexDirection="column",this.pdfContainer.style.overflow="auto"):(this.pdfContainer.style.flexDirection="column",this.pdfContainer.style.overflow="hidden")}stop(){je(window,"resize",this.onResize)}};var Bo=class{constructor(t,n,i,o,a,l,u,d,h,y,b,w,p,m,f,g,v,A){this.settings=t;this.navigator=n;this.highlighter=i;this.bookmarkModule=o;this.annotationModule=a;this.ttsSettings=l;this.ttsModule=u;this.searchModule=d;this.definitionsModule=h;this.contentProtectionModule=y;this.timelineModule=b;this.mediaOverlaySettings=w;this.mediaOverlayModule=p;this.pageBreakModule=m;this.lineFocusModule=f;this.historyModule=g;this.citationModule=v;this.consumptionModule=A;this.startReadAloud=()=>{this.navigator instanceof ut&&this.navigator.startReadAloud()};this.stopReadAloud=()=>{this.navigator instanceof ut&&this.navigator.stopReadAloud()};this.pauseReadAloud=()=>{this.navigator instanceof ut&&this.navigator.pauseReadAloud()};this.resumeReadAloud=()=>{this.navigator instanceof ut&&this.navigator.resumeReadAloud()};this.startReadAlong=()=>{this.navigator instanceof ut&&this.navigator.startReadAlong()};this.stopReadAlong=()=>{this.navigator instanceof ut&&this.navigator.stopReadAlong()};this.pauseReadAlong=()=>{this.navigator instanceof ut&&this.navigator.pauseReadAlong()};this.resumeReadAlong=()=>{this.navigator instanceof ut&&this.navigator.resumeReadAlong()};this.saveBookmark=async()=>await this.bookmarkModule?.saveBookmark()??!1;this.saveBookmarkPlus=async()=>this.bookmarkModule?.saveBookmarkPlus();this.deleteBookmark=async t=>await this.bookmarkModule?.deleteBookmark(t)??!1;this.deleteAnnotation=async t=>await this.annotationModule?.deleteAnnotation(t)??!1;this.addAnnotation=async t=>await this.annotationModule?.addAnnotation(t)??!1;this.hideAnnotationLayer=()=>this.annotationModule?.hideAnnotationLayer();this.showAnnotationLayer=()=>this.annotationModule?.showAnnotationLayer();this.hideLayer=t=>this.navigator instanceof ut?this.navigator?.hideLayer(t):!1;this.showLayer=t=>this.navigator instanceof ut?this.navigator?.showLayer(t):!1;this.activateMarker=(t,n)=>this.navigator instanceof ut?this.navigator?.activateMarker(t,n):!1;this.deactivateMarker=()=>this.navigator instanceof ut?this.navigator?.deactivateMarker():!1;this.clearDefinitions=async()=>{await this.definitionsModule?.clearDefinitions()};this.addDefinition=async t=>{await this.definitionsModule?.addDefinition(t)};this.historyBack=async()=>this.historyModule?.historyBack();this.historyForward=async()=>this.historyModule?.historyForward();this.search=async(t,n)=>await this.searchModule?.search(t,n)??[];this.goToSearchIndex=async(t,n,i)=>{this.navigator instanceof ut&&this.navigator.rights.enableSearch&&await this.searchModule?.goToSearchIndex(t,n,i)};this.goToSearchID=async(t,n,i)=>{this.navigator instanceof ut&&this.navigator.rights.enableSearch&&await this.searchModule?.goToSearchID(t,n,i)};this.clearSearch=async()=>{this.navigator instanceof ut&&this.navigator.rights.enableSearch&&await this.searchModule?.clearSearch()};this.resetUserSettings=async()=>await this.settings.resetUserSettings();this.applyUserSettings=async t=>await this.settings.applyUserSettings(t);this.scroll=async(t,n)=>this.navigator instanceof Ar?this.navigator.scroll(t,n):await this.settings.scroll(t);this.increase=async t=>{this.isTTSIncrementable(t)?this.navigator instanceof ut&&this.navigator.rights.enableTTS&&await this.ttsSettings?.increase(t):this.isMOIncrementable(t)?this.navigator instanceof ut&&this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.increase(t):await this.settings.increase(t)};this.decrease=async t=>{this.isTTSIncrementable(t)?this.navigator instanceof ut&&this.navigator.rights.enableTTS&&await this.ttsSettings?.decrease(t):this.isMOIncrementable(t)?this.navigator instanceof ut&&this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.decrease(t):await this.settings.decrease(t)};this.resetTTSSettings=()=>{this.navigator instanceof ut&&this.navigator.rights.enableTTS&&this.ttsSettings?.resetTTSSettings()};this.applyTTSSettings=async t=>{this.navigator instanceof ut&&this.navigator.rights.enableTTS&&await this.ttsSettings?.applyTTSSettings(t)};this.applyPreferredVoice=async t=>{this.navigator instanceof ut&&this.navigator.rights.enableTTS&&await this.ttsSettings?.applyPreferredVoice(t)};this.resetMediaOverlaySettings=async()=>{this.navigator instanceof ut&&this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.resetMediaOverlaySettings()};this.applyMediaOverlaySettings=async t=>{this.navigator instanceof ut&&this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.applyMediaOverlaySettings(t)};this.goTo=async t=>{this.navigator.goTo(t)};this.goToPosition=async t=>this.navigator.goToPosition(t);this.goToPage=async t=>{await this.navigator.goToPage(t)};this.fitToPage=()=>{this.navigator instanceof Ar&&this.navigator.fitToPage()};this.fitToWidth=()=>{this.navigator instanceof Ar&&this.navigator.fitToWidth()};this.zoomIn=()=>{this.navigator instanceof Ar&&this.navigator.zoomIn()};this.zoomOut=()=>{this.navigator instanceof Ar&&this.navigator.zoomOut()};this.activateHand=()=>{this.navigator instanceof Ar&&this.navigator.activateHand()};this.deactivateHand=()=>{this.navigator instanceof Ar&&this.navigator.deactivateHand()};this.copyToClipboard=t=>{this.contentProtectionModule?.copyToClipboard(t)};this.nextResource=()=>{this.navigator.nextResource()};this.previousResource=()=>{this.navigator.previousResource()};this.nextPage=async()=>{this.navigator.nextPage()};this.previousPage=async()=>{this.navigator.previousPage()};this.snapToSelector=async t=>{this.navigator instanceof ut&&this.navigator.snapToSelector(t)};this.applyAttributes=t=>{this.navigator instanceof ut&&this.navigator.applyAttributes(t)};this.stop=()=>{document.body.onscroll=()=>{},this.navigator.stop(),this.settings.stop(),this.ttsSettings?.stop(),this.ttsModule?.stop(),this.bookmarkModule?.stop(),this.annotationModule?.stop(),this.searchModule?.stop(),this.definitionsModule?.stop(),this.contentProtectionModule?.stop(),this.timelineModule?.stop(),this.mediaOverlaySettings?.stop(),this.mediaOverlayModule?.stop(),this.pageBreakModule?.stop(),this.lineFocusModule?.stop(),this.citationModule?.stop(),this.consumptionModule?.stop()}}addEventListener(){this.navigator instanceof ut&&this.navigator.addListener(arguments[0],arguments[1])}static async load(t){let n=t.rights??{autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1};n.enableContentProtection&&t.protection&&await ya.setupPreloadProtection(t.protection);let i=mt(document,"#D2Reader-Container"),o=Ie(document,"#headerMenu"),a=Ie(document,"#footerMenu"),l=t.url,u;t.publication?(u=Ks(t.publication,bo),u.manifestUrl=new URL(l)):u=await bo.fromUrl(l,t.requestConfig);let d=new _a({prefix:u.manifestUrl,useLocalStorage:t.useLocalStorage??!1}),h=new _a({prefix:"r2d2bc-reader",useLocalStorage:t.useLocalStorage??!1}),y=new _a({prefix:"r2d2bc-layers",useLocalStorage:t.useLocalStorage??!1}),b=new Io({store:d});if(u.sample=t.sample,n=j8(n,u),u.Metadata.ConformsTo&&u.Metadata.ConformsTo.includes("https://readium.org/webpub-manifest/profiles/pdf")){let w=await Ao.create({store:h,initialUserSettings:t.userSettings,layout:""}),p=await Ar.create({mainElement:i,publication:u,settings:w,api:t.api});return new Bo(w,p)}else{n.autoGeneratePositions?await u.autoGeneratePositions(t.requestConfig):(t.services?.positions&&await u.fetchPositionsFromService(t.services?.positions.href,t.requestConfig),t.services?.weight&&await u.fetchWeightsFromService(t.services?.weight.href,t.requestConfig));let w=await xg.create({store:y}),p=await Ao.create({store:h,initialUserSettings:t.userSettings,headerMenu:o,api:t.api,injectables:(u.Metadata.Rendition?.Layout??"unknown")==="fixed"?t.injectablesFixed:t.injectables,layout:(u.Metadata.Rendition?.Layout??"unknown")==="fixed"?"fixed":"reflowable"}),m=await Qe.create(et({layerSettings:w},t.highlighter)),f=n.enableBookmarks?await ds.create(et({annotator:b,headerMenu:o,rights:n,publication:u,initialAnnotations:t.initialAnnotations},t.bookmarks)):void 0,g=n.enableAnnotations?await us.create(et({annotator:b,rights:n,publication:u,initialAnnotations:t.initialAnnotations,highlighter:m,headerMenu:o},t.annotations)):void 0,v=n.enableTTS,A=v?await _g.create({store:h,initialTTSSettings:t.tts,headerMenu:o}):void 0,C;v&&A&&(C=await va.create(et({tts:A,headerMenu:o,rights:n,highlighter:m},t.tts)));let O=n.enableSearch?await Il.create(et({headerMenu:o,publication:u,highlighter:m},t.search)):void 0,E=n.enableDefinitions?await jl.create(et({publication:u,highlighter:m},t.define)):void 0,T=n.enableTimeline?await Rl.create({publication:u}):void 0,I=n.enableContentProtection?await ya.create(et({},t.protection)):void 0,M=n.enableCitations?await Ea.create(et({publication:u,highlighter:m},t.citations)):void 0,j=n.enableMediaOverlays,U=j?await Q0.create(et({store:h,initialMediaOverlaySettings:t.mediaOverlays,headerMenu:o},t.mediaOverlays)):void 0,B=j?await Ol.create(et({publication:u,settings:U},t.mediaOverlays)):void 0,q=n.enablePageBreaks&&u.isReflowable?await Nl.create(et({publication:u,headerMenu:o},t.pagebreak)):void 0,z=n.enableLineFocus?await wa.create(et({publication:u,highlighter:m},t.lineFocus)):void 0,ne=n.enableHistory?await Hl.create({annotator:b,publication:u,headerMenu:o}):void 0,oe=n.enableConsumption?await Tl.create(et({publication:u},t.consumption)):void 0,ae=await ut.create({mainElement:i,headerMenu:o,footerMenu:a,publication:u,settings:p,annotator:b,initialLastReadingPosition:t.lastReadingPosition,api:t.api,rights:n,tts:t.tts,sample:t.sample,requestConfig:t.requestConfig,injectables:(u.Metadata.Rendition?.Layout??"unknown")==="fixed"?t.injectablesFixed??[]:t.injectables,attributes:t.attributes,services:t.services,highlighter:m,modules:[f,g,C,O,E,T,I,M,B,q,z,ne,oe]});return new Bo(p,ae,m,f,g,A,C,O,E,I,T,U,B,q,z,ne,M,oe)}}get hasMediaOverlays(){return this.navigator instanceof ut?this.navigator.hasMediaOverlays:!1}get tableOfContents(){return $l(this.navigator.tableOfContents())??[]}get readingOrder(){return $l(this.navigator.readingOrder())??[]}get bookmarks(){return this.bookmarkModule?.getBookmarks()??[]}get annotations(){return this.annotationModule?.getAnnotations()}get history(){return this.historyModule?.history}get historyCurrentIndex(){return this.historyModule?.historyCurrentIndex}get currentResource(){return this.navigator.currentResource()}get mostRecentNavigatedTocItem(){return this.navigator instanceof ut?this.navigator.mostRecentNavigatedTocItem():!1}get totalResources(){return this.navigator.totalResources()}get publicationLanguage(){return this.navigator.publication.Metadata.Language}get currentSettings(){return this.settings.currentSettings}isTTSIncrementable(t){return t==="pitch"||t==="rate"||t==="volume"}isMOIncrementable(t){return t==="mo_rate"||t==="mo_volume"}get currentLocator(){return this.navigator.currentLocator()}get positions(){return this.navigator.positions()}get atStart(){return this.navigator instanceof ut?this.navigator.atStart():!1}get atEnd(){return this.navigator instanceof ut?this.navigator.atEnd():!1}async applyLineFocusSettings(t){if(t.lines&&this.lineFocusModule){let n=this.lineFocusModule.properties.lines??1;this.lineFocusModule.index=this.lineFocusModule.index*n/parseInt(t.lines),this.lineFocusModule.index=Math.abs(parseInt(this.lineFocusModule.index.toFixed())),this.lineFocusModule.properties.lines=parseInt(t.lines),this.lineFocusModule.isActive&&await this.lineFocusModule.enableLineFocus()}t.debug!==void 0&&this.lineFocusModule&&(this.lineFocusModule.isDebug=t.debug,this.lineFocusModule.isActive&&await this.lineFocusModule.enableLineFocus())}lineUp(){this.lineFocusModule?.lineUp()}lineDown(){this.lineFocusModule?.lineDown()}async enableLineFocus(){await this.lineFocusModule?.enableLineFocus()}async lineFocus(t){t?await this.lineFocusModule?.enableLineFocus():this.lineFocusModule?.disableLineFocus()}disableLineFocus(){this.lineFocusModule?.disableLineFocus()}};function j8(r,t){return t.isFixedLayout&&(r.enableAnnotations=!1,r.enableSearch=!1,r.enableTTS=!1,r.enableDefinitions=!1,r.enablePageBreaks=!1,r.enableLineFocus=!1),t.sample?.isSampleRead&&(r.enableAnnotations=!1,r.enableSearch=!1,r.enableTTS=!1,r.enableDefinitions=!1,r.enableTimeline=!1,r.enableMediaOverlays=!1,r.enablePageBreaks=!1,r.enableLineFocus=!1),r}var F8=Bo,H8=Bo.load;return U8;})();
|
|
86
|
+
`;var vh=nt(So());H();var ba=class{constructor(t){this.onBackwardSwipe=()=>{};this.onForwardSwipe=()=>{};this.setupEvents=t=>{let n=null,i=null,o=this;t&&(t.addEventListener("touchstart",function(a){a.changedTouches.length===1&&(n=a)},!1),t.addEventListener("touchend",function(a){if(a.changedTouches.length!==1||!n)return;let l=n.changedTouches[0],u=a.changedTouches[0];if(!l)return;let d=window.devicePixelRatio,h=(l.clientX-u.clientX)/d,y=(l.clientY-u.clientY)/d;if(Math.abs(h)<ba.TAP_TOLERANCE&&Math.abs(y)<ba.TAP_TOLERANCE){if(i){n=null,i=null;return}if(a.timeStamp-n.timeStamp>ba.LONG_PRESS_MS){n=null,i=null;return}n=null,i=a;return}if(i=null,a.timeStamp-n.timeStamp>ba.SLOW_SWIPE_MS){n=null;return}let b=(l.clientY-u.clientY)/(l.clientX-u.clientX);if(Math.abs(b)>.5){n=null;return}h<0?o.onBackwardSwipe(a):o.onForwardSwipe(a),n=null},!1))};this.navigator=t}},ys=ba;ys.TAP_TOLERANCE=10,ys.LONG_PRESS_MS=500,ys.SLOW_SWIPE_MS=500;H();var mh=class{constructor(t){this.onBackwardSwipe=()=>{};this.onForwardSwipe=()=>{};this.setupEvents=t=>{t&&(this.focusin(t),this.keydown(t))};this.focusin=t=>{let n=this;t.addEventListener("focusin",function(i){n.navigator.view?.snap(i.target)},!0)};this.keydown=t=>{let n=this;this.navigator.rights.customKeyboardEvents||t.addEventListener("keydown",function(i){let o=i.target;if(/input|select|option|textarea/i.test(o.tagName)||!(o.ownerDocument||o).defaultView.getSelection().isCollapsed)return;switch(i.key){case"ArrowRight":n.onForwardSwipe(i);break;case"ArrowLeft":n.onBackwardSwipe(i);break}switch(i.code){case"Space":i.ctrlKey?n.onBackwardSwipe(i):n.onForwardSwipe(i);break}},!1)};this.navigator=t}};H();var $A=nt(So()),yh=class{constructor(t){this.enforceSampleRead=(0,$A.debounce)(t=>{let n=Math.round(t.locations.totalProgression*100),i=!1;this.navigator.sample?.limit&&(i=n<=this.navigator.sample?.limit,this.navigator.view?.layout==="fixed"&&!i&&this.navigator.sample?.minimum&&t.locations.position<=this.navigator.sample?.minimum&&(i=!0));let o={37:1,38:0,39:1,40:1,32:1,33:1,34:1,35:1,36:1};function a(m){m.preventDefault()}function l(m){o[m.keyCode]&&!i&&a(m)}let u=!1,d=Object.defineProperty&&Object.defineProperty({},"passive",{get:function(){u=!0}});window.addEventListener("test",function(){},d);let h=u?{passive:!1}:!1;function y(m){m=m||window.event;let f=Math.max(-1,Math.min(1,m.wheelDelta||-m.detail));return f===-1&&!i&&m.preventDefault(),!1}let b;function w(m){m=m||window.event;let f=m.target||m.srcElement,g=m.touches[0].clientY;if(!(g>b)){if(g<b&&!i)return f.className.match(/\baltNav\b/)||(m.returnValue=!1,m.cancelable&&(m.cancelBubble=!0),m.preventDefault&&m.cancelable&&(m.preventDefault(),m.stopPropagation())),!1}return b=g,!1}function p(m){return m=m||window.event,b=m.touches[0].clientY,!1}window.addEventListener("mousewheel",y,h),window.addEventListener("DOMMouseScroll",y,h),window.addEventListener("keydown",l,h),window.addEventListener("touchmove",w,h),window.addEventListener("touchstart",p,h),i?(this.navigator.iframes[0].focus(),this.navigator.errorMessage&&(this.navigator.errorMessage.style.display="none",this.navigator.errorMessage.style.removeProperty("background-color"))):(this.navigator.iframes[0].blur(),this.navigator.errorMessage&&(this.navigator.errorMessage.style.display="block",this.navigator.errorMessage.style.backgroundColor="rgb(255, 255, 255)",this.navigator.errorMessage.innerHTML=this.navigator.sample?.popup??""))},300);this.navigator=t}};H();var Bl=nt(Jt()),Nl=class{static async create(t){let n=new this(t.publication,t,t.headerMenu);return await n.start(),n}constructor(t,n,i){this.headerMenu=i,this.publication=t,this.properties=n}async stop(){Bl.default.log("Page Break module stop")}async start(){this.headerMenu&&(this.goToPageView=Ie(this.headerMenu,"#sidenav-section-gotopage")),this.headerMenu&&(this.goToPageNumberInput=Ie(this.headerMenu,"#goToPageNumberInput")),this.headerMenu&&(this.goToPageNumberButton=Ie(this.headerMenu,"#goToPageNumberButton")),Ee(this.goToPageNumberInput,"keypress",this.goToPageNumber.bind(this)),Ee(this.goToPageNumberButton,"click",this.goToPageNumber.bind(this)),this.goToPageView&&(this.publication.pageList?.length||this.goToPageView.parentElement?.removeChild(this.goToPageView)),setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("pagebreak"):this.navigator.showLayer("pagebreak")},10)}async goToPageNumber(t){if(this.goToPageNumberInput.value&&(t.key==="Enter"||t.type==="click")){var n=this.publication.pageList?.filter(o=>o.Href.slice(o.Href.indexOf("#")+1).replace(/[^0-9]/g,"")===this.goToPageNumberInput.value);if(n&&n.length>0){var i=n[0];let o={progression:0};if(i.Href.indexOf("#")!==-1){let l=i.Href.slice(i.Href.indexOf("#")+1);l!==null&&(o={fragment:l})}let a={href:this.publication.getAbsoluteHref(i.Href),locations:o,type:i.TypeLink,title:i.Title};this.navigator.goTo(a)}}}async handleResize(){await this.navigator.highlighter?.destroyHighlights(it.PageBreak),await this.drawPageBreaks()}async drawPageBreaks(){setTimeout(()=>{let t=this.navigator.iframes[0].contentDocument?.body,n=t?.querySelectorAll('[*|type="pagebreak"]');n?.length===0&&(n=t?.querySelectorAll("[epub\\:type='pagebreak']"));let i=this;function o(a){try{let l=i.navigator.iframes[0].contentDocument;return l?wn(a,l,Co):""}catch(l){return Bl.default.log("uniqueCssSelector:"),Bl.default.error(l),""}}if(n)for(let a=0;a<n.length;a++){let l=n[a];Bl.default.log(l);let u=l.innerHTML,d=!1;l.innerHTML.length===0&&(u=l.getAttribute("title")??"",l.innerHTML=u,d=!0),l.innerHTML.length===0&&(u=(l.getAttribute("id")??"").replace(/[^0-9]/g,""),l.innerHTML=u,d=!0);let h=this.navigator.iframes[0].contentDocument;if(h){let y=this.navigator.highlighter?.dom(h.body).getWindow().document.createRange(),b=this.navigator.highlighter?.dom(h.body).getSelection();if(b.removeAllRanges(),y.selectNodeContents(l),b.addRange(y),!b.isCollapsed){let w=Xr(y,o);b.removeAllRanges(),w&&this.createPageBreakHighlight({rangeInfo:w,cleanText:"",rawText:""},u)}}d&&(l.innerHTML="")}},200)}createPageBreakHighlight(t,n){try{let o=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,a=Fi.hash(o),l="R2_PAGEBREAK_"+a;var i=!1;let u={color:"#000000",id:l,pointerInteraction:i,selectionInfo:t,marker:Ve.Custom,icon:{id:"pageBreak",title:n,color:"#000000",position:"left"},type:it.PageBreak};tn.push(u);let d=this.navigator.highlighter?.createHighlightDom(this.navigator.iframes[0].contentWindow,u);return u.position=parseInt((d?.hasChildNodes()?d.childNodes[0]:d).style.top.replace("px","")),u}catch(o){throw"Can't create highlight: "+o}}};H();var qA=nt(E0());var WA=nt(So());var Ct=nt(Jt()),va=class{constructor(t,n,i,o,a,l){this.voices=[];this.hasEventListener=!1;this.startX=0;this.startY=0;this.index=0;this.userScrolled=!1;this.scrollPartial=!1;this.speaking=!1;this.restartIndex=-1;this.ttsQueueIndex=-1;this.ttsQueue=void 0;this.ttsPlayQueueIndexDebounced=(0,WA.debounce)((t,n)=>{this.restartIndex>=0?(this.ttsQueueIndex=this.restartIndex,this.restartIndex=-1):this.ttsQueueIndex=t,this.ttsQueue=n,this.ttsPlayQueueIndex(this.ttsQueueIndex,n)},150);this.tts=t,this.headerMenu=l,this.rights=n,this.highlighter=i,this.properties=o,this.api=a}initialize(t){this.highlighter!==void 0&&(this.tts.setControls(),this.tts.onRestart(this.restart.bind(this)),this.body=t,this.clean=(0,qA.default)(this.body.innerHTML,{allowedTags:[],allowedAttributes:{}}),this.wrapper=mt(document,"#iframe-wrapper"),window.speechSynthesis.getVoices(),this.initVoices(!0),this.hasEventListener||(this.hasEventListener=!0,Ee(document,"wheel",this.wheel.bind(this)),Ee(this.body,"wheel",this.wheel.bind(this)),Ee(document,"keydown",this.wheel.bind(this)),Ee(this.navigator.iframes[0].contentDocument,"keydown",this.wheel.bind(this))),Ee(this.body,"mousedown",this.clickStart.bind(this)),Ee(this.body,"mouseup",this.click.bind(this)))}clickStart(t){"clientX"in t&&(this.startX=t.clientX),"clientY"in t&&(this.startY=t.clientY)}click(t){let n=0,i=0;if("clientX"in t&&(n=t.clientX),"clientY"in t&&(i=t.clientY),window.speechSynthesis.speaking&&this.speaking&&n===this.startX&&i===this.startY){let o=this.navigator.iframes[0].contentDocument;if(o){let a=this.highlighter.dom(o.body).getSelection(),l=a.getRangeAt(0),u=a.anchorNode;for(;l.toString().indexOf(" ")!==0;)try{l.setStart(u,l.startOffset-1)}catch(y){break}l.setStart(u,l.startOffset+1);do l.setEnd(u,u.length<l.endOffset?l.endOffset+1:u.length);while(l.toString().indexOf(" ")===-1&&l.toString().trim()!=="");let h=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body;if(this.ttsQueue&&h){let y=this.findTtsQueueItemIndex(this.ttsQueue,a.anchorNode,a.anchorNode,a.anchorOffset,h);a.removeAllRanges(),y>=0&&(window.speechSynthesis.cancel(),this.restartIndex=y,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}}}}initVoices(t){function n(){return new Promise(function(o,a){let l=window.speechSynthesis,u;u=setInterval(()=>{l.getVoices().length!==0&&(o(l.getVoices()),clearInterval(u))},10)})}n().then(async o=>{if(Ct.default.log(o),this.voices=[],o.forEach(l=>{l.localService===!0&&this.voices.push(l)}),Ct.default.log(this.voices),t&&this.headerMenu){var a=Ie(this.headerMenu,"#preferred-languages");a&&this.voices.forEach(l=>{var u=document.createElement("option");u.value=l.name+":"+l.lang,u.innerHTML=l.name+" ("+l.lang+")",a.add(u)})}})}cancel(t=!0){t&&(this.api?.stopped&&this.api?.stopped(),this.navigator.emit("readaloud.stopped","stopped")),this.userScrolled=!1,this.speaking=!1,setTimeout(()=>{window.speechSynthesis.cancel()},0),this._ttsQueueItemHighlightsWord&&(this.navigator.highlighter?.destroyHighlights(it.ReadAloud),this._ttsQueueItemHighlightsWord=void 0)}async speak(t,n,i){n||this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.deactivate(),this.api?.started&&this.api?.started(),this.navigator.emit("readaloud.started","started");let o=this;this.userScrolled=!1,this.cancel(!1);let a;if(n){let w=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body,p=this.navigator.iframes[0].contentDocument;if(p){let m=this.highlighter.dom(p.body).getSelection();if(m.isCollapsed){let f=o.navigator.iframes[0].contentDocument,g=o.navigator.annotationModule?.annotator?.getTemporarySelectionInfo(f);m.addRange(g.range)}if(w){var l=this.generateTtsQueue(w);if(!l.length)return;var u=this.findTtsQueueItemIndex(l,m.anchorNode,m.anchorNode,m.anchorOffset,w),d=this.findTtsQueueItemIndex(l,m.focusNode,m.focusNode,m.focusOffset,w);let f=bs(l,u),g=bs(l,d);var h;if(f&&t&&t.cleanText){let v=vs(f),A=t.rangeInfo.startOffset,C=t.cleanText;if(g&&u+1===d){let E=vs(g);A=(v+" "+E).indexOf(t.cleanText),C=v.slice(A,v.length),h=t.cleanText.replace(C,"").trim()}else if(d>u){let E="";for(let T=u+1;T<d;T++){let I=bs(l,T);if(I){let M=vs(I);E+=M,h=t.cleanText.replace(M,"")}}if(g){let T=vs(g);E+=" "+T}A=(v+" "+E).indexOf(t.cleanText),C=v.slice(A,v.length),h=h.replace(C,"").trim()}a=new SpeechSynthesisUtterance(C),a.rate=this.tts.rate,a.pitch=this.tts.pitch,a.volume=this.tts.volume,this.setVoice(this,a),Ct.default.log(t),Ct.default.log(C,t.range?.commonAncestorContainer.textContent),Ct.default.log(f),Ct.default.log(f.item.textNodes),Ct.default.log(A),Ct.default.log(f.item.combinedText);let O=f.item.textNodes.filter(E=>E===t.range?.commonAncestorContainer)[0];Ct.default.log(O),a.onboundary=E=>{this.updateTTSInfo(f,E.charIndex,E.charLength,A,a.text)}}}}}else a=new SpeechSynthesisUtterance(this.clean);a.rate=this.tts.rate,a.pitch=this.tts.pitch,a.volume=this.tts.volume,this.setVoice(o,a),this.index=0;function y(){a.onend=function(){if(d>u)if(u=u+1,u!==d){let b=bs(l,u);if(b){let w=vs(b);a=new SpeechSynthesisUtterance(w),a.rate=o.tts.rate,a.pitch=o.tts.pitch,a.volume=o.tts.volume,o.setVoice(o,a),a.onboundary=p=>{o.updateTTSInfo(b,p.charIndex,p.charLength,0,a.text)},setTimeout(()=>{window.speechSynthesis.speak(a)},0),y()}}else{let b=bs(l,u);b&&(a=new SpeechSynthesisUtterance(h),a.rate=o.tts.rate,a.pitch=o.tts.pitch,a.volume=o.tts.volume,o.setVoice(o,a),a.onboundary=w=>{o.updateTTSInfo(b,w.charIndex,w.charLength,0,a.text)},setTimeout(()=>{window.speechSynthesis.speak(a)},0),y()),u>d&&(Ct.default.log("utterance ended"),o.highlighter.doneSpeaking(),o.api?.finished(),o.navigator.emit("readaloud.finished","finished"))}else Ct.default.log("utterance ended"),o.highlighter.doneSpeaking(),o.api?.finished(),o.navigator.emit("readaloud.finished","finished")}}setTimeout(()=>{window.speechSynthesis.speak(a),n||this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)},0),y(),i()}setVoice(t,n){Ct.default.log("this.tts.voice.lang",this.tts.voice.lang);let i=!0;this.tts.voice&&this.tts.voice.lang&&(i=this.tts.voice.lang.indexOf("-")!==-1,i||(this.tts.voice.lang=this.tts.voice.lang.replace("_","-"),i=!0)),Ct.default.log("initialVoiceHasHyphen",i),Ct.default.log("voices",this.voices);let o;i?(o=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(h=>{var y=h.lang.replace("_","-");return y===this.tts.voice.lang&&h.name===this.tts.voice.name})[0]:void 0,o===void 0&&(o=this.tts.voice&&this.tts.voice.lang?this.voices.filter(h=>h.lang.replace("_","-")===this.tts.voice.lang)[0]:void 0)):(o=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(h=>h.lang===this.tts.voice.lang&&h.name===this.tts.voice.name)[0]:void 0,o===void 0&&(o=this.tts.voice&&this.tts.voice.lang?this.voices.filter(h=>h.lang===this.tts.voice.lang)[0]:void 0)),Ct.default.log("initialVoice",o);let a=t.navigator.publication.Metadata.Language[0].indexOf("-")!==-1;Ct.default.log("publicationVoiceHasHyphen",a);let l;a?l=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(h=>{var y=h.lang.replace("_","-");return y.startsWith(t.navigator.publication.Metadata.Language[0])||y.endsWith(t.navigator.publication.Metadata.Language[0].toUpperCase())})[0]:void 0:l=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(h=>h.lang.startsWith(t.navigator.publication.Metadata.Language[0])||h.lang.endsWith(t.navigator.publication.Metadata.Language[0].toUpperCase()))[0]:void 0,Ct.default.log("publicationVoice",l);let u=navigator.language.indexOf("-")!==-1;Ct.default.log("defaultVoiceHasHyphen",u);let d;u?d=this.voices.filter(h=>h.lang.replace("_","-")===navigator.language&&h.localService)[0]:d=this.voices.filter(h=>h.lang===navigator.language&&h.localService)[0],d===void 0&&(d=this.voices.filter(h=>h.lang.includes(navigator.language)&&h.localService)[0]),Ct.default.log("defaultVoice",d),o?(Ct.default.log("initialVoice"),n.voice=o):l?(Ct.default.log("publicationVoice"),n.voice=l):d&&(Ct.default.log("defaultVoice"),n.voice=d),n.voice!==void 0&&n.voice!==null&&(n.lang=n.voice.lang,Ct.default.log("utterance.voice.lang",n.voice.lang),Ct.default.log("utterance.lang",n.lang)),Ct.default.log("navigator.language",navigator.language)}speakPlay(){this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.deactivate(),this.scrollPartial=!0,this.cancel(!1),this.api?.started&&this.api?.started(),this.navigator.emit("readaloud.started","started");let t=this,i=document.querySelector("main#iframe-wrapper iframe").contentWindow?.document.body;if(i){let l=function(){let u=t.highlighter.visibleTextRects[0],d=t.navigator.iframes[0].contentDocument;if(d){let h=t.highlighter.dom(d.body).getWindow().document.createRange(),y=t.highlighter.dom(t.navigator.iframes[0].contentDocument?.body).getSelection();y.removeAllRanges(),h.selectNodeContents(u.node),y.addRange(h);let b=0,w=y.focusNode,p=y.focusOffset;y.collapse(y.anchorNode,y.anchorOffset);for(let m=0;m<b;m++)y.modify("move","forward","line");if(y.extend(w,p),y.collapse(y.anchorNode,y.anchorOffset),i){let m=t.findTtsQueueItemIndex(o,y.anchorNode,y.anchorNode,y.anchorOffset,i);m>=0&&(a=m)}y.removeAllRanges()}},o=this.generateTtsQueue(i);if(!o.length)return;let a=0;l(),a<0&&(a=0),setTimeout(()=>{this.startTTSSession(o,a)},200)}this.navigator.rights.enableContentProtection&&this.navigator.contentProtectionModule?.recalculate(200)}speakPause(){window.speechSynthesis.speaking&&(this.api?.paused&&this.api?.paused(),this.navigator.emit("readaloud.paused","paused"),this.userScrolled=!1,window.speechSynthesis.pause(),this.speaking=!1,this._ttsQueueItemHighlightsWord&&(this.navigator.highlighter?.destroyHighlights(it.ReadAloud),this._ttsQueueItemHighlightsWord=void 0))}speakResume(){window.speechSynthesis.speaking&&(this.api?.resumed&&this.api?.resumed(),this.navigator.emit("readaloud.resumed","resumed"),this.userScrolled=!1,window.speechSynthesis.resume(),this.speaking=!0)}static async create(t){let n=new this(t.tts,t.rights,t.highlighter,t,t.api,t.headerMenu);return await n.start(),n}async start(){if(this.headerMenu){var t=Ie(this.headerMenu,"#menu-button-tts");t&&t.parentElement?.style.removeProperty("display")}setTimeout(()=>{this.properties?.hideLayer?this.navigator.hideLayer("readaloud"):this.navigator.showLayer("readaloud")},10)}wheel(t){if(t instanceof KeyboardEvent)switch(t.key){case"ArrowUp":this.userScrolled=!0;break;case"ArrowDown":this.userScrolled=!0;break}else this.userScrolled=!0}stop(){Ct.default.log("TTS module stop"),je(document,"wheel",this.wheel.bind(this)),je(this.body,"wheel",this.wheel.bind(this)),je(document,"keydown",this.wheel.bind(this)),je(this.navigator.iframes[0].contentDocument,"keydown",this.wheel.bind(this)),je(this.body,"click",this.click.bind(this))}generateTtsQueue(t){let n=[],i=[];function o(d){if(d.nodeType!==Node.TEXT_NODE||!d.nodeValue||!d.nodeValue.trim().length)return;let h=i[i.length-1];if(!h)return;let y=d.parentElement?GA(d.parentElement):void 0,b=d.parentElement?R8(d.parentElement):void 0,w=n[n.length-1];(!w||w.parentElement!==h||w.lang!==y||w.dir!==b)&&(w={combinedText:"",dir:b,lang:y,parentElement:h,textNodes:[]},n.push(w)),w.textNodes.push(d)}let a=!0;function l(d){if(d.nodeType!==Node.ELEMENT_NODE)return;let h=a||d.matches("h1, h2, h3, h4, h5, h6, p, th, td, caption, li, blockquote, q, dt, dd, figcaption, div, pre");a=!1,h&&i.push(d);for(let y of d.childNodes)switch(y.nodeType){case Node.ELEMENT_NODE:let b=y;if(!b.matches("img, sup, sub, audio, video, source, button, canvas, del, dialog, embed, form, head, iframe, meter, noscript, object, s, script, select, style, textarea"))l(b);else if(b.tagName&&b.tagName.toLowerCase()==="img"&&b.src){let p=b.getAttribute("alt");if(p){let m=p.trim();if(m){let f=GA(b),g=void 0;n.push({combinedText:m,dir:g,lang:f,parentElement:b,textNodes:[]})}}}break;case Node.TEXT_NODE:i.length!==0&&o(y);break;default:break}h&&i.pop()}l(t);function u(d){if(!d.textNodes||!d.textNodes.length){(!d.combinedText||!d.combinedText.length)&&(d.combinedText="");return}d.combinedText=P8(d.textNodes,!0).replace(/[\r\n]/g," ");let h=d.parentElement;for(;h;){if(h.tagName){let y=h.tagName.toLowerCase();if(y==="pre"||y==="code"||y==="video"||y==="audio")break}h=h.parentElement}}for(let d of n)u(d);return n}findTtsQueueItemIndex(t,n,i,o,a){let l=0;for(let u of t){if(i&&u.textNodes){if(u.textNodes.includes(i))return l}else if(n===u.parentElement||u.parentElement!==n.ownerDocument.body&&u.parentElement!==a&&u.parentElement.contains(n)||n.contains(u.parentElement))return l;l++}return-1}restart(){window.speechSynthesis.speaking&&(window.speechSynthesis.cancel(),this.restartIndex=this.ttsQueueIndex,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}startTTSSession(t,n){if(!bs(t,n)){this.cancel();return}this.speaking=!0,this.ttsPlayQueueIndexDebounced(n,t)}ttsPlayQueueIndex(t,n){if(t<0){this.cancel();return}let i=bs(n,t);if(!i){this.cancel();return}let o=vs(i);if(!o){this.cancel();return}let a=new SpeechSynthesisUtterance(o);a.rate=this.tts.rate,a.pitch=this.tts.pitch,a.volume=this.tts.volume;let l=this;this.setVoice(l,a),a.onboundary=u=>{Ct.default.log(u.name),this.updateTTSInfo(i,u.charIndex,u.charLength,0,a.text)},setTimeout(()=>{window.speechSynthesis.speak(a),l.speaking||window.speechSynthesis.pause()},0),a.onend=function(){l.speaking&&l.ttsPlayQueueIndexDebounced(t+1,n)}}updateTTSInfo(t,n,i,o,a){if(!t)return;Ct.default.log(t,n,i,a);let l=a||vs(t);if(n>=0&&a){let u=a.slice(0,n+1).search(/\S+$/),d=a.slice(n).search(/\s/),h=d<0?a.slice(u):a.slice(u,d+n),y=u+h.length;if(i===void 0){let b=a.substring(n).match(/^[a-z\d']*/i);b&&(i=b[0].length)}i===void 0&&(i=h.length),this.wrapHighlightWord(t,a,n+o,i,h,u,y)}return l}wrapHighlightWord(t,n,i,o,a,l,u){Ct.default.log(t),Ct.default.log(n),Ct.default.log(i,o,a,l,u),this._ttsQueueItemHighlightsWord&&(this.navigator.highlighter?.destroyHighlights(it.ReadAloud),this._ttsQueueItemHighlightsWord=void 0);let d=t.item,h=i,y=0,b,w=-1,p,m=-1,f=h+o;for(let g of d.textNodes){if(!g.nodeValue&&g.nodeValue!=="")continue;let v=g.nodeValue.length;if(y+=v,b||h<y&&(b=g,w=v-(y-h)),b&&f<=y&&(p=g,m=v-(y-f)),p)break}if(b&&p){let A=function(E){try{let T=v.navigator.iframes[0].contentDocument;return T?wn(E,T,Co):""}catch(T){return Ct.default.log("uniqueCssSelector:"),Ct.default.error(T),""}},g=new Range;g.setStart(b,w),g.setEnd(p,m);let v=this,C=Xr(g,A);if(!C)return;let O=this.navigator.highlighter?.createHighlight(this.navigator.iframes[0].contentWindow,{rangeInfo:C,cleanText:"",rawText:"",range:void 0},this.tts.color,!1,Ve.Custom,{id:"tts",title:"",position:"right"},void 0,{defaultClass:this.tts.color},it.ReadAloud,"R2_READALOUD_");if(O){this._ttsQueueItemHighlightsWord=O[0];let I=(O[1]?.firstChild?.getBoundingClientRect()).top-this.wrapper.scrollTop>window.innerHeight/2-65;this.navigator.view?.isScrollMode()&&this.tts.autoScroll&&!this.userScrolled&&this.scrollPartial&&I?O[1]?.firstChild?.scrollIntoView({block:"center",behavior:"smooth"}):this.navigator.view?.isPaginated()&&v.navigator.view?.snap(O[1]?.firstChild)}}}};function GA(r){let t=r;for(;t&&t.nodeType===Node.ELEMENT_NODE;){let n=t.getAttribute("xml:lang");if(n||(n=t.getAttributeNS("http://www.w3.org/XML/1998/namespace","lang")),n||(n=t.getAttribute("lang")),n)return n;t=t.parentNode}}function R8(r){let t=r;for(;t&&t.nodeType===Node.ELEMENT_NODE;){let n=t.getAttribute("dir");if(n)return n;t=t.parentNode}}function P8(r,t){if(r&&r.length){let n="";for(let i of r)i.nodeValue&&(n+=t?i.nodeValue:k8(i.nodeValue));return n}return""}function M8(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function k8(r){return M8(r).replace(/\n/g," ").replace(/\s\s+/g," ")}function bs(r,t){let n=-1,i=-1;for(let o of r)if(i++,n++,t===n)return{item:o,iArray:i,iGlobal:n,iSentence:-1}}function vs(r){return r.item.combinedText}H();var Dl=nt(Yd());var zA=nt(So());var VA=nt(Jt()),jl=class{constructor(t,n,i,o){this.currentChapterPopupResult=[];this.currentPopupHighlights=[];this.definitions=(0,zA.debounce)(async()=>{if(await this.highlighter.destroyHighlights(it.Definition),this.properties.definitions)for(let t of this.properties.definitions)await this.define(t)},200);this.publication=t,this.properties=n,this.api=o,this.highlighter=i}static async create(t){let n=new this(t.publication,t,t.highlighter,t.api);return await n.start(),n}async stop(){VA.default.log("Definitions module stop")}async start(){setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("definitions"):this.navigator.showLayer("definitions")},10)}async searchAndPaint(t,n){let i=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[this.navigator.currentResource()??0].Href:""),o=this.publication.getTOCItem(i);o===void 0&&this.publication.readingOrder&&(o=this.publication.readingOrder[this.navigator.currentResource()??0]);let a=[];if(o)for(let l of t.terms){let u=t.terms.indexOf(l);o&&await Mo(l,this.navigator.iframes[0].contentDocument,o.Href,o.Title,this.navigator.definitionsModule?.properties.fullWordSearch).then(d=>{let h;t.result===1?h=0:t.result===2&&(h=Math.floor(Math.random()*d.length-1)+1),d.forEach((y,b)=>{if(h===void 0||h===b){let w={rangeInfo:y.rangeInfo},p=this.createDefinitionHighlight(w,t);y.highlight=p,a.push(Dl.omit(p,"definition")),this.currentChapterPopupResult.push(y),this.currentPopupHighlights.push(p)}}),u===t.terms.length-1&&n(a)})}}async define(t){await this.searchAndPaint(t,async n=>{this.api?.success&&(this.api?.success(Dl.omit(t,"callbacks"),n),this.navigator.emit("definition.success",n),this.api?.visible&&n.forEach(i=>{let a=this.navigator.iframes[0].contentDocument?.querySelector(`#${i.id}`)?.querySelectorAll(`.${Tn}`),l=new IntersectionObserver((u,d)=>{u.forEach(h=>{h.intersectionRatio===1&&(this.api?.visible(Dl.omit(t,"callbacks"),Dl.omit(i,"definition")),this.navigator.emit("definition.visible",t,i))})},{threshold:1});a&&a.length>0&&l.observe(a[0])}))})}async drawDefinitions(){setTimeout(async()=>{await this.definitions()},100)}async handleResize(){await this.drawDefinitions()}createDefinitionHighlight(t,n){try{let i=this.navigator.definitionsModule?.properties.color;Qe.isHexColor(i)&&(i=Qe.hexToRgbChannels(i));let o=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,a=Fi.hash(o),l="R2_DEFINITION_"+a;this.highlighter.destroyHighlight(this.navigator.iframes[0].contentDocument,l);let u={color:i||ls,id:l,pointerInteraction:!0,selectionInfo:t,marker:Ve.Underline,type:it.Definition};tn.push(u);let d=this.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,u);return d&&(n.definition&&(d.dataset.definition=n.definition),d.dataset.order=String(n.order),u.definition=n,u.position=parseInt((d?.hasChildNodes()?d.childNodes[0]:d).style.top.replace("px",""))),u}catch(i){throw"Can't create definitions highlight: "+i}}async addDefinition(t){await this.define(t)}async clearDefinitions(){await this.highlighter.destroyHighlights(it.Definition)}};var QA=nt(Ag());H();var Lo=nt(Jt()),KA=.5,wa=class{constructor(t,n,i){this.hasEventListener=!1;this.lines=[];this.index=0;this.isActive=!1;this.isDebug=!1;this.lineFocusContainer=document.getElementById("lineFocusContainer");this.readerContainer=document.getElementById("D2Reader-Container");this.lineFocusTopBlinder=document.getElementById("lineFocusTopBlinder");this.lineFocusBottomBlinder=document.getElementById("lineFocusBottomBlinder");this.wrapperHeight=void 0;this.properties=t,this.api=i,this.highlighter=n}static async create(t){let n=new this(t,t.highlighter,t.api);return await n.start(),n}async stop(){Lo.default.log("Definitions module stop"),this.hasEventListener=!1,je(document,"keydown",this.keydown.bind(this)),je(document,"keyup",this.keyup.bind(this)),je(this.navigator.iframes[0].contentDocument,"keydown",this.keydown.bind(this)),je(this.navigator.iframes[0].contentDocument,"keyup",this.keyup.bind(this))}async start(){let t=mt(document,"#iframe-wrapper");t.style.height.length>0&&(this.wrapperHeight=t.style.height,this.lineFocusContainer&&this.lineFocusContainer.style.height.length===0&&(this.lineFocusContainer.style.height=this.wrapperHeight),this.readerContainer&&this.readerContainer.style.height.length===0&&(this.readerContainer.style.height=this.wrapperHeight),this.readerContainer&&(this.readerContainer.style.overflow="hidden"))}initialize(){return new Promise(async t=>{await document.fonts.ready,this.hasEventListener||(this.hasEventListener=!0,Ee(document,"keydown",this.keydown.bind(this)),Ee(document,"keyup",this.keyup.bind(this)),Ee(this.navigator.iframes[0].contentDocument,"keydown",this.keydown.bind(this)),Ee(this.navigator.iframes[0].contentDocument,"keyup",this.keyup.bind(this))),t(null)})}keydown(t){if(t instanceof KeyboardEvent&&this.isActive)switch(t.key){case"ArrowUp":t.stopPropagation();break;case"ArrowDown":t.stopPropagation();break}}keyup(t){if(t instanceof KeyboardEvent&&this.isActive)switch(t.key){case"ArrowUp":this.lineUp();break;case"ArrowDown":this.lineDown();break}}handleResize(){this.isActive&&this.lineFocus()}async enableLineFocus(){this.isActive=!0,await this.navigator.settings.scroll(!0),this.lineFocus()}disableLineFocus(t=!0){this.isActive=!1;let n=mt(document,"#iframe-wrapper");this.wrapperHeight&&(n.style.height=this.wrapperHeight),t||(this.index=0);let i=this.navigator.iframes[0].contentDocument;un(i,"html").style.removeProperty("--USER__maxMediaHeight"),this.wrapperHeight=void 0,this.lineFocusContainer&&(this.lineFocusContainer.style.display="none");let a=document.getElementById("container-view-timeline");a&&a.style.removeProperty("display");let l=document.getElementById("divBefore");l&&l.remove();let u=document.getElementById("divAfter");u&&u.remove(),this.highlighter.destroyHighlights(it.LineFocus)}lineFocus(){let t=mt(document,"#iframe-wrapper"),n=this.navigator.iframes[0].contentDocument,i=un(n,"html"),o=this.properties.maxHeight?tr()*this.properties.maxHeight/100:tr()/2;i.style.setProperty("--USER__maxMediaHeight",o+"px");function a(y,b){y.parentNode.insertBefore(b,y.nextSibling)}function l(y,b){y.parentNode.insertBefore(b,y)}let u=document.getElementById("container-view-timeline");u&&(u.style.display="none"),this.lineFocusContainer&&this.lineFocusContainer.style.removeProperty("display");let d=document.getElementById("divBefore");if(d)d.style.height=t.clientHeight/2+"px";else{let y=document.createElement("div");y.style.height=t.clientHeight/2+"px",y.id="divBefore",l(t,y)}let h=document.getElementById("divAfter");if(h)h.style.height=t.clientHeight/2+"px";else{let y=document.createElement("div");y.style.height=t.clientHeight/2+"px",y.id="divAfter",a(t,y)}if(this.lines=[],n){let w=function(){let A=Math.round,C=Math.random,O=255;return{blue:A(C()*O),green:A(C()*O),red:A(C()*O)}},p=function(A,C){let O=[];for(let E=0,T=0;E<A.length;E++)E>=C&&E%C==0&&T++,O[T]=O[T]||[],O[T].push(A[E]);return O},m=function(A,C){let O=Math.min(A.left,C.left),E=Math.max(A.right,C.right),T=Math.min(A.top,C.top),I=Math.max(A.bottom,C.bottom);return{bottom:I,height:I-T,left:O,right:E,top:T,width:E-O}},f=function(A){if(A.length>1){let C=m(A[0],A[1]);if(A.length>2){let O=m(C,A[2]);if(A.length>3){let E=m(O,A[3]);return A.length>4?m(E,A[4]):E}return O}return C}return A[0]},y=this.findRects(n.body);y=T0(y,!0),y=y.sort(function(A,C){return A.top-C.top});let b=[];y=y.filter(function(A){let C=A.top;return b.indexOf(C)===-1&&b.indexOf(C+1)===-1&&b.indexOf(C+2)===-1&&b.indexOf(C+3)===-1&&b.indexOf(C+4)===-1&&b.indexOf(C-1)===-1&&b.indexOf(C-2)===-1&&b.indexOf(C-3)===-1&&b.indexOf(C-4)===-1?(b.push(C),!0):!1}),this.highlighter.destroyHighlights(it.LineFocus);let g=[];this.properties.lines&&this.properties.lines>1?p(y,this.properties.lines).forEach(C=>{g.push(f(C))}):g=y;let v=Ie(n,"#"+qe.R2_ID_LINEFOCUS_CONTAINER);if(v)for(let A of g){let C=document.createElement("div");C.setAttribute("class",Tn);let O=w();if(Qe.isHexColor(O)&&(O=Qe.hexToRgbChannels(O)),this.isDebug){let le=`border-bottom: 1px solid rgba(${O.red}, ${O.green}, ${O.blue}, ${KA}) !important`;C.setAttribute("style",`mix-blend-mode: multiply; border-radius: 1px !important; background-color: rgba(${O.red}, ${O.green}, ${O.blue}, ${KA}) !important; ${le}`)}C.style.outline="none",C.tabIndex=0;let E=this.navigator.iframes[0].contentWindow.document,T=this.navigator.view.isPaginated();T?E.body.style.position="revert":E.body.style.position="relative";let I=E.body.getBoundingClientRect(),M=this.highlighter.getScrollingElement(E),j=T?-M.scrollLeft:I.left,U=T?-M.scrollTop:I.top,B=1,N=24,q,z,ne=this.navigator.iframes[0].contentWindow?.innerWidth,oe=parseInt(getComputedStyle(n.documentElement).getPropertyValue("column-count")),ae=parseInt(getComputedStyle(n.documentElement).getPropertyValue("column-width")),te=parseInt(getComputedStyle(n.body).getPropertyValue("padding-left"));if(ne){let le=ne/(oe||1);le<ae&&(le=ne),T||(le=parseInt(getComputedStyle(n.body).width.replace("px","")));let xe=this.navigator.settings.fontSize/100,fe=20*xe;xe<=1&&(fe=-60);let J=0;xe<=1&&(J=-60),q=Math.floor(A.left/le)*le+le-(N<40?40:N)+J,z=Math.floor(A.left/le)*le+(N<40?40:N)-fe;let D=parseInt(n.documentElement.style.getPropertyValue("--USER__pageMargins"));D>=2&&(z=z+te/oe,q=q-te/oe),T||(q=parseInt(getComputedStyle(n.body).width.replace("px","")),z=parseInt(getComputedStyle(n.body).width.replace("px",""))-le,D>=2&&(z=z+te/2,q=q-te/2))}C.style.setProperty("pointer-events","none"),C.style.position="absolute",C.scale=B,C.rect={height:A.height,left:A.left-j,top:A.top-U,width:A.width},C.style.width=`${C.rect.width*B}px`,C.style.height=`${C.rect.height*B}px`,C.style.left=`${C.rect.left*B}px`,C.style.top=`${C.rect.top*B}px`,this.lines.push(C),v.append(C)}setTimeout(()=>{this.currentLine()},100)}}currentLine(){let t=this.lines[this.index],n=t.style.top,o=parseInt(t.style.top.replace("px",""))+parseInt(t.style.height.replace("px",""))-parseInt(n.replace("px",""));if(this.lineFocusContainer){let l=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=l+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=l+"px")}t.scrollIntoView({block:"center",behavior:"smooth"})}lineDown(){if(this.index<this.lines.length-1){this.index+=1,this.index>this.lines.length-1&&(this.index=this.lines.length-1);let t=this.lines[this.index],n=t.style.top,o=parseInt(t.style.top.replace("px",""))+parseInt(t.style.height.replace("px",""))-parseInt(n.replace("px",""));if(this.lineFocusContainer){let l=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=l+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=l+"px")}t.scrollIntoView({block:"center",behavior:"smooth"})}}lineUp(){if(this.index>0){this.index-=1,this.index<0&&(this.index=0);let t=this.lines[this.index],n=t.style.top,o=parseInt(t.style.top.replace("px",""))+parseInt(t.style.height.replace("px",""))-parseInt(n.replace("px",""));if(this.lineFocusContainer){let l=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-o)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=l+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=l+"px")}t.scrollIntoView({block:"center",behavior:"smooth"})}}almostEqual(t,n,i){return Math.abs(t-n)<=i}findRects(t){let n=this.findTextNodes(t),i=Array.from(t.getElementsByTagName("img")),o=[];return n.forEach(a=>{o.push(...this.measureTextNodes(a))}),i.forEach(a=>{o.push(...this.measureImageNodes(a))}),o}findTextNodes(t,n=[]){let i=t.firstChild;for(;i;)i.nodeType===1&&this.findTextNodes(i,n),i.nodeType===3&&i.textContent?.trim()&&(i.textContent.trim().length>1||i.parentElement?.tagName.toLowerCase()==="h1"||i.parentElement?.tagName.toLowerCase()==="h2"||i.parentElement?.tagName.toLowerCase()==="h3"||i.parentElement?.tagName.toLowerCase()==="h4"||i.parentElement?.tagName.toLowerCase()==="h5"||i.parentElement?.tagName.toLowerCase()==="h6")&&i.parentElement&&getComputedStyle(i.parentElement).verticalAlign==="baseline"&&n.push(i),i=i.nextSibling;return n}measureTextNodes(t){try{let n=document.createRange();n.selectNodeContents(t);let i=Array.from(n.getClientRects());return n.detach(),i}catch(n){Lo.default.log("measureTextNode "+n),Lo.default.log("measureTextNode "+t),Lo.default.log(`${t.textContent}`)}}measureImageNodes(t){try{let n=document.createRange();n.selectNode(t);let i=Array.from(n.getClientRects());return n.detach(),i}catch(n){Lo.default.log("measureTextNode "+n),Lo.default.log("measureTextNode "+t),Lo.default.log(`${t.textContent}`)}}};H();var YA=nt(Jt()),Hl=class{constructor(t,n,i,o){this.history=[];this.headerMenu=o,this.publication=n,this.properties=i,this.annotator=t}static async create(t){let n=new this(t.annotator,t.publication,t,t.headerMenu);return await n.start(),n}async stop(){YA.default.log("Page Break module stop"),je(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),je(this.historyBackAnchorElement,"click",this.handleHistoryBackClick.bind(this))}async handleResize(){await this.setup()}setup(){this.history.length>0&&(this.historyForwardAnchorElement&&this.historyCurrentIndex+1<this.history.length?this.historyForwardAnchorElement.className=this.historyForwardAnchorElement.className.replace(" disabled",""):this.historyForwardAnchorElement&&(this.historyForwardAnchorElement.removeAttribute("href"),this.historyForwardAnchorElement.className+=" disabled"),this.historyBackAnchorElement&&this.historyCurrentIndex>0?this.historyBackAnchorElement.className=this.historyBackAnchorElement.className.replace(" disabled",""):this.historyBackAnchorElement&&(this.historyBackAnchorElement.removeAttribute("href"),this.historyBackAnchorElement.className+=" disabled"))}async push(t,n){let i;if(n&&this.annotator){let o=await this.annotator.getLastReadingPosition();if(o){let a=this.publication.getAbsoluteHref(o.href);o.href=a,this.historyCurrentIndex<this.history.length-1?(this.history=this.history.slice(0,this.historyCurrentIndex),this.history.push(o),this.historyCurrentIndex=this.history.length-1):o?.locations.progression&&o?.locations.progression>0&&(this.history.push(o),this.historyCurrentIndex=this.history.length-1)}this.historyCurrentIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyCurrentIndex)),i=this.history[this.history.length-1],(i&&i.href!==t.href||i===void 0)&&(this.history.push(t),this.historyCurrentIndex=this.history.length-1)}}async start(){this.headerMenu&&(this.historyForwardAnchorElement=Ie(this.headerMenu,"#history-forward")),this.headerMenu&&(this.historyBackAnchorElement=Ie(this.headerMenu,"#history-back")),this.historyCurrentIndex=this.history.length-1,Ee(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),Ee(this.historyBackAnchorElement,"click",this.handleHistoryBackClick.bind(this))}async handleHistoryForwardClick(t){await this.historyForward(),t.preventDefault(),t.stopPropagation()}async historyForward(){this.history.length>0&&this.historyCurrentIndex+1<this.history.length&&(this.historyCurrentIndex=this.historyCurrentIndex+1,await this.navigator.navigate(this.history[this.historyCurrentIndex],!1))}async handleHistoryBackClick(t){await this.historyBack(),t.preventDefault(),t.stopPropagation()}async historyBack(){this.history.length>0&&this.historyCurrentIndex>0&&(this.historyCurrentIndex=this.historyCurrentIndex-1,await this.navigator.navigate(this.history[this.historyCurrentIndex],!1))}};H();var XA=nt(Jt()),yt;(function(i){i[i.Chicago=0]="Chicago",i[i.MLA=1]="MLA",i[i.APA=2]="APA"})(yt||(yt={}));var ZA;(function(o){o.Author="Author",o.Editor="Editor",o.Translator="Translator",o.Compiler="Compiler"})(ZA||(ZA={}));var Ea=class{constructor(t,n,i,o){this.highlighter=n,this.properties=i,this.publication=t,this.api=o}static async create(t){let n=new this(t.publication,t.highlighter,t,t.api);return await n.start(),n}async stop(){XA.default.log("Citation module stop")}copyToClipboard(t){this.navigator?.contentProtectionModule&&(this.navigator.contentProtectionModule.citation=!0);let n=!0;if(window.clipboardData)window.clipboardData.setData("text/plain",t);else{let i=this.createElementForExecCommand(t);this.selectContent(i);try{window.netscape&&netscape.security&&netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"),n=document.execCommand("copy",!1)}catch(o){n=!1}document.body.removeChild(i)}n?this.api?.citationCreated("The text was copied to the clipboard!"):this.api?.citationFailed("Your browser doesn't allow clipboard access!")}createElementForExecCommand(t){let n=document.createElement("div");return n.style.position="absolute",n.style.left="-10000px",n.style.top="-10000px",n.innerHTML=t,document.body.appendChild(n),n.contentEditable=!0,n}selectContent(t){let n=document.createRange();n.selectNodeContents(t);let i=window.getSelection();i?.removeAllRanges(),i?.addRange(n)}async start(){let t=this,n={id:"citationIcon",callback:function(i){let o=function(){let M="",j="",U="";return t.properties.author?(U=U+t.properties.author,j=j+t.properties.author,M=M+t.properties.author):t.publication.Metadata.Author?.length>0&&0===0&&t.publication.Metadata.Author[0].Name&&t.publication.Metadata.Author[0].Name.length>0&&(U=U+t.publication.Metadata.Author[0].Name,j=j+t.publication.Metadata.Author[0].Name,M=M+t.publication.Metadata.Author[0].Name),U.length>0&&j.length>0&&M.length>0?[M+". ",j+". ",U+". "]:["","",""]},a=function(){let M="",j="",U="";return t.properties.publisher?(j=j+t.properties.publisher,M=M+t.properties.publisher):t.publication.Metadata.Publisher&&t.publication.Metadata.Publisher[0].Name&&(j=j+t.publication.Metadata.Publisher[0].Name,M=M+t.publication.Metadata.Publisher[0].Name),t.properties.published?(U=U+"("+t.properties.published+")",j=j+", "+t.properties.published,M=M+", "+t.properties.published):t.publication.Metadata.PublicationDate&&t.publication.Metadata.PublicationDate.getFullYear()>0&&(U=U+"("+t.publication.Metadata.PublicationDate.getFullYear()+")",j=j+", "+t.publication.Metadata.PublicationDate.getFullYear(),M=M+", "+t.publication.Metadata.PublicationDate.getFullYear()),U.length>0&&j.length>0&&M.length>0?[M+". ",j+". ",U+". "]:["","",""]},l=function(){return t.properties.title?["<em>"+t.properties.title+"</em>. ","<em>"+t.properties.title+"</em>. ","<em>"+t.properties.title+"</em>. "]:t.publication.Metadata.Title?["<em>"+t.publication.Metadata.Title+"</em>. ","<em>"+t.publication.Metadata.Title+"</em>. ","<em>"+t.publication.Metadata.Title+"</em>. "]:["","",""]},u=function(){return["","",""]},d=function(){let M="",j="",U="";return t.properties.publisher?(j=j+t.properties.publisher+", ",M=M+t.properties.publisher+", ",U=U+t.properties.publisher):t.publication.Metadata.Publisher&&t.publication.Metadata.Publisher[0].Name&&(j=j+t.publication.Metadata.Publisher[0].Name+", ",M=M+t.publication.Metadata.Publisher[0].Name+", ",U=U+t.publication.Metadata.Publisher[0].Name),U.length>0&&j.length>0&&M.length>0?[M+". ",j+". ",U+". "]:["","",""]},h=function(){return["","",""]},y=function(){return["","",""]},b=function(){return["","",""]},w=function(){return t.properties.library?["Retrieved from "+t.properties.library+". ","Retrieved from "+t.properties.library+". ","Retrieved from "+t.properties.library+". "]:["","",""]},p=function(){return t.properties.appName?[t.properties.appName+". ",t.properties.appName+". ",t.properties.appName+". "]:["","",""]},m=function(){return t.properties.appLink?[t.properties.appLink+". ",t.properties.appLink+". ",t.properties.appLink+". "]:["","",""]},f=function(){return["","",""]},g=function(M,j){return M.length>j?M.substring(0,j)+"...":M},v=o()[0]+l()[0]+h()[0]+u()[0]+b()[0]+a()[0]+y()[0]+w()[0]+p()[0]+m()[0],A=o()[2]+a()[2]+l()[2]+u()[2]+d()[2]+h()[2]+y()[2]+b()[2]+w()[2]+p()[2]+m()[2],C=o()[1]+l()[1]+h()[1]+u()[1]+b()[1]+a()[1]+f()[1]+w()[1]+p()[1]+m()[1],O="\u201C"+g(i,t.properties.characters)+"\u201C<br><br>"+v,E="\u201C"+g(i,t.properties.characters)+"\u201C<br><br>"+A,T="\u201C"+g(i,t.properties.characters)+"\u201C<br><br>"+C,I="";t.properties.styles?.includes(yt[0])&&(t.properties.styles.length>1&&(I=I+"Chicago: <br>"),I=I+O+"<br><br>"),t.properties.styles?.includes(yt[2])&&(t.properties.styles.length>1&&(I=I+"APA: <br>"),I=I+E+"<br><br>"),t.properties.styles?.includes(yt[1])&&(t.properties.styles.length>1&&(I=I+"MLA: <br>"),I=I+T+"<br><br>"),t.copyToClipboard(I)}};this.highlighter?.addSelectionMenuItem(n)}};var si=nt(Jt());var ut=class extends QA.default{constructor(t,n=void 0,i=void 0,o,a,l,u,d,h,y,b,w,p,m){super();this.iframes=[];this.sideNavExpanded=!1;this.currentChapterLink={href:""};this.currentSpreadLinks={};this.rights={autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1};this.didInitKeyboardEventHandler=!1;this.onResize=()=>{clearTimeout(this.timeout),this.timeout=setTimeout(this.handleResize.bind(this),200)};this.reload=async()=>{let t;if(this.annotator&&(t=await this.annotator.getLastReadingPosition()),t){let n=this.publication.getAbsoluteHref(t.href);si.default.log(t.href),si.default.log(n),t.href=n,await this.navigate(t)}};this.savePosition=(0,vh.debounce)(()=>{this.annotator&&this.saveCurrentReadingPosition()},200);this.checkResourcePosition=(0,vh.debounce)(()=>{this.view?.atStart()&&this.view?.atEnd()?(this.api?.resourceFitsScreen&&this.api?.resourceFitsScreen(),this.emit("resource.fits")):this.view?.atEnd()?(this.api?.resourceAtEnd&&this.api?.resourceAtEnd(),this.emit("resource.end")):this.view?.atStart()&&(this.api?.resourceAtStart&&this.api?.resourceAtStart(),this.emit("resource.start"))},200);this.highlighter=p,this.highlighter&&(this.highlighter.navigator=this);for(let f in m){let g=m[f];g&&(g.navigator=this),m[f]instanceof us&&(this.annotationModule=g),m[f]instanceof ds&&(this.bookmarkModule=g),m[f]instanceof va&&(this.ttsModule=g),m[f]instanceof va&&(this.ttsModule=g),m[f]instanceof Il&&(this.searchModule=g),m[f]instanceof jl&&(this.definitionsModule=g),m[f]instanceof Rl&&(this.timelineModule=g),m[f]instanceof ya&&(this.contentProtectionModule=g),m[f]instanceof Ea&&(this.citationModule=g),m[f]instanceof Ol&&(this.mediaOverlayModule=g),m[f]instanceof Nl&&(this.pageBreakModule=g),m[f]instanceof wa&&(this.lineFocusModule=g),m[f]instanceof Hl&&(this.historyModule=g),m[f]instanceof Tl&&(this.consumptionModule=g)}this.settings=t,this.annotator=n,this.view=t.view,this.view.attributes=h,this.view.navigator=this,this.eventHandler=new qd(this),this.touchEventHandler=new ys(this),this.keyboardEventHandler=new mh(this),this.initialLastReadingPosition=i,this.publication=o,this.api=a,this.rights=l??{autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1},this.tts=u,this.injectables=d,this.attributes=h||{margin:0},this.services=y,this.sample=b,this.requestConfig=w,this.sampleReadEventHandler=new yh(this)}static async create(t){let n=new this(t.settings,t.annotator||void 0,t.initialLastReadingPosition||void 0,t.publication,t.api,t.rights,t.tts,t.injectables,t.attributes||{margin:0},t.services,t.sample,t.requestConfig,t.highlighter,t.modules);return await n.start(t.mainElement,t.headerMenu,t.footerMenu),new Promise(i=>i(n))}stop(){si.default.log("Iframe navigator stop"),je(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),je(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),je(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),je(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),je(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),je(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),je(this.tryAgainButton,"click",this.tryAgain.bind(this)),je(this.goBackButton,"click",ut.goBack.bind(this)),je(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),je(window,"resize",this.onResize),this.iframes.forEach(t=>{je(t,"resize",this.onResize)})}async start(t,n,i){this.headerMenu=n,this.mainElement=t;try{let p=mt(t,"main#iframe-wrapper");p.style.overflow="auto";let m=Ie(t,"main#iframe-wrapper iframe"),f=Ie(t,"#second");if(m&&this.iframes.push(m),f&&this.iframes.push(f),window.matchMedia("screen and (max-width: 600px)").matches&&(this.settings.columnCount=1),this.iframes.length===0){p.style.overflow="auto";let g=document.createElement("iframe");if(g.setAttribute("SCROLLING","no"),g.setAttribute("allowtransparency","true"),this.iframes.push(g),this.publication.isFixedLayout?(this.spreads=document.createElement("div"),this.firstSpread=document.createElement("div"),this.spreads.style.display="flex",this.spreads.style.alignItems="center",this.spreads.style.justifyContent="center",this.spreads.appendChild(this.firstSpread),this.firstSpread.appendChild(this.iframes[0]),p.appendChild(this.spreads)):(g.setAttribute("height","100%"),g.setAttribute("width","100%"),p.appendChild(this.iframes[0])),this.publication.isFixedLayout)if(this.settings.columnCount!==1&&!window.matchMedia("screen and (max-width: 600px)").matches){let v=document.createElement("div");this.spreads.appendChild(v);let A=document.createElement("iframe");A.setAttribute("SCROLLING","no"),A.setAttribute("allowtransparency","true"),A.style.opacity="1",A.style.border="none",A.style.overflow="hidden",this.iframes.push(A),v.appendChild(this.iframes[1]),this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 100% 120%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc",v.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, 0% 120%)",v.style.boxShadow="0 0 8px 2px #ccc"}else this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc";else this.iframes[0].style.paddingTop=(this.attributes?.iframePaddingTop??0)+"px"}if(this.publication.isFixedLayout){let g=p.clientHeight;var o=this.iframes[0].parentElement?.parentElement;o.style.height=g+40+"px"}else this.iframes.length===2&&this.iframes.pop();if(this.loadingMessage=Ie(t,"#reader-loading"),this.loadingMessage&&(this.loadingMessage.innerHTML=gh,this.loadingMessage.style.display="none"),this.errorMessage=Ie(t,"#reader-error"),this.errorMessage&&(this.errorMessage.innerHTML=UA,this.errorMessage.style.display="none"),this.tryAgainButton=Ie(t,"button[class=try-again]"),this.goBackButton=Ie(t,"button[class=go-back]"),this.infoTop=Ie(t,"div[class='info top']"),this.infoBottom=Ie(t,"div[class='info bottom']"),this.headerMenu&&(this.bookTitle=Ie(this.headerMenu,"#book-title")),this.infoBottom&&(this.chapterTitle=Ie(this.infoBottom,"span[class=chapter-title]")),this.infoBottom&&(this.chapterPosition=Ie(this.infoBottom,"span[class=chapter-position]")),this.infoBottom&&(this.remainingPositions=Ie(this.infoBottom,"span[class=remaining-positions]")),this.headerMenu&&(this.espandMenuIcon=Ie(this.headerMenu,"#expand-menu")),this.headerMenu&&(this.links=Ie(this.headerMenu,"ul.links.top")),this.headerMenu&&(this.linksTopLeft=Ie(this.headerMenu,"#nav-mobile-left")),this.headerMenu&&(this.tocView=Ie(this.headerMenu,"#container-view-toc")),this.headerMenu&&(this.landmarksView=Ie(this.headerMenu,"#container-view-landmarks")),this.headerMenu&&(this.landmarksSection=Ie(this.headerMenu,"#sidenav-section-landmarks")),this.headerMenu&&(this.pageListView=Ie(this.headerMenu,"#container-view-pagelist")),i&&(this.linksBottom=Ie(i,"ul.links.bottom")),i&&(this.linksMiddle=Ie(i,"ul.links.middle")),this.headerMenu&&(this.nextChapterAnchorElement=Ie(this.headerMenu,"a[rel=next]")),this.headerMenu&&(this.nextChapterBottomAnchorElement=Ie(t,"#next-chapter")),i&&(this.nextPageAnchorElement=Ie(i,"a[rel=next]")),this.headerMenu&&(this.previousChapterAnchorElement=Ie(this.headerMenu,"a[rel=prev]")),this.headerMenu&&(this.previousChapterTopAnchorElement=Ie(t,"#previous-chapter")),i&&(this.previousPageAnchorElement=Ie(i,"a[rel=prev]")),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.newPosition=void 0,this.newElementId=void 0,this.isBeingStyled=!0,this.isLoading=!0,this.settings.setIframe(this.iframes[0]),this.settings.onSettingsChange(this.handleResize.bind(this)),this.settings.onColumnSettingsChange(this.handleNumberOfIframes.bind(this)),this.settings.onViewChange(this.updateBookView.bind(this)),this.initialLastReadingPosition&&this.annotator?.initLastReadingPosition(this.initialLastReadingPosition),this.headerMenu){var a=Ie(this.headerMenu,"#menu-button-search"),l=Ie(this.headerMenu,"#menu-button-tts"),u=Ie(this.headerMenu,"#menu-button-bookmark"),d=Ie(this.headerMenu,"#menu-button-play"),h=Ie(this.headerMenu,"#menu-button-pause"),y=Ie(this.headerMenu,"#menu-button-mediaoverlay");if(!this.rights.enableBookmarks){u&&u.parentElement?.style.setProperty("display","none");var b=Ie(this.headerMenu,"#sidenav-section-bookmarks");b&&b.style.setProperty("display","none")}if(!this.rights.enableAnnotations){var w=Ie(this.headerMenu,"#sidenav-section-highlights");w&&w.style.setProperty("display","none")}this.rights.enableTTS||l&&l.parentElement?.style.setProperty("display","none"),this.rights.enableSearch||a&&a.parentElement?.style.setProperty("display","none"),a&&this.view?.navigator.publication.isFixedLayout&&a.parentElement?.style.setProperty("display","none"),this.hasMediaOverlays?(d&&d.parentElement?.style.removeProperty("display"),h&&h.parentElement?.style.removeProperty("display"),y&&y.parentElement?.style.removeProperty("display")):(d&&d.parentElement?.style.setProperty("display","none"),h&&h.parentElement?.style.setProperty("display","none"),y&&y.parentElement?.style.setProperty("display","none"))}else a&&a.parentElement?.style.setProperty("display","none"),l&&l.parentElement?.style.setProperty("display","none"),u&&u.parentElement?.style.setProperty("display","none");return this.setupEvents(),await this.loadManifest()}catch(p){return si.default.error(p),this.abortOnError(p),Promise.reject(p)}}setupEvents(){for(let t of this.iframes)Ee(t,"load",this.handleIFrameLoad.bind(this));Ee(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),Ee(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),Ee(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Ee(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),Ee(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Ee(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),Ee(this.tryAgainButton,"click",this.tryAgain.bind(this)),Ee(this.goBackButton,"click",ut.goBack.bind(this)),Ee(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),Ee(window,"resize",this.onResize);for(let t of this.iframes)Ee(t,"resize",this.onResize)}updateBookView(t){this.view?.layout==="fixed"?(this.nextPageAnchorElement&&(this.nextPageAnchorElement.style.display="none"),this.previousPageAnchorElement&&(this.previousPageAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.keyboardEventHandler&&(this.keyboardEventHandler.onBackwardSwipe=this.handlePreviousChapterClick.bind(this),this.keyboardEventHandler.onForwardSwipe=this.handleNextChapterClick.bind(this)),this.touchEventHandler&&(this.touchEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.touchEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this))):(this.settings.isPaginated().then(n=>{if(n)this.view.height=tr()-40-(this.attributes?.margin??0),this.infoBottom&&this.infoBottom.style.removeProperty("display"),document.body.onscroll=()=>{},this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextPageAnchorElement&&(this.nextPageAnchorElement.style.display="unset"),this.previousPageAnchorElement&&(this.previousPageAnchorElement.style.display="unset"),this.chapterTitle&&(this.chapterTitle.style.display="inline"),this.chapterPosition&&(this.chapterPosition.style.display="inline"),this.remainingPositions&&(this.remainingPositions.style.display="inline"),this.eventHandler&&(this.eventHandler.onInternalLink=this.handleInternalLink.bind(this),this.eventHandler.onClickThrough=this.handleClickThrough.bind(this)),this.touchEventHandler&&(this.touchEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.touchEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this)),this.keyboardEventHandler&&(this.keyboardEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.keyboardEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this));else{this.infoBottom&&(this.infoBottom.style.display="none"),this.nextPageAnchorElement&&(this.nextPageAnchorElement.style.display="none"),this.previousPageAnchorElement&&(this.previousPageAnchorElement.style.display="none"),this.view?.layout==="fixed"?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")):this.view?.atStart()&&this.view?.atEnd()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):this.view?.atEnd()?(this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset")):this.view?.atStart()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"));let i=(0,vh.debounce)(()=>{this.isScrolling=!1},200),o=mt(document,"#iframe-wrapper");o.onscroll=async()=>{this.isScrolling=!0,await this.savePosition(),this.view?.atEnd(),this.view?.layout==="fixed"?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")):(this.settings.isPaginated().then(a=>{a||(this.view?.atStart()&&this.view?.atEnd()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):this.view?.atEnd()?(this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset")):this.view?.atStart()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")))}),this.checkResourcePosition()),i()},this.chapterTitle&&(this.chapterTitle.style.display="none"),this.chapterPosition&&(this.chapterPosition.style.display="none"),this.remainingPositions&&(this.remainingPositions.style.display="none"),this.eventHandler&&(this.eventHandler.onInternalLink=this.handleInternalLink.bind(this),this.eventHandler.onClickThrough=this.handleClickThrough.bind(this)),this.touchEventHandler&&(this.touchEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.touchEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this)),this.keyboardEventHandler&&(this.keyboardEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.keyboardEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this))}}),t?.skipDrawingAnnotations||setTimeout(async()=>{await this.highlighter?.prepareContainers(this.iframes[0].contentWindow),this.highlighter&&(this.rights.enableAnnotations&&this.annotationModule&&await this.annotationModule.drawHighlights(),this.rights.enableBookmarks&&this.bookmarkModule&&await this.bookmarkModule.drawBookmarks(),this.rights.enableSearch&&this.searchModule&&(await this.highlighter.destroyHighlights(it.Search),this.searchModule.drawSearch()),this.rights.enablePageBreaks&&this.pageBreakModule&&(await this.highlighter.destroyHighlights(it.PageBreak),await this.pageBreakModule.drawPageBreaks()),this.rights.enableDefinitions&&this.definitionsModule&&await this.definitionsModule.drawDefinitions())},200))}async loadManifest(){try{let t=(d,h,y=!1)=>{var b=document.createElement("ul");y&&(b=document.createElement("ol")),b.className="sidenav-toc";for(let w of h){let p=document.createElement("li"),m=document.createElement("a"),f=document.createElement("span");m.className="chapter-link",m.tabIndex=-1;let g="";w.Href?(g=this.publication.getAbsoluteHref(w.Href),m.href=g,m.innerHTML=w.Title||"",p.appendChild(m)):(f.innerHTML=w.Title||"",f.className="chapter-title",p.appendChild(f)),w.Children&&w.Children.length>0&&t(p,w.Children,!0),b.appendChild(p)}Ee(b,"click",w=>{if(w.preventDefault(),w.stopPropagation(),w.target&&w.target.tagName.toLowerCase()==="a"){let p=w.target;if(p.className.indexOf("active")!==-1)this.hideView();else{let m={progression:0};if(p.href.indexOf("#")!==-1){let g=p.href.slice(p.href.indexOf("#")+1);g!==void 0&&(m={fragment:g})}let f={href:p.href,locations:m,type:p.type,title:p.title};this.hideView(),this.navigate(f)}}}),d.appendChild(b)},n=this.publication.tableOfContents,i=this.publication.landmarks,o=this.publication.pageList;this.tocView&&(n.length?t(this.tocView,n):this.tocView.parentElement?.parentElement?.removeChild(this.tocView.parentElement)),this.pageListView&&(o?.length?t(this.pageListView,o):this.pageListView.parentElement?.parentElement?.removeChild(this.pageListView.parentElement)),this.landmarksView&&(i?.length?t(this.landmarksView,i):this.landmarksSection.parentElement?.removeChild(this.landmarksSection));let a;this.annotator&&(a=await this.annotator.getLastReadingPosition());let l=this.publication.getStartLink(),u;if(l&&l.Href&&(u=this.publication.getAbsoluteHref(l.Href)),a){let d=this.publication.getAbsoluteHref(a.href);si.default.log(a.href),si.default.log(d),a.href=d,await this.navigate(a)}else if(u){let d={href:u,locations:{progression:0},created:new Date,title:l?.Title};await this.navigate(d)}return new Promise(d=>d())}catch(t){return si.default.error(t),this.abortOnError(t),new Promise((n,i)=>i(t)).catch(()=>{})}}async handleIFrameLoad(){this.errorMessage&&(this.errorMessage.style.display="none"),this.showLoadingMessageAfterDelay();try{let t=0;this.newPosition&&(t=this.newPosition.locations.progression),await this.handleResize(),this.updateBookView({skipDrawingAnnotations:!0}),await this.settings.applyProperties();let n=this.currentChapterLink.href;if(n){let d=this.publication.getPreviousSpineItem(n);d&&d.Href&&(this.previousChapterLink={href:d.Href,title:d.Title,type:d.TypeLink})}this.previousChapterAnchorElement&&(this.previousChapterLink&&this.previousChapterLink.href?(this.previousChapterAnchorElement.href=this.publication.getAbsoluteHref(this.previousChapterLink.href),this.previousChapterAnchorElement.className=this.previousChapterAnchorElement.className.replace(" disabled","")):(this.previousChapterAnchorElement.removeAttribute("href"),this.previousChapterAnchorElement.className+=" disabled"));let i=this.publication.getNextSpineItem(n);i?this.nextChapterLink={href:i.Href,title:i.Title,type:i.TypeLink}:this.nextChapterLink=void 0,this.nextChapterAnchorElement&&(this.nextChapterLink&&this.nextChapterLink.href?(this.nextChapterAnchorElement.href=this.publication.getAbsoluteHref(this.nextChapterLink.href),this.nextChapterAnchorElement.className=this.nextChapterAnchorElement.className.replace(" disabled","")):(this.nextChapterAnchorElement.removeAttribute("href"),this.nextChapterAnchorElement.className+=" disabled")),this.historyModule&&this.historyModule.setup(),this.currentTocUrl!==void 0?this.setActiveTOCItem(this.currentTocUrl):this.setActiveTOCItem(n),this.publication.Metadata.Title&&this.bookTitle&&(this.bookTitle.innerHTML=this.publication.Metadata.Title.toString());let o=this.publication.getSpineItem(n);o!==void 0&&(this.currentChapterLink.title=o.Title,this.currentChapterLink.type=o.TypeLink);let a=this.publication.getTOCItem(n);this.currentTocUrl!==void 0&&(a=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&a!==void 0&&a.Title&&(this.currentChapterLink.title=a.Title),!this.currentChapterLink.type&&a!==void 0&&a.TypeLink&&(this.currentChapterLink.title=a.Title),this.currentChapterLink.title?this.chapterTitle&&(this.chapterTitle.innerHTML="("+this.currentChapterLink.title+")"):this.chapterTitle&&(this.chapterTitle.innerHTML="(Current Chapter)"),await this.injectInjectablesIntoIframeHead(),this.highlighter!==void 0&&await this.highlighter.initialize();let u=this.iframes[0].contentDocument?.body?.querySelector("details");if(u){let d=this;u.addEventListener("toggle",async h=>{await d.view?.setIframeHeight?.(this.iframes[0])})}if(this.eventHandler){for(let d of this.iframes)this.eventHandler.setupEvents(d.contentDocument),this.touchEventHandler.setupEvents(d.contentDocument),this.keyboardEventHandler.setupEvents(d.contentDocument);this.touchEventHandler.setupEvents(this.errorMessage),this.didInitKeyboardEventHandler||(this.keyboardEventHandler.keydown(document),this.didInitKeyboardEventHandler=!0)}if(this.view?.layout!=="fixed"&&this.view?.isScrollMode()&&(this.iframes[0].height="0",this.view?.setIframeHeight?.(this.iframes[0])),this.rights.enableContentProtection&&this.contentProtectionModule&&await this.contentProtectionModule.initialize(),this.rights.enableConsumption&&this.consumptionModule&&await this.consumptionModule.initialize(),this.rights.enableAnnotations&&this.annotationModule&&await this.annotationModule.initialize(),this.rights.enableBookmarks&&this.bookmarkModule&&await this.bookmarkModule.initialize(),this.rights.enableLineFocus&&this.lineFocusModule&&await this.lineFocusModule.initialize(),this.rights.enableTTS&&this.ttsModule){let d=this.iframes[0].contentDocument?.body;await this.ttsModule.initialize(d)}return this.rights.enableTimeline&&this.timelineModule&&await this.timelineModule.initialize(),this.rights.enableMediaOverlays&&this.mediaOverlayModule&&this.hasMediaOverlays&&await this.mediaOverlayModule.initialize(),setTimeout(async()=>{if(this.newElementId){let d=this.iframes[0].contentDocument.getElementById(this.newElementId);this.view?.goToElement?.(d),this.newElementId=void 0}else if(this.newPosition&&this.newPosition.highlight){let d=this.newPosition.highlight?.selectionInfo.rangeInfo.startContainerElementCssSelector;d&&this.view?.goToCssSelector(d)}else t&&t>=0&&this.view?.goToProgression(t);if(this.newPosition=void 0,this.rights?.enableContentProtection&&this.contentProtectionModule!==void 0&&await this.contentProtectionModule.recalculate(10),this.hideLoadingMessage(),this.showIframeContents(),this.rights.enableMediaOverlays&&this.mediaOverlayModule&&this.hasMediaOverlays){let d=this.currentLink();await this.mediaOverlayModule?.initializeResource(d)}await this.updatePositionInfo(),await this.view?.setSize(),setTimeout(()=>{this.mediaOverlayModule&&(this.mediaOverlayModule.settings.resourceReady=!0)},300)},200),new Promise(d=>d())}catch(t){return si.default.error(t),this.abortOnError(t),Promise.reject(t)}}async injectInjectablesIntoIframeHead(){let t=[],n=i=>{let o=new Promise((a,l)=>{i.onload=()=>{a(!0)},i.onerror=u=>{let d=typeof u=="string"?u:`Injectable failed to load at: ${"href"in i?i.href:i.src}`;l(new Error(d))}});t.push(o)};for(let i of this.iframes){let o=i.contentDocument?.head;o&&(i.contentDocument.getElementsByTagName("base").length===0&&o.insertBefore(ut.createBase(this.currentChapterLink.href),o.firstChild),this.injectables?.forEach(l=>{if(l.type==="style"){if(l.fontFamily){if(this.settings.initAddedFont(),!l.systemFont&&l.url){let u=ut.createCssLink(l.url);o.appendChild(u),n(u)}}else if(l.r2before&&l.url){let u=ut.createCssLink(l.url);o.insertBefore(u,o.firstChild),n(u)}else if(l.r2default&&l.url){let u=ut.createCssLink(l.url);o.insertBefore(u,o.childNodes[1]),n(u)}else if(l.r2after&&l.url){l.appearance&&this.settings.initAddedAppearance();let u=ut.createCssLink(l.url);o.appendChild(u),n(u)}else if(l.url){let u=ut.createCssLink(l.url);o.appendChild(u),n(u)}}else if(l.type==="script"&&l.url){let u=ut.createJavascriptLink(l.url,l.async??!1);o.appendChild(u),n(u)}}))}t.length!==0&&await Promise.all(t)}abortOnError(t){if(this.api?.onError){let n=t instanceof Error?t:typeof t=="string"?new Error(t):new Error("An unknown error occurred in the IFrameNavigator.");this.api.onError(n)}else this.errorMessage&&(this.errorMessage.style.display="block"),this.isLoading&&this.hideLoadingMessage()}tryAgain(){this.precessContentForIframe()}precessContentForIframe(){let t=this;var n=this.publication.getSpineIndex(this.currentChapterLink.href),i=(n??0)%2==1;this.showLoadingMessageAfterDelay();function o(d,h){let b=new DOMParser().parseFromString(d,"application/xhtml+xml");b.head&&b.getElementsByTagName("base").length===0&&b.head.insertBefore(ut.createBase(h),b.head.firstChild);let w=b.documentElement.outerHTML,p=t.iframes[0].contentDocument;p&&(p.open(),p.write(w),p.close())}function a(d,h){let b=new DOMParser().parseFromString(d,"application/xhtml+xml");b.head&&b.getElementsByTagName("base").length===0&&b.head.insertBefore(ut.createBase(h),b.head.firstChild);let w=b.documentElement.outerHTML,p=t.iframes[1].contentDocument;p&&(p.open(),p.write(w),p.close())}let l=new URL(this.currentChapterLink.href),u=window.location.protocol===l.protocol&&window.location.port===l.port&&window.location.hostname===l.hostname;if(this.api?.getContent)if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(i){if(this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.api?.getContent(this.currentChapterLink.href).then(d=>{d===void 0?u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(h=>h.text()).then(async h=>{o.call(this,h,this.currentChapterLink.href)}):o.call(this,d,this.currentChapterLink.href)}),this.iframes.length===2)if((n??0)<this.publication.readingOrder.length-1){let d=this.publication.getNextSpineItem(this.currentChapterLink.href);if(d){let h=this.publication.getAbsoluteHref(d.Href);this.currentSpreadLinks.right={href:h},this.api?.getContent(h).then(y=>{y===void 0?u?this.iframes[1].src=h:fetch(h,this.requestConfig).then(b=>b.text()).then(async b=>{a.call(this,b,h),this.currentSpreadLinks.right={href:h}}):a.call(this,y,h)})}}else this.iframes[1].src="about:blank"}else{if((n??0)>0){let d=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(d){let h=this.publication.getAbsoluteHref(d.Href);this.currentSpreadLinks.left={href:h},this.api?.getContent(h).then(y=>{y===void 0?u?this.iframes[0].src=h:fetch(h,this.requestConfig).then(b=>b.text()).then(async b=>{o.call(this,b,h)}):o.call(this,y,h)})}}else this.iframes[0].src="about:blank";this.iframes.length===2&&this.publication.isFixedLayout&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},this.api.getContent(this.currentChapterLink.href).then(d=>{d===void 0?u?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(h=>h.text()).then(async h=>{a.call(this,h,this.currentChapterLink.href)}):a.call(this,d,this.currentChapterLink.href)}))}else this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.api?.getContent(this.currentChapterLink.href).then(d=>{d===void 0?u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(h=>h.text()).then(async h=>{o.call(this,h,this.currentChapterLink.href)}):o.call(this,d,this.currentChapterLink.href)});else this.api?.getContent(this.currentChapterLink.href).then(d=>{this.currentSpreadLinks.left={href:this.currentChapterLink.href},d===void 0?u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(h=>h.text()).then(async h=>{o.call(this,h,this.currentChapterLink.href)}):o.call(this,d,this.currentChapterLink.href)});else if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(i){if(u){if(this.iframes[0].src=this.currentChapterLink.href,this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.iframes.length===2)if((n??0)<this.publication.readingOrder.length-1){let d=this.publication.getNextSpineItem(this.currentChapterLink.href);if(d){let h=this.publication.getAbsoluteHref(d.Href);this.iframes[1].src=h,this.currentSpreadLinks.right={href:h}}}else this.iframes[1].src="about:blank"}else if(fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{o.call(this,d,this.currentChapterLink.href)}),this.iframes.length===2)if((n??0)<this.publication.readingOrder.length-1){let d=this.publication.getNextSpineItem(this.currentChapterLink.href);if(d){let h=this.publication.getAbsoluteHref(d.Href);this.currentSpreadLinks.right={href:h},fetch(h,this.requestConfig).then(y=>y.text()).then(async y=>{a.call(this,y,h)})}}else this.iframes[1].src="about:blank"}else{if((n??0)>0){let d=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(d){let h=this.publication.getAbsoluteHref(d.Href);this.currentSpreadLinks.left={href:h},u?(this.iframes[0].src=h,this.iframes.length===2&&(this.iframes[1].src=this.currentChapterLink.href)):(fetch(h,this.requestConfig).then(y=>y.text()).then(async y=>{o.call(this,y,h)}),this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},fetch(this.currentChapterLink.href,this.requestConfig).then(y=>y.text()).then(async y=>{a.call(this,y,this.currentChapterLink.href)})))}}else this.iframes[0].src="about:blank";this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},u?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{a.call(this,d,this.currentChapterLink.href)}))}else this.currentSpreadLinks.left={href:this.currentChapterLink.href},u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{o.call(this,d,this.currentChapterLink.href)});else this.currentSpreadLinks.left={href:this.currentChapterLink.href},u?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(d=>d.text()).then(async d=>{o.call(this,d,this.currentChapterLink.href)});this.publication.isFixedLayout&&setTimeout(()=>{let d,h,y;if(n===0&&this.iframes?.length===2?y=this.iframes[1].contentDocument:y=this.iframes[0].contentDocument,y&&y.body&&(d=getComputedStyle(y.body).height,h=getComputedStyle(y.body).width,parseInt(d?.replace("px",""))===0||parseInt(h?.replace("px",""))===0)){let v=un(y,"head");if(v){let A=Ie(v,"meta[name=viewport]");if(A){var b=A.content,w=b.split(",").reduce((C,O)=>{var[E,T]=O.match(/[^\s;=]+/g);return C[E]=isNaN(Number(T))?T:+T,C},{});d=w.height+"px",h=w.width+"px"}}}var p=n===0&&this.iframes.length===2?this.iframes[1].parentElement?.parentElement:this.iframes[0].parentElement?.parentElement;if(p&&h){var m=(parseInt(getComputedStyle(p).width)-100)/(this.iframes.length===2?parseInt(h?.replace("px",""))*2+200:parseInt(h?.replace("px",""))),f=(parseInt(getComputedStyle(p).height)-100)/parseInt(d?.replace("px","")),g=Math.min(m,f);p.style.transform="scale("+g+")";for(let v of this.iframes)v.style.height=d,v.style.width=h,v.parentElement&&(v.parentElement.style.height=d)}},400)}static goBack(){window.history.back()}handleEditClick(t){var n=t.target;if(this.headerMenu){var i=Ie(document,".sidenav");n.className.indexOf(" active")===-1?(n.className+=" active",i.className+=" expanded",n.innerText="unfold_less",this.sideNavExpanded=!0,this.bookmarkModule?.showBookmarks(),this.annotationModule?.showHighlights()):(n.className=n.className.replace(" active",""),i.className=i.className.replace(" expanded",""),n.innerText="unfold_more",this.sideNavExpanded=!1,this.bookmarkModule?.showBookmarks(),this.annotationModule?.showHighlights())}t.preventDefault(),t.stopPropagation()}get hasMediaOverlays(){return this.publication.hasMediaOverlays}startReadAloud(){this.rights.enableTTS&&this.ttsModule.speakPlay()}startReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.startReadAloud()}stopReadAloud(){this.rights.enableTTS&&this.highlighter?.stopReadAloud()}stopReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.stopReadAloud()}pauseReadAloud(){this.rights.enableTTS&&(this.ttsModule.speakPause(),this.annotationModule!==void 0&&this.annotationModule.drawHighlights())}pauseReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.pauseReadAloud()}resumeReadAloud(){this.rights.enableTTS&&this.ttsModule.speakResume()}resumeReadAlong(){this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&this.mediaOverlayModule?.resumeReadAloud()}totalResources(){return this.publication.readingOrder.length}mostRecentNavigatedTocItem(){return this.publication.getRelativeHref(this.currentTOCRawLink)}currentResource(){let t=this.currentChapterLink.href;return this.publication.getSpineIndex(t)}currentLink(){if(this.settings.columnCount!==1&&this.currentSpreadLinks.left!==void 0&&this.currentSpreadLinks.right!==void 0){let n=this.publication.getSpineItem(this.currentSpreadLinks.left.href),i=this.publication.getSpineItem(this.currentSpreadLinks.right.href);return[n,i]}let t=this.currentChapterLink.href;return[this.publication.getSpineItem(t)]}tableOfContents(){return this.publication.tableOfContents}readingOrder(){return this.publication.readingOrder}atStart(){return this.view?.atStart()??!1}atEnd(){return this.view?.atEnd()??!1}previousPage(){this.handlePreviousPageClick(void 0)}nextPage(){this.handleNextPageClick(void 0)}previousResource(){this.handlePreviousChapterClick(void 0)}nextResource(){this.handleNextChapterClick(void 0)}goTo(t){let n=t.locations??{progression:0};if(t.href.indexOf("#")!==-1){let a=t.href.slice(t.href.indexOf("#")+1);a!==void 0&&(n=Yt(et({},n),{fragment:a}))}let i=et({},t);i.locations=n;let o=this.publication.getAbsoluteHref(t.href);si.default.log(t.href),si.default.log(o),i.href=o,this.stopReadAloud(),this.navigate(i)}currentLocator(){let t;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let n=this.publication.positionsByHref(this.publication.getRelativeHref(this.currentChapterLink.href)),i=Math.ceil((this.view?.getCurrentPosition()??0)*(n.length-1));t=n[i]}else{let n=this.publication.getTOCItem(this.currentChapterLink.href);n&&(this.currentTocUrl!==void 0&&(n=this.publication.getTOCItem(this.currentTocUrl)),n===void 0&&(n=this.publication.getTOCItemAbsolute(this.currentChapterLink.href)),n&&(t={href:n.Href,type:this.currentChapterLink.type,title:this.currentChapterLink.title,locations:{}}))}return t&&(t.locations.progression=this.view?.getCurrentPosition(),t.displayInfo={resourceScreenIndex:Math.round(this.view?.getCurrentPage()??0),resourceScreenCount:Math.round(this.view?.getPageCount()??0)}),t}positions(){return this.publication.positions?this.publication.positions:[]}goToPosition(t){if(this.publication.positions){let n=this.publication.positions.filter(i=>i.locations.position===parseInt(String(t)))[0];this.goTo(n)}}async goToPage(t){this.pageBreakModule!==void 0&&await this.pageBreakModule.goToPageNumber(t)}snapToSelector(t){let n=this.iframes[0].contentDocument;if(n){si.default.log(t);let i=n.querySelectorAll(t);i.length>0&&this.view?.snap(i[0])}}applyAttributes(t){this.attributes=t,this.view.attributes=t,this.handleResize()}handlePreviousPageClick(t){this.stopReadAloud(),this.view?.layout==="fixed"?this.handlePreviousChapterClick(t):(this.view?.atStart()?this.handlePreviousChapterClick(t):(this.view?.goToPreviousPage?.(),this.updatePositionInfo(),this.savePosition()),t&&(t.preventDefault(),t.stopPropagation()))}handleNextPageClick(t){let n=!0;if(this.sample?.isSampleRead&&this.publication.positions){let i=this.currentLocator(),o=Math.round((i.locations.totalProgression??0)*100);this.sample?.limit&&(n=o<=this.sample?.limit,this.view?.layout==="fixed"&&((!n&&this.sample?.minimum&&i.locations.position)??0<=(this.sample?.minimum??0))&&(n=!0))}(n&&this.sample?.isSampleRead&&this.publication.positions||!this.sample?.isSampleRead||!this.publication.positions)&&(this.stopReadAloud(),this.view?.layout==="fixed"?this.handleNextChapterClick(t):(this.view?.atEnd()?this.handleNextChapterClick(t):(this.view?.goToNextPage?.(),this.updatePositionInfo(),this.savePosition()),t&&(t.preventDefault(),t.stopPropagation()))),!n&&this.sample?.isSampleRead&&this.publication.positions&&t&&(t.preventDefault(),t.stopPropagation())}handleClickThrough(t){}handleInternalLink(t){let n=t.target,i={progression:0},o=n;if(o.href.indexOf("#")!==-1){let l=o.href.slice(o.href.indexOf("#")+1);l!==void 0&&(i={fragment:l})}let a={href:o.href,locations:i,type:o.type,title:o.title};t.preventDefault(),t.stopPropagation(),this.stopReadAloud(),this.navigate(a)}handleNumberOfIframes(){if(this.publication.isFixedLayout){if(this.settings.columnCount!==1&&!window.matchMedia("screen and (max-width: 600px)").matches){if(this.iframes.length===1){var t=document.createElement("iframe");t.setAttribute("SCROLLING","no"),t.setAttribute("allowtransparency","true"),t.style.opacity="1",t.style.border="none",t.style.overflow="hidden",this.iframes.push(t)}let n=document.createElement("div");this.spreads.appendChild(n),n.appendChild(this.iframes[1]),this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 100% 120%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc",n.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, 0% 120%)",n.style.boxShadow="0 0 8px 2px #ccc"}else this.iframes.length===2&&(this.iframes.pop(),this.spreads.lastChild&&this.spreads.removeChild(this.spreads.lastChild)),this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc";this.precessContentForIframe()}}async handleResize(){if(this.isScrolling)return;if(this.publication.isFixedLayout){var t=this.publication.getSpineIndex(this.currentChapterLink.href);let h=tr()-40-(this.attributes?.margin??0);var n=t===0&&this.iframes.length===2?this.iframes[1].parentElement?.parentElement:this.iframes[0].parentElement?.parentElement;if(n){n.style.height=h+40+"px";let y,b,w;t===0&&this.iframes?.length===2?w=this.iframes[1].contentDocument:w=this.iframes[0].contentDocument,w&&w.body&&(y=getComputedStyle(w.body).height,b=getComputedStyle(w.body).width);let p=un(w,"head");if(p){let m=Ie(p,"meta[name=viewport]");if(m){var i=m.content,o=i.split(",").reduce((f,g)=>{var[v,A]=g.match(/[^\s;=]+/g);return f[v]=isNaN(Number(A))?A:+A,f},{});(parseInt(o.height)!==0||parseInt(o.width)!==0)&&(y=o.height+"px",b=o.width+"px")}}var a=(parseInt(getComputedStyle(n).width)-100)/(this.iframes.length===2?parseInt(b?.replace("px",""))*2+200:parseInt(b?.replace("px",""))),l=(parseInt(getComputedStyle(n).height)-100)/parseInt(y?.replace("px","")),u=Math.min(a,l);n.style.transform="scale("+u+")";for(let m of this.iframes)m.style.height=y,m.style.width=b,m.parentElement&&(m.parentElement.style.height=y)}}let d=this.view?.getCurrentPosition();await this.settings.applyProperties(),this.infoTop&&(this.infoTop.style.height=0+"px"),this.infoTop&&(this.infoTop.style.minHeight=0+"px"),this.infoBottom&&(this.infoBottom.style.height=this.attributes?.bottomInfoHeight?this.attributes.bottomInfoHeight+"px":40+"px"),this.view?.layout!=="fixed"&&this.settings.isPaginated().then(h=>{h?(this.view.height=tr()-40-(this.attributes?.margin??0),this.infoBottom&&this.infoBottom.style.removeProperty("display")):this.infoBottom&&(this.infoBottom.style.display="none")}),setTimeout(()=>{this.view?.layout!=="fixed"&&this.view?.isScrollMode()&&this.view?.setIframeHeight?.(this.iframes[0])},100),setTimeout(async()=>{d&&this.view?.goToProgression(d),await this.updatePositionInfo(!1),this.annotationModule!==void 0&&await this.annotationModule.handleResize(),this.bookmarkModule!==void 0&&await this.bookmarkModule.handleResize(),this.searchModule!==void 0&&await this.searchModule.handleResize(),this.definitionsModule!==void 0&&await this.definitionsModule.handleResize(),this.pageBreakModule!==void 0&&await this.pageBreakModule.handleResize(),this.contentProtectionModule!==void 0&&this.contentProtectionModule.handleResize(),this.lineFocusModule!==void 0&&this.lineFocusModule.handleResize(),this.historyModule!==void 0&&this.historyModule.handleResize()},150)}updatePositionInfo(t=!0){if(this.view?.layout==="fixed")this.chapterPosition&&(this.chapterPosition.innerHTML=""),this.remainingPositions&&(this.remainingPositions.innerHTML="");else if(this.view?.isPaginated()){let n=this.currentLocator();if(n){let i=n.displayInfo.resourceScreenIndex,o=n.displayInfo.resourceScreenCount;this.chapterPosition&&(this.chapterPosition.innerHTML="Page "+i+" of "+o)}}else this.chapterPosition&&(this.chapterPosition.innerHTML=""),this.remainingPositions&&(this.remainingPositions.innerHTML="");t&&this.savePosition()}handlePreviousChapterClick(t){if(this.view?.layout==="fixed"&&this.settings.columnCount!==1){let n=this.publication.getSpineIndex(this.currentChapterLink.href)??0;n=n-2,n<0&&(n=0);let i=this.publication.readingOrder[n],o={href:this.publication.getAbsoluteHref(i.Href),locations:{progression:0},type:i.TypeLink,title:i.Title};this.stopReadAloud(),this.navigate(o,!1)}else if(this.previousChapterLink){let n={href:this.publication.getAbsoluteHref(this.previousChapterLink.href),locations:{progression:1},type:this.previousChapterLink.type,title:this.previousChapterLink.title};this.stopReadAloud(),this.navigate(n,!1)}t&&(t.preventDefault(),t.stopPropagation())}handleNextChapterClick(t){if(this.view?.layout==="fixed"&&this.settings.columnCount!==1){let n=this.publication.getSpineIndex(this.currentChapterLink.href)??0;n=n+2,n>=this.publication.readingOrder.length-1&&(n=this.publication.readingOrder.length-1);let i=this.publication.readingOrder[n],o={href:this.publication.getAbsoluteHref(i.Href),locations:{progression:0},type:i.TypeLink,title:i.Title};this.stopReadAloud(),this.navigate(o,!1)}else if(this.nextChapterLink){let n={href:this.publication.getAbsoluteHref(this.nextChapterLink.href),locations:{progression:0},type:this.nextChapterLink.type,title:this.nextChapterLink.title};this.stopReadAloud(),this.navigate(n,!1)}t&&(t.preventDefault(),t.stopPropagation())}hideView(){this.view?.layout!=="fixed"&&this.view?.isScrollMode()&&(document.body.style.overflow="auto")}setActiveTOCItem(t){if(this.tocView){let n=Array.prototype.slice.call(this.tocView.querySelectorAll("li > a"));for(let o of n)o.className=o.className.replace(" active","");let i=this.tocView.querySelector('li > a[href^="'+t+'"]');i&&(i.className+=" active")}}async navigate(t,n=!0){if(this.rights.enableConsumption&&this.consumptionModule&&n&&this.consumptionModule.startReadingSession(t),this.historyModule&&await this.historyModule.push(t,n),this.publication.getTOCItem(t.href)){var o=!1;if(t.href.indexOf("#")!==-1){let a=t.href.slice(0,t.href.indexOf("#"));a===this.currentChapterLink.href&&(o=!0),this.currentChapterLink.href=a,this.currentChapterLink.type=t.type,this.currentChapterLink.title=t.title}else t.href===this.currentChapterLink.href&&(o=!0),this.currentChapterLink.href=t.href,this.currentChapterLink.type=t.type,this.currentChapterLink.title=t.title;if(this.currentSpreadLinks.left!==void 0&&this.currentSpreadLinks.right!==void 0&&(t.href===this.currentSpreadLinks.left.href||t.href===this.currentSpreadLinks.right.href))return;if(o){if(t.href.indexOf("#")!==-1){let y=t.href.slice(t.href.indexOf("#")+1);t.locations={fragment:y}}if(this.newPosition=t,this.currentTOCRawLink=t.href,t.locations.fragment===void 0?this.currentTocUrl=void 0:(this.newElementId=t.locations.fragment,this.currentTocUrl=this.currentChapterLink.href+"#"+this.newElementId),this.newElementId){for(let y of this.iframes){let b=y.contentDocument.getElementById(this.newElementId);this.view?.goToElement?.(b)}this.newElementId=void 0}else if(t.highlight){let y=t.highlight?.selectionInfo.rangeInfo.startContainerElementCssSelector;y&&this.view?.goToCssSelector(y)}else this.view?.goToProgression(t.locations.progression??0);let a=this.currentChapterLink.href,l=this.publication.getPreviousSpineItem(a);l&&l.Href&&(this.previousChapterLink={href:l.Href,type:l.TypeLink,title:l.Title}),this.previousChapterAnchorElement&&(this.previousChapterLink?(this.previousChapterAnchorElement.href=this.publication.getAbsoluteHref(this.previousChapterLink.href),this.previousChapterAnchorElement.className=this.previousChapterAnchorElement.className.replace(" disabled","")):(this.previousChapterAnchorElement.removeAttribute("href"),this.previousChapterAnchorElement.className+=" disabled"));let u=this.publication.getNextSpineItem(a);u?this.nextChapterLink={href:u.Href,type:u.TypeLink,title:u.Title}:this.nextChapterLink=void 0,this.nextChapterAnchorElement&&(this.nextChapterLink?(this.nextChapterAnchorElement.href=this.publication.getAbsoluteHref(this.nextChapterLink.href),this.nextChapterAnchorElement.className=this.nextChapterAnchorElement.className.replace(" disabled","")):(this.nextChapterAnchorElement.removeAttribute("href"),this.nextChapterAnchorElement.className+=" disabled")),this.currentTocUrl!==void 0?this.setActiveTOCItem(this.currentTocUrl):this.setActiveTOCItem(a),this.publication.Metadata.Title&&this.bookTitle&&(this.bookTitle.innerHTML=this.publication.Metadata.Title.toString());let d=this.publication.getSpineItem(a);d!==void 0&&(this.currentChapterLink.title=d.Title,this.currentChapterLink.type=d.TypeLink);let h=this.publication.getTOCItem(a);this.currentTocUrl!==void 0&&(h=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&h!==void 0&&h.Title&&(this.currentChapterLink.title=h.Title),!this.currentChapterLink.type&&h!==void 0&&h.TypeLink&&(this.currentChapterLink.title=h.Title),this.currentChapterLink.title?this.chapterTitle&&(this.chapterTitle.innerHTML="("+this.currentChapterLink.title+")"):this.chapterTitle&&(this.chapterTitle.innerHTML="(Current Chapter)"),await this.updatePositionInfo()}else this.lineFocusModule!==void 0&&this.lineFocusModule.disableLineFocus(!1),this.searchModule!==void 0&&this.searchModule.clearSearch(),t.locations.fragment===void 0?this.currentTocUrl=void 0:(this.newElementId=t.locations.fragment,this.currentTocUrl=this.currentChapterLink.href+"#"+this.newElementId),this.hideIframeContents(),this.showLoadingMessageAfterDelay(),t.locations===void 0&&(t.locations={progression:0}),this.newPosition=t,this.currentTOCRawLink=t.href,this.precessContentForIframe(),this.rights.enableContentProtection&&this.contentProtectionModule!==void 0&&await this.contentProtectionModule.initializeResource(),this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&await this.mediaOverlayModule.initializeResource(this.currentLink()),this.rights.enableContentProtection&&this.contentProtectionModule!==void 0&&await this.contentProtectionModule.recalculate(300),this.bookmarkModule&&(await this.bookmarkModule.drawBookmarks(),await this.bookmarkModule.showBookmarks()),this.pageBreakModule&&(await this.highlighter?.destroyHighlights(it.PageBreak),await this.pageBreakModule.drawPageBreaks()),this.rights.enableSearch&&this.searchModule!==void 0&&this.highlighter!==void 0&&(await this.highlighter.destroyHighlights(it.Search),this.searchModule.drawSearch()),this.rights.enableDefinitions&&this.definitionsModule&&this.highlighter&&await this.definitionsModule.drawDefinitions(),this.rights.enableConsumption&&this.consumptionModule&&this.consumptionModule.continueReadingSession(t),this.view?.layout==="fixed"?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.api?.resourceFitsScreen&&this.api?.resourceFitsScreen(),this.emit("resource.fits")):this.settings.isPaginated().then(a=>{a||(this.view?.atStart()&&this.view?.atEnd()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):this.view?.atEnd()?(this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset")):this.view?.atStart()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")))})}else{let a=this.publication.getStartLink(),l;if(a&&a.Href&&(l=this.publication.getAbsoluteHref(a.Href),l)){let u={href:l,locations:{progression:0},created:new Date,title:a.Title};await this.navigate(u)}}}showIframeContents(){this.isBeingStyled=!1,setTimeout(()=>{this.isBeingStyled||this.iframes.forEach(t=>{t.style.opacity="1",t.style.border="none",t.style.overflow="hidden"})},150)}showLoadingMessageAfterDelay(){this.isLoading=!0,this.isLoading&&this.loadingMessage&&(this.loadingMessage.style.display="block",this.loadingMessage.classList.add("is-loading")),this.mediaOverlayModule!==void 0&&(this.mediaOverlayModule.settings.resourceReady=!1)}hideIframeContents(){this.isBeingStyled=!0,this.iframes.forEach(t=>{t.style.opacity="0",t.style.border="none",t.style.overflow="hidden"})}hideLoadingMessage(){setTimeout(()=>{this.isLoading=!1,this.loadingMessage&&(this.loadingMessage.style.display="none",this.loadingMessage.classList.remove("is-loading")),this.view?.layout!=="fixed"&&(this.view?.atStart()&&this.view?.atEnd()?(this.api?.resourceFitsScreen&&this.api?.resourceFitsScreen(),this.emit("resource.fits")):this.view?.atEnd()?(this.api?.resourceAtEnd&&this.api?.resourceAtEnd(),this.emit("resource.end")):this.view?.atStart()&&(this.api?.resourceAtStart&&this.api?.resourceAtStart(),this.emit("resource.start"))),this.api?.resourceReady&&this.api?.resourceReady(),this.emit("resource.ready")},150)}saveCurrentReadingPosition(){if(this.annotator){var t=this.publication.getTOCItem(this.currentChapterLink.href);this.currentTocUrl!==void 0&&(t=this.publication.getTOCItem(this.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.currentChapterLink.href));let n={progression:this.view?.getCurrentPosition()};if(t){if(t.Href.indexOf("#")!==-1){let o=t.Href.slice(t.Href.indexOf("#")+1);o!==void 0&&(n={progression:this.view?.getCurrentPosition(),fragment:o})}let i;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let o=this.publication.positionsByHref(this.publication.getRelativeHref(t.Href));if(o.length>0){let a=Math.ceil((n.progression??0)*(o.length-1)),l=o[a];l&&(l.locations.fragment=n.fragment,i=Yt(et({},l),{href:t.Href,created:new Date,title:this.currentChapterLink.title}))}}else i={href:t.Href,locations:n,created:new Date,type:this.currentChapterLink.type,title:this.currentChapterLink.title};i&&(this.sample?.isSampleRead&&this.publication.positions&&this.sampleReadEventHandler?.enforceSampleRead(i),this.api?.updateCurrentLocation?this.api?.updateCurrentLocation(i).then(async o=>(si.default.log("api updated current location",i),this.annotator?.saveLastReadingPosition(i))):(si.default.log("save last reading position",i),this.annotator.saveLastReadingPosition(i)),this.consumptionModule&&this.consumptionModule.continueReadingSession(i))}}}static createBase(t){let n=document.createElement("base");return n.target="_self",n.href=t,n}static createCssLink(t){let n=document.createElement("link");return n.rel="stylesheet",n.type="text/css",n.href=t,n}static createJavascriptLink(t,n){let i=document.createElement("script");return i.type="text/javascript",i.src=t,i.async=n,i}activateMarker(t,n){this.annotationModule!==void 0&&(this.annotationModule.activeAnnotationMarkerId===void 0||this.annotationModule.activeAnnotationMarkerId!==t?(this.annotationModule.activeAnnotationMarkerId=t,this.annotationModule.activeAnnotationMarkerPosition=n,this.highlighter&&(this.highlighter.activeAnnotationMarkerId=t)):this.deactivateMarker())}deactivateMarker(){this.annotationModule!==void 0&&(this.annotationModule.activeAnnotationMarkerId=void 0,this.annotationModule.activeAnnotationMarkerPosition=void 0,this.highlighter&&(this.highlighter.activeAnnotationMarkerId=void 0))}showLayer(t){let n="#",i=new Xa("layer-on","layer-off",!0,t,"layer-"+t);switch(t){case"annotations":case"highlights":n+=qe.R2_ID_HIGHLIGHTS_CONTAINER,i.name=qe.R2_ID_HIGHLIGHTS_CONTAINER;break;case"readaloud":n+=qe.R2_ID_READALOUD_CONTAINER,i.name=qe.R2_ID_READALOUD_CONTAINER;break;case"pagebreak":n+=qe.R2_ID_PAGEBREAK_CONTAINER,i.name=qe.R2_ID_PAGEBREAK_CONTAINER;break;case"search":n+=qe.R2_ID_SEARCH_CONTAINER,i.name=qe.R2_ID_SEARCH_CONTAINER;break;case"definitions":n+=qe.R2_ID_DEFINITIONS_CONTAINER,i.name=qe.R2_ID_DEFINITIONS_CONTAINER;break}this.highlighter?.layerSettings.saveProperty(i);let o=this.iframes[0].contentDocument;if(o){let a=Ie(o,n);a&&(a.style.display="block")}}hideLayer(t){let n="#",i=new Xa("layer-on","layer-off",!1,t,"layer-"+t);switch(t){case"annotations":case"highlights":n+=qe.R2_ID_HIGHLIGHTS_CONTAINER,i.name=qe.R2_ID_HIGHLIGHTS_CONTAINER;break;case"readaloud":n+=qe.R2_ID_READALOUD_CONTAINER,i.name=qe.R2_ID_READALOUD_CONTAINER;break;case"pagebreak":n+=qe.R2_ID_PAGEBREAK_CONTAINER,i.name=qe.R2_ID_PAGEBREAK_CONTAINER;break;case"search":n+=qe.R2_ID_SEARCH_CONTAINER,i.name=qe.R2_ID_SEARCH_CONTAINER;break;case"definitions":n+=qe.R2_ID_DEFINITIONS_CONTAINER,i.name=qe.R2_ID_DEFINITIONS_CONTAINER;break}this.highlighter?.layerSettings.saveProperty(i);let o=this.iframes[0].contentDocument;if(o){let a=Ie(o,n);a&&(a.style.display="none")}}};H();var Rt=class{constructor(t){this.store=t.store}getLastReadingPosition(){let t=this.store.get(Rt.LAST_READING_POSITION);return t?JSON.parse(t):null}initLastReadingPosition(t){if(typeof t=="string")this.store.set(Rt.LAST_READING_POSITION,t);else{let n=JSON.stringify(t);this.store.set(Rt.LAST_READING_POSITION,n)}}saveLastReadingPosition(t){if(typeof t=="string")this.store.set(Rt.LAST_READING_POSITION,t);else{let n=JSON.stringify(t);this.store.set(Rt.LAST_READING_POSITION,n)}}initBookmarks(t){if(typeof t=="string"){let n=JSON.parse(t);this.store.set(Rt.BOOKMARKS,JSON.stringify(n))}else this.store.set(Rt.BOOKMARKS,JSON.stringify(t));return t}saveBookmark(t){let n=this.store.get(Rt.BOOKMARKS);if(n){let i=JSON.parse(n);i.push(t),this.store.set(Rt.BOOKMARKS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(Rt.BOOKMARKS,JSON.stringify(i))}return t}locatorExists(t,n){let i;switch(n){case Si.Bookmark:i=Rt.BOOKMARKS;break}let o=this.store.get(i);return o&&JSON.parse(o).filter(u=>u.href===t.href&&u.locations.progression===t.locations.progression).length>0?t:null}deleteBookmark(t){let n=this.store.get(Rt.BOOKMARKS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.id!==t.id),this.store.set(Rt.BOOKMARKS,JSON.stringify(i))}return t}getBookmarks(t){let n=this.store.get(Rt.BOOKMARKS);if(n){let i=JSON.parse(n);if(t){let o=i.filter(a=>a.href===t);return o=o.sort((a,l)=>{if(a.locations.progression&&l.locations.progression)return a.locations.progression-l.locations.progression}),o}return i=i.sort((o,a)=>{if(o.locations.progression&&a.locations.progression)return o.locations.progression-a.locations.progression}),i}return[]}initAnnotations(t){let n;typeof t=="string"?n=JSON.parse(t):n=t;let i=[];return n.forEach(o=>{let a=`${o.highlight.selectionInfo.rangeInfo.startContainerElementCssSelector}${o.highlight.selectionInfo.rangeInfo.startContainerChildTextNodeIndex}${o.highlight.selectionInfo.rangeInfo.startOffset}${o.highlight.selectionInfo.rangeInfo.endContainerElementCssSelector}${o.highlight.selectionInfo.rangeInfo.endContainerChildTextNodeIndex}${o.highlight.selectionInfo.rangeInfo.endOffset}`,l=Fi.hash(a);o.highlight.id="R2_HIGHLIGHT_"+l;let u;o.highlight.color?u=o.highlight.color:o.color&&(u=o.color),Qe.isHexColor(u)&&(u=Qe.hexToRgbString(u)),o.highlight.color=u,o.highlight.pointerInteraction=!0,o.highlight.selectionInfo.cleanText=o.highlight.selectionInfo.rawText.trim().replace(/\n/g," ").replace(/\s\s+/g," "),i.push(o)}),this.store.set(Rt.ANNOTATIONS,JSON.stringify(i)),i}saveTemporarySelectionInfo(t){this.store.set(Rt.SELECTIONINFO,JSON.stringify(t))}getTemporarySelectionInfo(t){let n=this.store.get(Rt.SELECTIONINFO);if(n){let i=JSON.parse(n);return i.range=Jd(t,i.rangeInfo),i}return[]}deleteTemporarySelectionInfo(){this.store.remove(Rt.SELECTIONINFO)}saveAnnotation(t){let n=this.store.get(Rt.ANNOTATIONS);if(n){let i=JSON.parse(n);i.push(t),this.store.set(Rt.ANNOTATIONS,JSON.stringify(i))}else{let i=[];i.push(t),this.store.set(Rt.ANNOTATIONS,JSON.stringify(i))}return t}deleteAnnotation(t){let n=this.store.get(Rt.ANNOTATIONS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.id!==t),this.store.set(Rt.ANNOTATIONS,JSON.stringify(i))}return t}deleteSelectedAnnotation(t){let n=this.store.get(Rt.ANNOTATIONS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.highlight?.id!==t.highlight.id),this.store.set(Rt.ANNOTATIONS,JSON.stringify(i))}return t}getAnnotations(){let t=this.store.get(Rt.ANNOTATIONS);if(t){let n=JSON.parse(t);return n=n.sort((i,o)=>{if(i.locations.progression&&o.locations.progression)return i.locations.progression-o.locations.progression}),n}return[]}getAnnotationsByChapter(t){let n=this.store.get(Rt.ANNOTATIONS);if(n){let i=JSON.parse(n);return i=i.filter(o=>o.href===t),i=i.sort((o,a)=>{if(o.locations.progression&&a.locations.progression)return o.locations.progression-a.locations.progression}),i}return[]}getAnnotationPosition(t,n){let i=this.store.get(Rt.ANNOTATIONS);if(i){let a=JSON.parse(i).filter(l=>l.highlight?.id===t||l.id===t);if(a.length>0){let l=n.document.getElementById(`${a[0].highlight.id}`);if(l){let u=0;if(l.hasChildNodes)for(let d=0;d<l.childNodes.length;d++){let h=l.childNodes[d],y=parseInt(h.style.top.replace("px",""));(y<u||u===0)&&(u=y)}else u=parseInt(l.style.top.replace("px",""));return u}}}return null}getAnnotationElement(t,n){let i=this.store.get(Rt.ANNOTATIONS);if(i){let a=JSON.parse(i).filter(l=>l.highlight?.id===t);if(a.length>0){let l=n.document.getElementById(`${a[0].highlight.id}`);if(l){let u=0;if(l.hasChildNodes)for(let d=0;d<l.childNodes.length;d++){let h=l.childNodes[d],y=parseInt(h.style.top.replace("px",""));if(y<u||u===0)return u=y,h}else u=parseInt(l.style.top.replace("px",""));return l}}}return null}getAnnotation(t){let n=this.store.get(Rt.ANNOTATIONS);if(n){let o=JSON.parse(n).filter(a=>a.highlight?.id===t.id);if(o.length>0)return o[0]}return null}getAnnotationByID(t){let n=this.store.get(Rt.ANNOTATIONS);if(n){let o=JSON.parse(n).filter(a=>a.highlight?.id===t);if(o.length>0)return o[0]}return null}},Io=Rt;Io.LAST_READING_POSITION="last-reading-position",Io.BOOKMARKS="bookmarks",Io.ANNOTATIONS="annotations",Io.SELECTIONINFO="selectionInfo";H();H();var wh=class{constructor(){this.store={}}get(t){return this.store[t]||null}set(t,n){this.store[t]=n}remove(t){this.store[t]=null}};var _a=class{constructor(t){this.prefix=t.prefix,this.useLocalStorage=t.useLocalStorage;try{let n=t.prefix+"-"+String(Math.random());this.useLocalStorage?(window.localStorage.setItem(n,"test"),window.localStorage.removeItem(n)):(window.sessionStorage.setItem(n,"test"),window.sessionStorage.removeItem(n)),this.fallbackStore=null}catch(n){this.fallbackStore=new wh}}getLocalStorageKey(t){return this.prefix+"-"+t}get(t){let n;return this.fallbackStore?n=this.fallbackStore.get(t):this.useLocalStorage?n=window.localStorage.getItem(this.getLocalStorageKey(t)):n=window.sessionStorage.getItem(this.getLocalStorageKey(t)),n}set(t,n){this.fallbackStore?this.fallbackStore.set(t,n):this.useLocalStorage?window.localStorage.setItem(this.getLocalStorageKey(t),n):window.sessionStorage.setItem(this.getLocalStorageKey(t),n)}remove(t){this.fallbackStore?this.fallbackStore.remove(t):this.useLocalStorage?window.localStorage.removeItem(this.getLocalStorageKey(t)):window.sessionStorage.removeItem(this.getLocalStorageKey(t))}};H();var ex=nt(za()),tx=nt(Un());var Ul=class extends ex.Link{};Ul=Lc([(0,tx.JsonObject)()],Ul);function $l(r){let t,n,i,o;if(r instanceof Array)return r.map(function(a){return typeof a=="object"&&(a=$l(a)),a});t={};for(n in r)r.hasOwnProperty(n)&&(i=(n.charAt(0).toLowerCase()+n.slice(1)||n).toString(),o=r[n],(o instanceof Array||o!=null&&o.constructor===Object)&&(o=$l(o)),i==="href1"?t.href=o:i==="typeLink"?t.type=o:t[i]=o);return t}H();var nx=nt(Jt()),xg=class{constructor(t){this.LAYERSETTINGS="layerSetting";this.store=t,this.initialize()}static async create(t){let n=new this(t.store);return new Promise(i=>i(n))}async stop(){nx.default.log("MediaOverlay settings stop")}async initialize(){this.userProperties=await this.getLayerSettings()}async getLayerSettings(){let t=new Wr,n=await this.store.get(this.LAYERSETTINGS);if(n){let i=JSON.parse(n);t.properties=i}return t}async saveProperty(t){let n=await this.store.get(this.LAYERSETTINGS);if(n){let i=JSON.parse(n);i=i.filter(o=>o.name!==t.name),i.push(t),await this.store.set(this.LAYERSETTINGS,JSON.stringify(i))}else{let i=[];i.push(t),await this.store.set(this.LAYERSETTINGS,JSON.stringify(i))}return new Promise(i=>i(t))}async getProperty(t){let n=await this.store.get(this.LAYERSETTINGS);if(n){let i=JSON.parse(n);return i=i.filter(o=>o.name===t),i.length===0?null:i[0]}return null}};H();var dx=nt(Ag()),Sa=nt(cx());H();var ux="grab-to-pan-grab",Eh,B8,_h,N8,Sh,D8,Cg=class{constructor(t){_n(this,Eh);_n(this,_h);_n(this,Sh);this.element=t.element,this.document=t.element.ownerDocument,typeof t.ignoreTarget=="function"&&(this.ignoreTarget=t.ignoreTarget),this.onActiveChanged=t.onActiveChanged,this.activate=this.activate.bind(this),this.deactivate=this.deactivate.bind(this),this.toggle=this.toggle.bind(this),this._onMouseDown=Dr(this,Eh,B8).bind(this),this._onMouseMove=Dr(this,_h,N8).bind(this),this._endPan=Dr(this,Sh,D8).bind(this);let n=this.overlay=document.createElement("div");n.className="grab-to-pan-grabbing"}activate(){this.active||(this.active=!0,this.element.addEventListener("mousedown",this._onMouseDown,!0),this.element.classList.add(ux),this.onActiveChanged?.(!0))}deactivate(){this.active&&(this.active=!1,this.element.removeEventListener("mousedown",this._onMouseDown,!0),this._endPan(),this.element.classList.remove(ux),this.onActiveChanged?.(!1))}toggle(){this.active?this.deactivate():this.activate()}ignoreTarget(t){return t.matches("a[href], a[href] *, input, textarea, button, button *, select, option")}};Eh=new WeakSet,B8=function(t){if(t.button!==0||this.ignoreTarget(t.target))return;if(t.originalTarget)try{t.originalTarget.tagName}catch(i){return}this.scrollLeftStart=this.element.scrollLeft,this.scrollTopStart=this.element.scrollTop,this.clientXStart=t.clientX,this.clientYStart=t.clientY,this.document.addEventListener("mousemove",this._onMouseMove,!0),this.document.addEventListener("mouseup",this._endPan,!0),this.element.addEventListener("scroll",this._endPan,!0),t.preventDefault(),t.stopPropagation();let n=document.activeElement;n&&!n.contains(t.target)&&n.blur()},_h=new WeakSet,N8=function(t){if(this.element.removeEventListener("scroll",this._endPan,!0),!(t.buttons&1)){this._endPan();return}let n=t.clientX-this.clientXStart,i=t.clientY-this.clientYStart,o=this.scrollTopStart-i,a=this.scrollLeftStart-n;this.element.scrollTo?this.element.scrollTo({top:o,left:a,behavior:"instant"}):(this.element.scrollTop=o,this.element.scrollLeft=a),this.overlay.parentNode||document.body.append(this.overlay)},Sh=new WeakSet,D8=function(){this.element.removeEventListener("scroll",this._endPan,!0),this.document.removeEventListener("mousemove",this._onMouseMove,!0),this.document.removeEventListener("mouseup",this._endPan,!0),this.overlay.remove()};var Aa;(function(n){n[n.Page=0]="Page",n[n.Width=1]="Width"})(Aa||(Aa={}));var Ar=class extends dx.default{constructor(t,n,i){super();this.pdfDoc=null;this.pageNum=1;this.scaleType=0;this.pageRendering=!1;this.pageNumPending=null;this.scale=1;this.resourceIndex=0;this.onResize=()=>{clearTimeout(this.timeout),this.timeout=setTimeout(this.handleResize.bind(this),200)};this.settings=t,this.publication=n,this.api=i}static async create(t){let n=new this(t.settings,t.publication,t.api);return await n.start(t.mainElement,t.headerMenu,t.footerMenu),new Promise(i=>i(n))}async start(t,n,i){this.headerMenu=n,this.footerMenu=i,this.mainElement=t,this.resourceIndex=0,this.resource=this.publication.readingOrder[this.resourceIndex],Sa.GlobalWorkerOptions.workerSrc="//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.14.305/pdf.worker.js",this.wrapper=mt(this.mainElement,"main#iframe-wrapper"),this.pdfContainer=mt(this.mainElement,"#pdf-container"),this.handTool=new Cg({element:this.pdfContainer});let o=this,a=document.createElement("div");a.id="loadingpdf",a.innerHTML=gh,a.style.width=getComputedStyle(this.wrapper).width,a.style.height=getComputedStyle(this.wrapper).height,a.style.display="flex",a.style.zIndex="100",a.style.position="absolute",a.style.alignItems="center",a.style.justifyContent="center",a.style.background="white",a.className="loading is-loading",this.pdfContainer.appendChild(a),(0,Sa.getDocument)(this.publication.getAbsoluteHref(this.resource.Href)).promise.then(function(l){o.pdfDoc=l,o.loadPDFJS(o.pageNum)}),this.setupEvents()}async handleResize(){this.loadPDFJS(this.pageNum)}setupEvents(){Ee(window,"resize",this.onResize)}loadPDFJS(t){let n=this,i=1;this.wrapper.style.height="calc(100vh - 10px)",this.pdfContainer.style.height="calc(100vh - 10px)",this.pdfContainer.style.flexDirection="column";let o=document.getElementsByTagName("canvas");Array.from(o).forEach(function(l){l?.parentNode?.removeChild(l)});function a(l){let u=document.createElement("canvas");u.id=String(i),u.style.border="1px solid gray",u.style.margin="1px";let d=l.getViewport({scale:n.scale});if(n.scale===1){let p=n.wrapper.clientHeight/d.height,m=n.wrapper.clientWidth/d.width;n.scaleType===0?d=l.getViewport({scale:p<m?p:m}):d=l.getViewport({scale:m})}n.pdfContainer.appendChild(u);let h=u.getContext("2d");u.height=d.height,u.width=d.width;let y={canvasContext:h,viewport:d},b=document.getElementById("loadingpdf");b.style.display="flex",b.style.width=getComputedStyle(n.wrapper).width,b.style.height=getComputedStyle(n.wrapper).height,l.render(y).promise.then(function(){i<n.pdfDoc.numPages?(i++,n.pdfDoc.getPage(i).then(a)):(document.getElementById(String(t))?.scrollIntoView(),b.style.display="none",n.api?.resourceReady&&n.api?.resourceReady(),n.emit("resource.ready"))})}this.pdfDoc.getPage(i).then(a)}queueRenderPage(t){let n=this;n.pageRendering?n.pageNumPending=t:(this.pageNum=t,document.getElementById(String(t))?.scrollIntoView())}readingOrder(){return this.publication.readingOrder}tableOfContents(){return this.publication.tableOfContents}currentResource(){}totalResources(){return this.publication.readingOrder.length}currentLocator(){}positions(){return this.publication.positions?this.publication.positions:[]}nextPage(){let t=this;if(t.pageNum>=t.pdfDoc.numPages){this.nextResource();return}this.pageNum++,this.queueRenderPage(t.pageNum)}previousPage(){let t=this;if(t.pageNum<=1){this.previousResource();return}t.pageNum--,t.queueRenderPage(t.pageNum)}nextResource(){let t=this;this.resourceIndex>=this.publication.readingOrder.length-1||(t.resourceIndex++,t.resource=this.publication.readingOrder[t.resourceIndex],(0,Sa.getDocument)(this.publication.getAbsoluteHref(this.resource.Href)).promise.then(function(n){t.pdfDoc=n,t.pageNum=1,t.loadPDFJS(t.pageNum)}))}previousResource(){let t=this;this.resourceIndex!==0&&(t.resourceIndex--,t.resource=this.publication.readingOrder[t.resourceIndex],(0,Sa.getDocument)(this.publication.getAbsoluteHref(this.resource.Href)).promise.then(function(n){t.pdfDoc=n,t.pageNum=t.pdfDoc.numPages,t.loadPDFJS(t.pageNum)}))}goTo(t){let n=new URL(t.href);if(n.searchParams.has("start")){let i=n.searchParams.get("start");i&&this.queueRenderPage(parseInt(i))}else this.queueRenderPage(1)}goToPosition(t){this.queueRenderPage(t)}async goToPage(t){this.queueRenderPage(t)}fitToWidth(){this.scale=1,this.scaleType=1,this.loadPDFJS(this.pageNum)}fitToPage(){this.scale=1,this.scaleType=0,this.loadPDFJS(this.pageNum)}zoomIn(){this.scale=this.scale+.2,this.loadPDFJS(this.pageNum)}zoomOut(){this.scale=this.scale-.2,this.loadPDFJS(this.pageNum)}activateHand(){this.handTool.activate()}deactivateHand(){this.handTool.deactivate()}async scroll(t,n){t?(n==="horizontal"?this.pdfContainer.style.flexDirection="row":this.pdfContainer.style.flexDirection="column",this.pdfContainer.style.overflow="auto"):(this.pdfContainer.style.flexDirection="column",this.pdfContainer.style.overflow="hidden")}stop(){je(window,"resize",this.onResize)}};var Bo=class{constructor(t,n,i,o,a,l,u,d,h,y,b,w,p,m,f,g,v,A){this.settings=t;this.navigator=n;this.highlighter=i;this.bookmarkModule=o;this.annotationModule=a;this.ttsSettings=l;this.ttsModule=u;this.searchModule=d;this.definitionsModule=h;this.contentProtectionModule=y;this.timelineModule=b;this.mediaOverlaySettings=w;this.mediaOverlayModule=p;this.pageBreakModule=m;this.lineFocusModule=f;this.historyModule=g;this.citationModule=v;this.consumptionModule=A;this.startReadAloud=()=>{this.navigator instanceof ut&&this.navigator.startReadAloud()};this.stopReadAloud=()=>{this.navigator instanceof ut&&this.navigator.stopReadAloud()};this.pauseReadAloud=()=>{this.navigator instanceof ut&&this.navigator.pauseReadAloud()};this.resumeReadAloud=()=>{this.navigator instanceof ut&&this.navigator.resumeReadAloud()};this.startReadAlong=()=>{this.navigator instanceof ut&&this.navigator.startReadAlong()};this.stopReadAlong=()=>{this.navigator instanceof ut&&this.navigator.stopReadAlong()};this.pauseReadAlong=()=>{this.navigator instanceof ut&&this.navigator.pauseReadAlong()};this.resumeReadAlong=()=>{this.navigator instanceof ut&&this.navigator.resumeReadAlong()};this.saveBookmark=async()=>await this.bookmarkModule?.saveBookmark()??!1;this.saveBookmarkPlus=async()=>this.bookmarkModule?.saveBookmarkPlus();this.deleteBookmark=async t=>await this.bookmarkModule?.deleteBookmark(t)??!1;this.deleteAnnotation=async t=>await this.annotationModule?.deleteAnnotation(t)??!1;this.addAnnotation=async t=>await this.annotationModule?.addAnnotation(t)??!1;this.hideAnnotationLayer=()=>this.annotationModule?.hideAnnotationLayer();this.showAnnotationLayer=()=>this.annotationModule?.showAnnotationLayer();this.hideLayer=t=>this.navigator instanceof ut?this.navigator?.hideLayer(t):!1;this.showLayer=t=>this.navigator instanceof ut?this.navigator?.showLayer(t):!1;this.activateMarker=(t,n)=>this.navigator instanceof ut?this.navigator?.activateMarker(t,n):!1;this.deactivateMarker=()=>this.navigator instanceof ut?this.navigator?.deactivateMarker():!1;this.clearDefinitions=async()=>{await this.definitionsModule?.clearDefinitions()};this.addDefinition=async t=>{await this.definitionsModule?.addDefinition(t)};this.historyBack=async()=>this.historyModule?.historyBack();this.historyForward=async()=>this.historyModule?.historyForward();this.search=async(t,n)=>await this.searchModule?.search(t,n)??[];this.goToSearchIndex=async(t,n,i)=>{this.navigator instanceof ut&&this.navigator.rights.enableSearch&&await this.searchModule?.goToSearchIndex(t,n,i)};this.goToSearchID=async(t,n,i)=>{this.navigator instanceof ut&&this.navigator.rights.enableSearch&&await this.searchModule?.goToSearchID(t,n,i)};this.clearSearch=async()=>{this.navigator instanceof ut&&this.navigator.rights.enableSearch&&await this.searchModule?.clearSearch()};this.resetUserSettings=async()=>await this.settings.resetUserSettings();this.applyUserSettings=async t=>await this.settings.applyUserSettings(t);this.scroll=async(t,n)=>this.navigator instanceof Ar?this.navigator.scroll(t,n):await this.settings.scroll(t);this.increase=async t=>{this.isTTSIncrementable(t)?this.navigator instanceof ut&&this.navigator.rights.enableTTS&&await this.ttsSettings?.increase(t):this.isMOIncrementable(t)?this.navigator instanceof ut&&this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.increase(t):await this.settings.increase(t)};this.decrease=async t=>{this.isTTSIncrementable(t)?this.navigator instanceof ut&&this.navigator.rights.enableTTS&&await this.ttsSettings?.decrease(t):this.isMOIncrementable(t)?this.navigator instanceof ut&&this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.decrease(t):await this.settings.decrease(t)};this.resetTTSSettings=()=>{this.navigator instanceof ut&&this.navigator.rights.enableTTS&&this.ttsSettings?.resetTTSSettings()};this.applyTTSSettings=async t=>{this.navigator instanceof ut&&this.navigator.rights.enableTTS&&await this.ttsSettings?.applyTTSSettings(t)};this.applyPreferredVoice=async t=>{this.navigator instanceof ut&&this.navigator.rights.enableTTS&&await this.ttsSettings?.applyPreferredVoice(t)};this.resetMediaOverlaySettings=async()=>{this.navigator instanceof ut&&this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.resetMediaOverlaySettings()};this.applyMediaOverlaySettings=async t=>{this.navigator instanceof ut&&this.navigator.rights.enableMediaOverlays&&await this.mediaOverlaySettings?.applyMediaOverlaySettings(t)};this.goTo=async t=>{this.navigator.goTo(t)};this.goToPosition=async t=>this.navigator.goToPosition(t);this.goToPage=async t=>{await this.navigator.goToPage(t)};this.fitToPage=()=>{this.navigator instanceof Ar&&this.navigator.fitToPage()};this.fitToWidth=()=>{this.navigator instanceof Ar&&this.navigator.fitToWidth()};this.zoomIn=()=>{this.navigator instanceof Ar&&this.navigator.zoomIn()};this.zoomOut=()=>{this.navigator instanceof Ar&&this.navigator.zoomOut()};this.activateHand=()=>{this.navigator instanceof Ar&&this.navigator.activateHand()};this.deactivateHand=()=>{this.navigator instanceof Ar&&this.navigator.deactivateHand()};this.copyToClipboard=t=>{this.contentProtectionModule?.copyToClipboard(t)};this.nextResource=()=>{this.navigator.nextResource()};this.previousResource=()=>{this.navigator.previousResource()};this.nextPage=async()=>{this.navigator.nextPage()};this.previousPage=async()=>{this.navigator.previousPage()};this.snapToSelector=async t=>{this.navigator instanceof ut&&this.navigator.snapToSelector(t)};this.applyAttributes=t=>{this.navigator instanceof ut&&this.navigator.applyAttributes(t)};this.stop=()=>{document.body.onscroll=()=>{},this.navigator.stop(),this.settings.stop(),this.ttsSettings?.stop(),this.ttsModule?.stop(),this.bookmarkModule?.stop(),this.annotationModule?.stop(),this.searchModule?.stop(),this.definitionsModule?.stop(),this.contentProtectionModule?.stop(),this.timelineModule?.stop(),this.mediaOverlaySettings?.stop(),this.mediaOverlayModule?.stop(),this.pageBreakModule?.stop(),this.lineFocusModule?.stop(),this.citationModule?.stop(),this.consumptionModule?.stop()}}addEventListener(){this.navigator instanceof ut&&this.navigator.addListener(arguments[0],arguments[1])}static async load(t){let n=t.rights??{autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1};n.enableContentProtection&&t.protection&&await ya.setupPreloadProtection(t.protection);let i=mt(document,"#D2Reader-Container"),o=Ie(document,"#headerMenu"),a=Ie(document,"#footerMenu"),l=t.url,u;t.publication?(u=Ks(t.publication,bo),u.manifestUrl=new URL(l)):u=await bo.fromUrl(l,t.requestConfig);let d=new _a({prefix:u.manifestUrl,useLocalStorage:t.useLocalStorage??!1}),h=new _a({prefix:"r2d2bc-reader",useLocalStorage:t.useLocalStorage??!1}),y=new _a({prefix:"r2d2bc-layers",useLocalStorage:t.useLocalStorage??!1}),b=new Io({store:d});if(u.sample=t.sample,n=j8(n,u),u.Metadata.ConformsTo&&u.Metadata.ConformsTo.includes("https://readium.org/webpub-manifest/profiles/pdf")){let w=await Ao.create({store:h,initialUserSettings:t.userSettings,layout:""}),p=await Ar.create({mainElement:i,publication:u,settings:w,api:t.api});return new Bo(w,p)}else{n.autoGeneratePositions?await u.autoGeneratePositions(t.requestConfig):(t.services?.positions&&await u.fetchPositionsFromService(t.services?.positions.href,t.requestConfig),t.services?.weight&&await u.fetchWeightsFromService(t.services?.weight.href,t.requestConfig));let w=await xg.create({store:y}),p=await Ao.create({store:h,initialUserSettings:t.userSettings,headerMenu:o,api:t.api,injectables:(u.Metadata.Rendition?.Layout??"unknown")==="fixed"?t.injectablesFixed:t.injectables,layout:(u.Metadata.Rendition?.Layout??"unknown")==="fixed"?"fixed":"reflowable"}),m=await Qe.create(et({layerSettings:w},t.highlighter)),f=n.enableBookmarks?await ds.create(et({annotator:b,headerMenu:o,rights:n,publication:u,initialAnnotations:t.initialAnnotations},t.bookmarks)):void 0,g=n.enableAnnotations?await us.create(et({annotator:b,rights:n,publication:u,initialAnnotations:t.initialAnnotations,highlighter:m,headerMenu:o},t.annotations)):void 0,v=n.enableTTS,A=v?await _g.create({store:h,initialTTSSettings:t.tts,headerMenu:o}):void 0,C;v&&A&&(C=await va.create(et({tts:A,headerMenu:o,rights:n,highlighter:m},t.tts)));let O=n.enableSearch?await Il.create(et({headerMenu:o,publication:u,highlighter:m},t.search)):void 0,E=n.enableDefinitions?await jl.create(et({publication:u,highlighter:m},t.define)):void 0,T=n.enableTimeline?await Rl.create({publication:u}):void 0,I=n.enableContentProtection?await ya.create(et({},t.protection)):void 0,M=n.enableCitations?await Ea.create(et({publication:u,highlighter:m},t.citations)):void 0,j=n.enableMediaOverlays,U=j?await Q0.create(et({store:h,initialMediaOverlaySettings:t.mediaOverlays,headerMenu:o},t.mediaOverlays)):void 0,B=j?await Ol.create(et({publication:u,settings:U},t.mediaOverlays)):void 0,q=n.enablePageBreaks&&u.isReflowable?await Nl.create(et({publication:u,headerMenu:o},t.pagebreak)):void 0,z=n.enableLineFocus?await wa.create(et({publication:u,highlighter:m},t.lineFocus)):void 0,ne=n.enableHistory?await Hl.create({annotator:b,publication:u,headerMenu:o}):void 0,oe=n.enableConsumption?await Tl.create(et({publication:u},t.consumption)):void 0,ae=await ut.create({mainElement:i,headerMenu:o,footerMenu:a,publication:u,settings:p,annotator:b,initialLastReadingPosition:t.lastReadingPosition,api:t.api,rights:n,tts:t.tts,sample:t.sample,requestConfig:t.requestConfig,injectables:(u.Metadata.Rendition?.Layout??"unknown")==="fixed"?t.injectablesFixed??[]:t.injectables,attributes:t.attributes,services:t.services,highlighter:m,modules:[f,g,C,O,E,T,I,M,B,q,z,ne,oe]});return new Bo(p,ae,m,f,g,A,C,O,E,I,T,U,B,q,z,ne,M,oe)}}get hasMediaOverlays(){return this.navigator instanceof ut?this.navigator.hasMediaOverlays:!1}get tableOfContents(){return $l(this.navigator.tableOfContents())??[]}get readingOrder(){return $l(this.navigator.readingOrder())??[]}get bookmarks(){return this.bookmarkModule?.getBookmarks()??[]}get annotations(){return this.annotationModule?.getAnnotations()}get history(){return this.historyModule?.history}get historyCurrentIndex(){return this.historyModule?.historyCurrentIndex}get currentResource(){return this.navigator.currentResource()}get mostRecentNavigatedTocItem(){return this.navigator instanceof ut?this.navigator.mostRecentNavigatedTocItem():!1}get totalResources(){return this.navigator.totalResources()}get publicationLanguage(){return this.navigator.publication.Metadata.Language}get currentSettings(){return this.settings.currentSettings}isTTSIncrementable(t){return t==="pitch"||t==="rate"||t==="volume"}isMOIncrementable(t){return t==="mo_rate"||t==="mo_volume"}get currentLocator(){return this.navigator.currentLocator()}get positions(){return this.navigator.positions()}get atStart(){return this.navigator instanceof ut?this.navigator.atStart():!1}get atEnd(){return this.navigator instanceof ut?this.navigator.atEnd():!1}async applyLineFocusSettings(t){if(t.lines&&this.lineFocusModule){let n=this.lineFocusModule.properties.lines??1;this.lineFocusModule.index=this.lineFocusModule.index*n/parseInt(t.lines),this.lineFocusModule.index=Math.abs(parseInt(this.lineFocusModule.index.toFixed())),this.lineFocusModule.properties.lines=parseInt(t.lines),this.lineFocusModule.isActive&&await this.lineFocusModule.enableLineFocus()}t.debug!==void 0&&this.lineFocusModule&&(this.lineFocusModule.isDebug=t.debug,this.lineFocusModule.isActive&&await this.lineFocusModule.enableLineFocus())}lineUp(){this.lineFocusModule?.lineUp()}lineDown(){this.lineFocusModule?.lineDown()}async enableLineFocus(){await this.lineFocusModule?.enableLineFocus()}async lineFocus(t){t?await this.lineFocusModule?.enableLineFocus():this.lineFocusModule?.disableLineFocus()}disableLineFocus(){this.lineFocusModule?.disableLineFocus()}};function j8(r,t){return t.isFixedLayout&&(r.enableAnnotations=!1,r.enableSearch=!1,r.enableTTS=!1,r.enableDefinitions=!1,r.enablePageBreaks=!1,r.enableLineFocus=!1),t.sample?.isSampleRead&&(r.enableAnnotations=!1,r.enableSearch=!1,r.enableTTS=!1,r.enableDefinitions=!1,r.enableTimeline=!1,r.enableMediaOverlays=!1,r.enablePageBreaks=!1,r.enableLineFocus=!1),r}var F8=Bo,H8=Bo.load;return U8;})();
|
|
87
87
|
/*!
|
|
88
88
|
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
|
|
89
89
|
*
|