UNPKG

ng2-pdfjs-viewer

Version:

The most comprehensive Angular PDF viewer, powered by Mozilla PDF.js 6 — view, annotate, sign, fill forms, search, and read aloud from one component. 8.3M+ downloads, mobile-first, production-ready.

22 lines 351 kB
/**
 * @licstart The following is the entire license notice for the
 * JavaScript code in this page
 *
 * Copyright 2024 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @licend The above is the entire license notice for the
 * JavaScript code in this page
 */
const e="auto",t=0,i=1,n=2,s=3,a=-1,r=0,o=1,l=2,d=3,h=4,c=0,u=1,g=2,p={UNKNOWN:-1,VERTICAL:0,HORIZONTAL:1,WRAPPED:2,PAGE:3},m={UNKNOWN:-1,NONE:0,ODD:1,EVEN:2},f=0,b=1,v=/\bprint\s*\(/;function w(e,t,i=void 0){const n=function(i){a||(a=window.requestAnimationFrame(function(){a=null;const i=e.scrollLeft,n=s.lastX;i!==n&&(s.right=i>n),s.lastX=i;const r=e.scrollTop,o=s.lastY;r!==o&&(s.down=r>o),s.lastY=r,t(s)}))},s={right:!0,down:!0,lastX:e.scrollLeft,lastY:e.scrollTop,_eventHandler:n};let a=null;return e.addEventListener("scroll",n,{useCapture:!0,signal:i}),i?.addEventListener("abort",()=>window.cancelAnimationFrame(a),{once:!0}),s}function y(e){const t=new Map;for(const[i,n]of new URLSearchParams(e))t.set(i.toLowerCase(),n);return t}const C=/[\x00-\x1F]/g;function P(e,t=!1){return C.test(e)?t?e.replaceAll(C,e=>"\0"===e?"":" "):e.replaceAll("\0",""):e}function S(e,t,i=0){let n=i,s=e.length-1;if(s<0||!t(e[s]))return e.length;if(t(e[n]))return n;for(;n<s;){const i=n+s>>1;t(e[i])?s=i:n=i+1}return n}function E(e){if(Math.floor(e)===e)return[e,1];const t=1/e;if(t>8)return[1,8];if(Math.floor(t)===t)return[1,t];const i=e>1?t:e;let n=0,s=1,a=1,r=1;for(;;){const e=n+a,t=s+r;if(t>8)break;i<=e/t?(a=e,r=t):(n=e,s=t)}return i-n/s<a/r-i?i===e?[n,s]:[s,n]:i===e?[a,r]:[r,a]}function x(e,t){return e-e%t}function T({scrollEl:e,views:t,sortByVisibility:i=!1,horizontal:n=!1,rtl:s=!1}){const a=e.scrollTop,r=a+e.clientHeight,o=e.scrollLeft,l=o+e.clientWidth;const d=[],h=new Set,c=t.length;let u=S(t,n?function(e){const t=e.div,i=t.offsetLeft+t.clientLeft,n=i+t.clientWidth;return s?i<l:n>o}:function(e){const t=e.div;return t.offsetTop+t.clientTop+t.clientHeight>a});u>0&&u<c&&!n&&(u=function(e,t,i){if(e<2)return e;let n=t[e].div,s=n.offsetTop+n.clientTop;s>=i&&(n=t[e-1].div,s=n.offsetTop+n.clientTop);for(let i=e-2;i>=0&&(n=t[i].div,!(n.offsetTop+n.clientTop+n.clientHeight<=s));--i)e=i;return e}(u,t,a));let g=n?l:-1;for(let e=u;e<c;e++){const i=t[e],s=i.div,c=s.offsetLeft+s.clientLeft,u=s.offsetTop+s.clientTop,p=s.clientWidth,m=s.clientHeight,f=c+p,b=u+m;if(-1===g)b>=r&&(g=b);else if((n?c:u)>g)break;if(b<=a||u>=r||f<=o||c>=l)continue;const v=Math.max(0,a-u),w=Math.max(0,o-c),y=v+Math.max(0,b-r),C=(p-(w+Math.max(0,f-l)))/p,P=(m-y)/m*C*100|0;d.push({id:i.id,x:c,y:u,visibleArea:100===P?null:{minX:w,minY:v,maxX:Math.min(f,l)-c,maxY:Math.min(b,r)-u},view:i,percent:P,widthPercent:100*C|0}),h.add(i.id)}const p=d[0],m=d.at(-1);return i&&d.sort(function(e,t){const i=e.percent-t.percent;return Math.abs(i)>.001?-i:e.id-t.id}),{first:p,last:m,views:d,ids:h}}function L(e){let t=Math.hypot(e.deltaX,e.deltaY);const i=Math.atan2(e.deltaY,e.deltaX);return-.25*Math.PI<i&&i<.75*Math.PI&&(t=-t),t}function _(e){return Number.isInteger(e)&&e%90==0}function M(e){return Number.isInteger(e)&&Object.values(p).includes(e)&&e!==p.UNKNOWN}function I(e){return Number.isInteger(e)&&Object.values(m).includes(e)&&e!==m.UNKNOWN}function A(e){return e.width<=e.height}const B=new Promise(function(e){window.requestAnimationFrame(e)}),k=document.documentElement.style;class D{#e=null;#t=null;#i=0;#n=null;#s=!0;constructor(e){this.#e=e.classList,this.#n=e.style}get percent(){return this.#i}set percent(e){this.#i=e,isNaN(e)?this.#e.add("indeterminate"):(this.#e.remove("indeterminate"),this.#n.setProperty("--progressBar-percent",`${this.#i}%`))}setWidth(e){if(!e)return;const t=e.parentNode.offsetWidth-e.offsetWidth;t>0&&this.#n.setProperty("--progressBar-end-offset",`${t}px`)}setDisableAutoFetch(e=5e3){100===this.#i||isNaN(this.#i)||(this.#t&&clearTimeout(this.#t),this.show(),this.#t=setTimeout(()=>{this.#t=null,this.hide()},e))}hide(){this.#s&&(this.#s=!1,this.#e.add("hidden"))}show(){this.#s||(this.#s=!0,this.#e.remove("hidden"))}}function N(){let e=document,t=e.activeElement||e.querySelector(":focus");for(;t?.shadowRoot;)e=t.shadowRoot,t=e.activeElement||e.querySelector(":focus");return t}function O(e){let t=p.VERTICAL,i=m.NONE;switch(e){case"SinglePage":t=p.PAGE;break;case"OneColumn":break;case"TwoPageLeft":t=p.PAGE;case"TwoColumnLeft":i=m.ODD;break;case"TwoPageRight":t=p.PAGE;case"TwoColumnRight":i=m.EVEN}return{scrollMode:t,spreadMode:i}}function R(e,t,i=null){e.classList.toggle("toggled",t),e.setAttribute("aria-checked",t),i?.classList.toggle("hidden",!t)}function j(e,t,i=null){e.classList.toggle("selected",t),e.setAttribute("aria-selected",t),i?.classList.toggle("hidden",!t)}function V(e,t,i=null){e.classList.toggle("toggled",t),e.setAttribute("aria-expanded",t),i?.classList.toggle("hidden",!t)}const F=function(){const e=document.createElement("div");return e.style.width="round(down, calc(1.6666666666666665 * 792px), 1px)","calc(1320px)"===e.style.width?Math.fround:e=>e}();{var U=new Map;const{maxTouchPoints:e,platform:t,userAgent:i}=navigator,n=/Android/.test(i);(/\b(?:iPad|iPhone|iPod)(?=;)/.test(i)||"MacIntel"===t&&e>1||n)&&U.set("maxCanvasPixels",5242880),n&&U.set("useSystemFonts",!1)}const z=1,H=2,$=4,W=8,X=16,G=128,Y={BOOLEAN:1,NUMBER:2,OBJECT:4,STRING:8,UNDEFINED:16},K={allowedGlobalEvents:{value:null,kind:z},canvasMaxAreaInBytes:{value:-1,kind:z+$},isInAutomation:{value:!1,kind:z},localeProperties:{value:{lang:navigator.language||"en-US"},kind:z},maxCanvasDim:{value:32767,kind:z+H},nimbusDataStr:{value:"",kind:z},supportsCaretBrowsingMode:{value:!1,kind:z},supportsDocumentFonts:{value:!0,kind:z},supportsIntegratedFind:{value:!1,kind:z},supportsMouseWheelZoomCtrlKey:{value:!0,kind:z},supportsMouseWheelZoomMetaKey:{value:!0,kind:z},supportsPinchToZoom:{value:!0,kind:z},supportsPrinting:{value:!0,kind:z},toolbarDensity:{value:0,kind:z+X},altTextLearnMoreUrl:{value:"",kind:H+G},annotationEditorMode:{value:0,kind:H+G},annotationMode:{value:2,kind:H+G},capCanvasAreaFactor:{value:200,kind:H+G},commentLearnMoreUrl:{value:"",kind:H+G},cursorToolOnLoad:{value:0,kind:H+G},debuggerSrc:{value:"./debugger.mjs",kind:H},defaultZoomDelay:{value:400,kind:H+G},defaultZoomValue:{value:"",kind:H+G},disableHistory:{value:!1,kind:H},disablePageLabels:{value:!1,kind:H+G},enableAltText:{value:!1,kind:H+G},enableAltTextModelDownload:{value:!0,kind:H+G+X},enableAutoLinking:{value:!0,kind:H+G},enableComment:{value:!1,kind:H+G},enableDetailCanvas:{value:!0,kind:H},enableGuessAltText:{value:!0,kind:H+G+X},enableHighlightFloatingButton:{value:!1,kind:H+G},enableMerge:{value:!1,kind:H+G},enableNewAltTextWhenAddingImage:{value:!0,kind:H+G},enableNewBadge:{value:!1,kind:H+G},enableOptimizedPartialRendering:{value:!1,kind:H+G},enablePermissions:{value:!1,kind:H+G},enablePrintAutoRotate:{value:!0,kind:H+G},enableScripting:{value:!0,kind:H+G},enableSignatureEditor:{value:!1,kind:H+G},enableSplitMerge:{value:!1,kind:H+G},enableUpdatedAddImage:{value:!1,kind:H+G},externalLinkRel:{value:"noopener noreferrer nofollow",kind:H},externalLinkTarget:{value:0,kind:H+G},highlightEditorColors:{value:"yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F,yellow_HCM=#FFFFCC,green_HCM=#53FFBC,blue_HCM=#80EBFF,pink_HCM=#F6B8FF,red_HCM=#C50043",kind:H+G},historyUpdateUrl:{value:!1,kind:H+G},ignoreDestinationZoom:{value:!1,kind:H+G},imageResourcesPath:{value:"./images/",kind:H},enableSelectionRendering:{value:!0,kind:H+G},imagesRightClickMinSize:{value:-1,kind:H+G},maxCanvasPixels:{value:2**25,kind:H},minDurationToUpdateCanvas:{value:500,kind:H},forcePageColors:{value:!1,kind:H+G},pageColorsBackground:{value:"Canvas",kind:H+G},pageColorsForeground:{value:"CanvasText",kind:H+G},pdfBugEnabled:{value:!1,kind:H+G},postMessageAfterPrintCallback:{value:!1,kind:H+G},printResolution:{value:150,kind:H},sidebarViewOnLoad:{value:-1,kind:H+G},scrollModeOnLoad:{value:-1,kind:H+G},spreadModeOnLoad:{value:-1,kind:H+G},textLayerMode:{value:1,kind:H+G},viewerCssTheme:{value:0,kind:H+G},viewOnLoad:{value:0,kind:H+G},cMapPacked:{value:!0,kind:$},cMapUrl:{value:"../web/cmaps/",kind:$},disableAutoFetch:{value:!1,kind:$+G},disableFontFace:{value:!1,kind:$+G},disableRange:{value:!1,kind:$+G},disableStream:{value:!1,kind:$+G},docBaseUrl:{value:"",kind:$},enableHWA:{value:!0,kind:$+G},enableWebGPU:{value:!0,kind:$+G},enableXfa:{value:!0,kind:$+G},fontExtraProperties:{value:!1,kind:$},iccUrl:{value:"../web/iccs/",kind:$},isOffscreenCanvasSupported:{value:!0,kind:$},maxImageSize:{value:-1,kind:$},pdfBug:{value:!1,kind:$},standardFontDataUrl:{value:"../web/standard_fonts/",kind:$},useSystemFonts:{value:void 0,kind:$,type:Y.BOOLEAN+Y.UNDEFINED},verbosity:{value:1,kind:$},wasmUrl:{value:"../web/wasm/",kind:$},workerPort:{value:null,kind:W},workerSrc:{value:"../build/pdf.worker.mjs",kind:W}};K.defaultUrl={value:"compressed.tracemonkey-pldi-09.pdf",kind:H},K.sandboxBundleSrc={value:"../build/pdf.sandbox.mjs",kind:H},K.enableFakeMLManager={value:!0,kind:H},K.disablePreferences={value:!1,kind:H};class Z{static eventBus;static#a=new Map;static{for(const e in K)this.#a.set(e,K[e].value);for(const[e,t]of U)this.#a.set(e,t);this._hasInvokedSet=!1,this._checkDisablePreferences=()=>!!this.get("disablePreferences")||(this._hasInvokedSet&&console.warn('The Preferences may override manually set AppOptions; please use the "disablePreferences"-option to prevent that.'),!1)}static get(e){return this.#a.get(e)}static getAll(e=null,t=!1){const i=Object.create(null);for(const n in K){const s=K[n];(!e||e&s.kind)&&(i[n]=t?s.value:this.#a.get(n))}return i}static set(e,t){this.setAll({[e]:t})}static setAll(e,t=!1){let i;this._hasInvokedSet||=!0;for(const n in e){const s=K[n],a=e[n];if(!s||!(typeof a==typeof s.value||Y[(typeof a).toUpperCase()]&s.type))continue;const{kind:r}=s;(!t||r&z||r&G)&&(this.eventBus&&r&X&&(i||=new Map).set(n,a),this.#a.set(n,a))}if(i)for(const[e,t]of i)this.eventBus.dispatch(e.toLowerCase(),{source:this,value:t})}}const q="a0babde2-53ef-4493-91fe-62dfc3177bcf",Q=Object.freeze({internal:q}),{AbortException:J,AnnotationEditorLayer:ee,AnnotationEditorParamsType:te,AnnotationEditorType:ie,AnnotationEditorUIManager:ne,AnnotationLayer:se,AnnotationMode:ae,AnnotationType:re,applyOpacity:oe,build:le,ColorPicker:de,createValidAbsoluteUrl:he,CSSConstants:ce,DOMSVGFactory:ue,DrawLayer:ge,FeatureTest:pe,fetchData:me,findContrastColor:fe,getDocument:be,getFilenameFromUrl:ve,getPdfFilenameFromUrl:we,getRGB:ye,getRGBA:Ce,getUuid:Pe,GlobalWorkerOptions:Se,ImageKind:Ee,InvalidPDFException:xe,isDataScheme:Te,isPdfFile:Le,isValidExplicitDest:_e,makeArr:Me,makeMap:Ie,makeObj:Ae,MathClamp:Be,noContextMenu:ke,normalizeUnicode:De,OPS:Ne,OutputScale:Oe,PasswordResponses:Re,PDFDataRangeTransport:je,PDFDateString:Ve,PDFWorker:Fe,PermissionFlag:Ue,PixelsPerInch:ze,RenderingCancelledException:He,renderRichText:$e,ResponseException:We,setLayerDimensions:Xe,shadow:Ge,SignatureExtractor:Ye,stopEvent:Ke,SupportedImageMimeTypes:Ze,TextLayer:qe,TextLayerImages:Qe,TouchManager:Je,updateUrlHash:et,Util:tt,VerbosityLevel:it,version:nt,XfaLayer:st}=globalThis.pdfjsLib,at={NONE:0,SELF:1,BLANK:2,PARENT:3,TOP:4};class rt{externalLinkEnabled=!0;constructor({eventBus:e,externalLinkTarget:t=null,externalLinkRel:i=null,ignoreDestinationZoom:n=!1}={}){this.eventBus=e,this.externalLinkTarget=t,this.externalLinkRel=i,this._ignoreDestinationZoom=n,this.baseUrl=null,this.pdfDocument=null,this.pdfViewer=null,this.pdfHistory=null}setDocument(e,t=null){this.baseUrl=t,this.pdfDocument=e}setViewer(e){this.pdfViewer=e}setHistory(e){this.pdfHistory=e}get pagesCount(){return this.pdfDocument?.pagesMapper.pagesNumber||0}get page(){return this.pdfDocument?this.pdfViewer.currentPageNumber:1}set page(e){this.pdfDocument&&(this.pdfViewer.currentPageNumber=e)}get rotation(){return this.pdfDocument?this.pdfViewer.pagesRotation:0}set rotation(e){this.pdfDocument&&(this.pdfViewer.pagesRotation=e)}get isInPresentationMode(){return!!this.pdfDocument&&this.pdfViewer.isInPresentationMode}async goToDestination(e){if(!this.pdfDocument)return;let t,i,n;if("string"==typeof e?(t=e,i=await this.pdfDocument.getDestination(e)):(t=null,i=await e),!Array.isArray(i))return void console.error(`goToDestination: "${i}" is not a valid destination array, for dest="${e}".`);const[s]=i;if(s&&"object"==typeof s){if(n=this.pdfDocument.cachedPageNumber(s),!n)try{n=await this.pdfDocument.getPageIndex(s)+1}catch{return void console.error(`goToDestination: "${s}" is not a valid page reference, for dest="${e}".`)}}else Number.isInteger(s)&&(n=s+1);if(!n||n<1||n>this.pagesCount)return void console.error(`goToDestination: "${n}" is not a valid page number, for dest="${e}".`);this.pdfHistory&&(this.pdfHistory.pushCurrentPosition(),this.pdfHistory.push({namedDest:t,explicitDest:i,pageNumber:n})),this.pdfViewer.scrollPageIntoView({pageNumber:n,destArray:i,ignoreDestinationZoom:this._ignoreDestinationZoom});const a=new AbortController;this.eventBus.on("textlayerrendered",e=>{e.pageNumber===n&&(e.source.textLayer.div.focus(),a.abort())},{signal:a.signal,...Q})}goToPage(e){if(!this.pdfDocument)return;const t="string"==typeof e&&this.pdfViewer.pageLabelToPageNumber(e)||0|e;Number.isInteger(t)&&t>0&&t<=this.pagesCount?(this.pdfHistory&&(this.pdfHistory.pushCurrentPosition(),this.pdfHistory.pushPage(t)),this.pdfViewer.scrollPageIntoView({pageNumber:t})):console.error(`PDFLinkService.goToPage: "${e}" is not a valid page.`)}goToXY(e,t,i,n={}){this.pdfViewer.scrollPageIntoView({pageNumber:e,destArray:[null,{name:"XYZ"},t,i],ignoreDestinationZoom:!0,...n})}addLinkAttributes(e,t,i=!1){if(!t||"string"!=typeof t)throw new Error('A valid "url" parameter must provided.');const n=i?at.BLANK:this.externalLinkTarget,s=this.externalLinkRel;let a=t;const r=URL.parse(t);(r?.username||r?.password)&&(r.username=r.password="",a=r.href),this.externalLinkEnabled?(e.href=t,e.title=a):(e.href="",e.title=`Disabled: ${a}`,e.onclick=()=>!1);let o="";switch(n){case at.NONE:break;case at.SELF:o="_self";break;case at.BLANK:o="_blank";break;case at.PARENT:o="_parent";break;case at.TOP:o="_top"}e.target=o,e.rel="string"==typeof s?s:"noopener noreferrer nofollow"}getDestinationHash(e){if("string"==typeof e){if(e.length>0)return this.getAnchorUrl("#"+escape(e))}else if(Array.isArray(e)){const t=JSON.stringify(e);if(t.length>0)return this.getAnchorUrl("#"+escape(t))}return this.getAnchorUrl("")}getAnchorUrl(e){return this.baseUrl?this.baseUrl+e:e}setHash(e){if(!this.pdfDocument)return;let t,i;if(e.includes("=")){const n=y(e);if(n.has("search")){const e=n.get("search").replaceAll('"',""),t="true"===n.get("phrase");this.eventBus.dispatch("findfromurlhash",{source:this,query:t?e:e.match(/\S+/g)})}if(n.has("page")&&(t=0|n.get("page")||1),n.has("zoom")){const e=n.get("zoom").split(","),t=e[0],s=parseFloat(t);t.includes("Fit")?"Fit"===t||"FitB"===t?i=[null,{name:t}]:"FitH"===t||"FitBH"===t||"FitV"===t||"FitBV"===t?i=[null,{name:t},e.length>1?0|e[1]:null]:"FitR"===t?5!==e.length?console.error('PDFLinkService.setHash: Not enough parameters for "FitR".'):i=[null,{name:t},0|e[1],0|e[2],0|e[3],0|e[4]]:console.error(`PDFLinkService.setHash: "${t}" is not a valid zoom value.`):i=[null,{name:"XYZ"},e.length>1?0|e[1]:null,e.length>2?0|e[2]:null,s?s/100:t]}return i?this.pdfViewer.scrollPageIntoView({pageNumber:t||this.page,destArray:i,allowNegativeOffset:!0}):t&&(this.page=t),n.has("pagemode")&&this.eventBus.dispatch("pagemode",{source:this,mode:n.get("pagemode")}),void(n.has("nameddest")&&this.goToDestination(n.get("nameddest")))}i=unescape(e);try{i=JSON.parse(i),Array.isArray(i)||(i=i.toString())}catch{}"string"==typeof i||_e(i)?this.goToDestination(i):console.error(`PDFLinkService.setHash: "${unescape(e)}" is not a valid destination.`)}executeNamedAction(e){if(this.pdfDocument){switch(e){case"GoBack":this.pdfHistory?.back();break;case"GoForward":this.pdfHistory?.forward();break;case"NextPage":this.pdfViewer.nextPage();break;case"PrevPage":this.pdfViewer.previousPage();break;case"LastPage":this.page=this.pagesCount;break;case"FirstPage":this.page=1}this.eventBus.dispatch("namedaction",{source:this,action:e})}}async executeSetOCGState(e){if(!this.pdfDocument)return;const t=this.pdfDocument,i=await this.pdfViewer.optionalContentConfigPromise;t===this.pdfDocument&&(i.setOCGState(e),this.pdfViewer.optionalContentConfigPromise=Promise.resolve(i))}}class ot extends rt{setDocument(e,t=null){}}const lt="event",dt="timeout";async function ht({target:e,name:t,delay:i=0}){if("object"!=typeof e||!t||"string"!=typeof t||!(Number.isInteger(i)&&i>=0))throw new Error("waitOnEventOrTimeout - invalid parameters.");const{promise:n,resolve:s}=Promise.withResolvers(),a=new AbortController;function r(e){a.abort(),clearTimeout(d),s(e)}const o=e instanceof ct?"on":"addEventListener",l=e instanceof ct?{signal:a.signal,...Q}:{signal:a.signal};e[o](t,r.bind(null,lt),l);const d=setTimeout(r.bind(null,dt),i);return n}class ct{#r=Object.create(null);constructor(){Object.seal(this)}on(e,t,i=null){let n=null;if(i?.signal instanceof AbortSignal){const{signal:s}=i;if(s.aborted)return void console.error("Cannot use an `aborted` signal.");const a=()=>this.off(e,t);n=()=>s.removeEventListener("abort",a),s.addEventListener("abort",a)}(this.#r[e]??=[]).push({listener:t,internal:i?.internal===q,once:!0===i?.once,rmAbort:n})}off(e,t,i=null){const n=this.#r[e];if(n)for(let e=0,i=n.length;e<i;e++){const i=n[e];if(i.listener===t)return i.rmAbort?.(),void n.splice(e,1)}}dispatch(e,t){const i=this.#r[e];if(!i?.length)return;let n;for(const{listener:s,internal:a,once:r}of i.slice(0))r&&this.off(e,s),a?s(t):(n??=[]).push(s);if(n)for(const e of n)e(t)}}class ut{updateFindControlState(e){}updateFindMatchesCount(e){}initPassiveLoading(){}reportTelemetry(e){}reportText(e){}async createL10n(){throw new Error("Not implemented: createL10n")}createScripting(){throw new Error("Not implemented: createScripting")}createSignatureStorage(){throw new Error("Not implemented: createSignatureStorage")}updateEditorStates(e){throw new Error("Not implemented: updateEditorStates")}dispatchGlobalEvent(e){}}class gt{#o=Object.freeze(Z.getAll(G,!0));#l=null;constructor(){this.#l=this._readFromStorage(this.#o).then(({browserPrefs:e,prefs:t})=>{Z._checkDisablePreferences()||Z.setAll({...e,...t},!0)})}async _writeToStorage(e){throw new Error("Not implemented: _writeToStorage")}async _readFromStorage(e){throw new Error("Not implemented: _readFromStorage")}async reset(){await this.#l,Z.setAll(this.#o,!0),await this._writeToStorage(this.#o)}async set(e,t){await this.#l,Z.setAll({[e]:t},!0),await this._writeToStorage(Z.getAll(G))}async get(e){return await this.#l,Z.get(e)}get defaults(){return this.#o}get initializedPromise(){return this.#l}}class pt{constructor(e){this.value=e}valueOf(){return this.value}}class mt extends pt{constructor(e="???"){super(e)}toString(e){return`{${this.value}}`}}class ft extends pt{constructor(e,t={}){super(e),this.opts=t}toString(e){if(e)try{return e.memoizeIntlObject(Intl.NumberFormat,this.opts).format(this.value)}catch(t){e.reportError(t)}return this.value.toString(10)}}class bt extends pt{static supportsValue(e){if("number"==typeof e)return!0;if(e instanceof Date)return!0;if(e instanceof pt)return bt.supportsValue(e.valueOf());if("Temporal"in globalThis){const t=globalThis.Temporal;if(e instanceof t.Instant||e instanceof t.PlainDateTime||e instanceof t.PlainDate||e instanceof t.PlainMonthDay||e instanceof t.PlainTime||e instanceof t.PlainYearMonth)return!0}return!1}constructor(e,t={}){e instanceof bt?(t={...e.opts,...t},e=e.value):e instanceof pt&&(e=e.valueOf()),"object"==typeof e&&"calendarId"in e&&void 0===t.calendar&&(t={...t,calendar:e.calendarId}),super(e),this.opts=t}[Symbol.toPrimitive](e){return"string"===e?this.toString():this.toNumber()}toNumber(){const e=this.value;if("number"==typeof e)return e;if(e instanceof Date)return e.getTime();if("epochMilliseconds"in e)return e.epochMilliseconds;if("toZonedDateTime"in e)return e.toZonedDateTime("UTC").epochMilliseconds;throw new TypeError("Unwrapping a non-number value as a number")}toString(e){if(e)try{return e.memoizeIntlObject(Intl.DateTimeFormat,this.opts).format(this.value)}catch(t){e.reportError(t)}return"number"==typeof this.value||this.value instanceof Date?new Date(this.value).toISOString():this.value.toString()}}function vt(e,t,i){if(i===t)return!0;if(i instanceof ft&&t instanceof ft&&i.value===t.value)return!0;if(t instanceof ft&&"string"==typeof i){if(i===e.memoizeIntlObject(Intl.PluralRules,t.opts).select(t.value))return!0}return!1}function wt(e,t,i){return t[i]?St(e,t[i].value):(e.reportError(new RangeError("No default")),new mt)}function yt(e,t){const i=[],n=Object.create(null);for(const s of t)"narg"===s.type?n[s.name]=Ct(e,s.value):i.push(Ct(e,s));return{positional:i,named:n}}function Ct(e,t){switch(t.type){case"str":return t.value;case"num":return new ft(t.value,{minimumFractionDigits:t.precision});case"var":return function(e,{name:t}){let i;if(e.params){if(!Object.prototype.hasOwnProperty.call(e.params,t))return new mt(`$${t}`);i=e.params[t]}else{if(!e.args||!Object.prototype.hasOwnProperty.call(e.args,t))return e.reportError(new ReferenceError(`Unknown variable: $${t}`)),new mt(`$${t}`);i=e.args[t]}if(i instanceof pt)return i;switch(typeof i){case"string":return i;case"number":return new ft(i);case"object":if(bt.supportsValue(i))return new bt(i);default:return e.reportError(new TypeError(`Variable type not supported: $${t}, ${typeof i}`)),new mt(`$${t}`)}}(e,t);case"mesg":return function(e,{name:t,attr:i}){const n=e.bundle._messages.get(t);if(!n)return e.reportError(new ReferenceError(`Unknown message: ${t}`)),new mt(t);if(i){const s=n.attributes[i];return s?St(e,s):(e.reportError(new ReferenceError(`Unknown attribute: ${i}`)),new mt(`${t}.${i}`))}if(n.value)return St(e,n.value);return e.reportError(new ReferenceError(`No value: ${t}`)),new mt(t)}(e,t);case"term":return function(e,{name:t,attr:i,args:n}){const s=`-${t}`,a=e.bundle._terms.get(s);if(!a)return e.reportError(new ReferenceError(`Unknown term: ${s}`)),new mt(s);if(i){const t=a.attributes[i];if(t){e.params=yt(e,n).named;const i=St(e,t);return e.params=null,i}return e.reportError(new ReferenceError(`Unknown attribute: ${i}`)),new mt(`${s}.${i}`)}e.params=yt(e,n).named;const r=St(e,a.value);return e.params=null,r}(e,t);case"func":return function(e,{name:t,args:i}){let n=e.bundle._functions[t];if(!n)return e.reportError(new ReferenceError(`Unknown function: ${t}()`)),new mt(`${t}()`);if("function"!=typeof n)return e.reportError(new TypeError(`Function ${t}() is not callable`)),new mt(`${t}()`);try{let t=yt(e,i);return n(t.positional,t.named)}catch(i){return e.reportError(i),new mt(`${t}()`)}}(e,t);case"select":return function(e,{selector:t,variants:i,star:n}){let s=Ct(e,t);if(s instanceof mt)return wt(e,i,n);for(const t of i){if(vt(e,s,Ct(e,t.key)))return St(e,t.value)}return wt(e,i,n)}(e,t);default:return new mt}}function Pt(e,t){if(e.dirty.has(t))return e.reportError(new RangeError("Cyclic reference")),new mt;e.dirty.add(t);const i=[],n=e.bundle._useIsolating&&t.length>1;for(const s of t)if("string"!=typeof s){if(e.placeables++,e.placeables>100)throw e.dirty.delete(t),new RangeError(`Too many placeables expanded: ${e.placeables}, max allowed is 100`);n&&i.push("⁨"),i.push(Ct(e,s).toString(e)),n&&i.push("⁩")}else i.push(e.bundle._transform(s));return e.dirty.delete(t),i.join("")}function St(e,t){return"string"==typeof t?e.bundle._transform(t):Pt(e,t)}class Et{constructor(e,t,i){this.dirty=new WeakSet,this.params=null,this.placeables=0,this.bundle=e,this.errors=t,this.args=i}reportError(e){if(!(this.errors&&e instanceof Error))throw e;this.errors.push(e)}memoizeIntlObject(e,t){let i=this.bundle._intls.get(e);i||(i={},this.bundle._intls.set(e,i));let n=JSON.stringify(t);return i[n]||(i[n]=new e(this.bundle.locales,t)),i[n]}}function xt(e,t){const i=Object.create(null);for(const[n,s]of Object.entries(e))t.includes(n)&&(i[n]=s.valueOf());return i}const Tt=["unitDisplay","currencyDisplay","useGrouping","minimumIntegerDigits","minimumFractionDigits","maximumFractionDigits","minimumSignificantDigits","maximumSignificantDigits"];function Lt(e,t){let i=e[0];if(i instanceof mt)return new mt(`NUMBER(${i.valueOf()})`);if(i instanceof ft)return new ft(i.valueOf(),{...i.opts,...xt(t,Tt)});if(i instanceof bt)return new ft(i.toNumber(),{...xt(t,Tt)});throw new TypeError("Invalid argument to NUMBER")}const _t=["dateStyle","timeStyle","fractionalSecondDigits","dayPeriod","hour12","weekday","era","year","month","day","hour","minute","second","timeZoneName"];function Mt(e,t){let i=e[0];if(i instanceof mt)return new mt(`DATETIME(${i.valueOf()})`);if(i instanceof bt||i instanceof ft)return new bt(i,xt(t,_t));throw new TypeError("Invalid argument to DATETIME")}const It=new Map;class At{constructor(e,{functions:t,useIsolating:i=!0,transform:n=e=>e}={}){this._terms=new Map,this._messages=new Map,this.locales=Array.isArray(e)?e:[e],this._functions={NUMBER:Lt,DATETIME:Mt,...t},this._useIsolating=i,this._transform=n,this._intls=function(e){const t=Array.isArray(e)?e.join(" "):e;let i=It.get(t);return void 0===i&&(i=new Map,It.set(t,i)),i}(e)}hasMessage(e){return this._messages.has(e)}getMessage(e){return this._messages.get(e)}addResource(e,{allowOverrides:t=!1}={}){const i=[];for(let n=0;n<e.body.length;n++){let s=e.body[n];if(s.id.startsWith("-")){if(!1===t&&this._terms.has(s.id)){i.push(new Error(`Attempt to override an existing term: "${s.id}"`));continue}this._terms.set(s.id,s)}else{if(!1===t&&this._messages.has(s.id)){i.push(new Error(`Attempt to override an existing message: "${s.id}"`));continue}this._messages.set(s.id,s)}}return i}formatPattern(e,t=null,i=null){if("string"==typeof e)return this._transform(e);let n=new Et(this,i,t);try{return Pt(n,e).toString(n)}catch(e){if(n.errors&&e instanceof Error)return n.errors.push(e),(new mt).toString(n);throw e}}}const Bt=/^(-?[a-zA-Z][\w-]*) *= */gm,kt=/\.([a-zA-Z][\w-]*) *= */y,Dt=/\*?\[/y,Nt=/(-?[0-9]+(?:\.([0-9]+))?)/y,Ot=/([a-zA-Z][\w-]*)/y,Rt=/([$-])?([a-zA-Z][\w-]*)(?:\.([a-zA-Z][\w-]*))?/y,jt=/^[A-Z][A-Z0-9_-]*$/,Vt=/([^{}\n\r]+)/y,Ft=/([^\\"\n\r]*)/y,Ut=/\\([\\"])/y,zt=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{6})/y,Ht=/^\n+/,$t=/ +$/,Wt=/ *\r?\n/g,Xt=/( *)$/,Gt=/{\s*/y,Yt=/\s*}/y,Kt=/\[\s*/y,Zt=/\s*] */y,qt=/\s*\(\s*/y,Qt=/\s*->\s*/y,Jt=/\s*:\s*/y,ei=/\s*,?\s*/y,ti=/\s+/y;class ii{constructor(e){this.body=[],Bt.lastIndex=0;let t=0;for(;;){let i=Bt.exec(e);if(null===i)break;t=Bt.lastIndex;try{this.body.push(o(i[1]))}catch(e){if(e instanceof SyntaxError)continue;throw e}}function i(i){return i.lastIndex=t,i.test(e)}function n(i,n){if(e[t]===i)return t++,!0;if(n)throw new n(`Expected ${i}`);return!1}function s(e,n){if(i(e))return t=e.lastIndex,!0;if(n)throw new n(`Expected ${e.toString()}`);return!1}function a(i){i.lastIndex=t;let n=i.exec(e);if(null===n)throw new SyntaxError(`Expected ${i.toString()}`);return t=i.lastIndex,n}function r(e){return a(e)[1]}function o(e){let t=l(),n=function(){let e=Object.create(null);for(;i(kt);){let t=r(kt),i=l();if(null===i)throw new SyntaxError("Expected attribute value");e[t]=i}return e}();if(null===t&&0===Object.keys(n).length)throw new SyntaxError("Expected message value or attributes");return{id:e,value:t,attributes:n}}function l(){let n;if(i(Vt)&&(n=r(Vt)),"{"===e[t]||"}"===e[t])return d(n?[n]:[],1/0);let s=b();return s?n?d([n,s],s.length):(s.value=v(s.value,Ht),d([s],s.length)):n?v(n,$t):null}function d(n=[],s){for(;;){if(i(Vt)){n.push(r(Vt));continue}if("{"===e[t]){n.push(h());continue}if("}"===e[t])throw new SyntaxError("Unbalanced closing brace");let a=b();if(!a)break;n.push(a),s=Math.min(s,a.length)}let a=n.length-1,o=n[a];"string"==typeof o&&(n[a]=v(o,$t));let l=[];for(let e of n)e instanceof ni&&(e=e.value.slice(0,e.value.length-s)),e&&l.push(e);return l}function h(){s(Gt,SyntaxError);let e=c();if(s(Yt))return e;if(s(Qt)){let t=function(){let e,t=[],s=0;for(;i(Dt);){n("*")&&(e=s);let i=g(),a=l();if(null===a)throw new SyntaxError("Expected variant value");t[s++]={key:i,value:a}}if(0===s)return null;if(void 0===e)throw new SyntaxError("Expected default variant");return{variants:t,star:e}}();return s(Yt,SyntaxError),{type:"select",selector:e,...t}}throw new SyntaxError("Unclosed placeable")}function c(){if("{"===e[t])return h();if(i(Rt)){let[,i,n,r=null]=a(Rt);if("$"===i)return{type:"var",name:n};if(s(qt)){let a=function(){let i=[];for(;;){switch(e[t]){case")":return t++,i;case void 0:throw new SyntaxError("Unclosed argument list")}i.push(u()),s(ei)}}();if("-"===i)return{type:"term",name:n,attr:r,args:a};if(jt.test(n))return{type:"func",name:n,args:a};throw new SyntaxError("Function names must be all upper-case")}return"-"===i?{type:"term",name:n,attr:r,args:[]}:{type:"mesg",name:n,attr:r}}return p()}function u(){let e=c();return"mesg"!==e.type?e:s(Jt)?{type:"narg",name:e.name,value:p()}:e}function g(){let e;return s(Kt,SyntaxError),e=i(Nt)?m():{type:"str",value:r(Ot)},s(Zt,SyntaxError),e}function p(){if(i(Nt))return m();if('"'===e[t])return function(){n('"',SyntaxError);let i="";for(;;){if(i+=r(Ft),"\\"!==e[t]){if(n('"'))return{type:"str",value:i};throw new SyntaxError("Unclosed string literal")}i+=f()}}();throw new SyntaxError("Invalid expression")}function m(){let[,e,t=""]=a(Nt),i=t.length;return{type:"num",value:parseFloat(e),precision:i}}function f(){if(i(Ut))return r(Ut);if(i(zt)){let[,e,t]=a(zt),i=parseInt(e||t,16);return i<=55295||57344<=i?String.fromCodePoint(i):"�"}throw new SyntaxError("Unknown escape sequence")}function b(){let i=t;switch(s(ti),e[t]){case".":case"[":case"*":case"}":case void 0:return!1;case"{":return w(e.slice(i,t))}return" "===e[t-1]&&w(e.slice(i,t))}function v(e,t){return e.replace(t,"")}function w(e){let t=e.replace(Wt,"\n"),i=Xt.exec(e)[1].length;return new ni(t,i)}}}class ni{constructor(e,t){this.value=e,this.length=t}}const si=/<|&#?\w+;/,ai={"http://www.w3.org/1999/xhtml":["em","strong","small","s","cite","q","dfn","abbr","data","time","code","var","samp","kbd","sub","sup","i","b","u","mark","bdi","bdo","span","br","wbr"]},ri={"http://www.w3.org/1999/xhtml":{global:["title","aria-description","aria-label","aria-valuetext"],a:["download"],area:["download","alt"],input:["alt","placeholder"],menuitem:["label"],menu:["label"],optgroup:["label"],option:["label"],track:["label"],img:["alt"],textarea:["placeholder"],th:["abbr"]},"http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul":{global:["accesskey","aria-label","aria-valuetext","label","title","tooltiptext"],description:["value"],key:["key","keycode"],label:["value"],textbox:["placeholder","value"]}};function oi(e,t){const{value:i}=t;if("string"==typeof i)if("title"===e.localName&&"http://www.w3.org/1999/xhtml"===e.namespaceURI)e.textContent=i;else if(si.test(i)){const t=e.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml","template");t.innerHTML=i,function(e,t){for(const i of e.childNodes)if(i.nodeType!==i.TEXT_NODE){if(i.hasAttribute("data-l10n-name")){const n=hi(t,i);e.replaceChild(n,i);continue}if(gi(i)){const t=ci(i);e.replaceChild(t,i);continue}console.warn(`An element of forbidden type "${i.localName}" was found in the translation. Only safe text-level elements and elements with data-l10n-name are allowed.`),e.replaceChild(ui(i),i)}t.textContent="",t.appendChild(e)}(t.content,e)}else e.textContent=i;di(t,e)}function li(e,t){if(!e)return!1;for(let i of e)if(i.name===t)return!0;return!1}function di(e,t){const i=t.hasAttribute("data-l10n-attrs")?t.getAttribute("data-l10n-attrs").split(",").map(e=>e.trim()):null;for(const n of Array.from(t.attributes))pi(n.name,t,i)&&!li(e.attributes,n.name)&&t.removeAttribute(n.name);if(e.attributes)for(const n of Array.from(e.attributes))pi(n.name,t,i)&&t.getAttribute(n.name)!==n.value&&t.setAttribute(n.name,n.value)}function hi(e,t){const i=t.getAttribute("data-l10n-name"),n=e.querySelector(`[data-l10n-name="${i}"]`);if(!n)return console.warn(`An element named "${i}" wasn't found in the source.`),ui(t);if(n.localName!==t.localName)return console.warn(`An element named "${i}" was found in the translation but its type ${t.localName} didn't match the element found in the source (${n.localName}).`),ui(t);e.removeChild(n);return mi(t,n.cloneNode(!1))}function ci(e){const t=e.ownerDocument.createElement(e.localName);return mi(e,t)}function ui(e){return e.ownerDocument.createTextNode(e.textContent)}function gi(e){const t=ai[e.namespaceURI];return t&&t.includes(e.localName)}function pi(e,t,i=null){if(i&&i.includes(e))return!0;const n=ri[t.namespaceURI];if(!n)return!1;const s=e.toLowerCase(),a=t.localName;if(n.global.includes(s))return!0;if(!n[a])return!1;if(n[a].includes(s))return!0;if("http://www.w3.org/1999/xhtml"===t.namespaceURI&&"input"===a&&"value"===s){const e=t.type.toLowerCase();if("submit"===e||"button"===e||"reset"===e)return!0}return!1}function mi(e,t){return t.textContent=e.textContent,di(e,t),t}class fi extends Array{static from(e){return e instanceof this?e:new this(e)}}Symbol.iterator;class bi extends fi{constructor(e){if(super(),Symbol.asyncIterator in Object(e))this.iterator=e[Symbol.asyncIterator]();else{if(!(Symbol.iterator in Object(e)))throw new TypeError("Argument must implement the iteration protocol.");this.iterator=e[Symbol.iterator]()}}[Symbol.asyncIterator](){const e=this;let t=0;return{next:async()=>(e.length<=t&&e.push(e.iterator.next()),e[t++])}}async touchNext(e=1){let t=0;for(;t++<e;){const e=this[this.length-1];if(e&&(await e).done)break;this.push(this.iterator.next())}return this[this.length-1]}}class vi{constructor(e=[],t){this.resourceIds=e,this.generateBundles=t,this.onChange(!0)}addResourceIds(e,t=!1){return this.resourceIds.push(...e),this.onChange(t),this.resourceIds.length}removeResourceIds(e){return this.resourceIds=this.resourceIds.filter(t=>!e.includes(t)),this.onChange(),this.resourceIds.length}async formatWithFallback(e,t){const i=[];let n=!1;for await(const s of this.bundles){n=!0;const a=Ci(t,s,e,i);if(0===a.size)break;if("undefined"!=typeof console){const e=s.locales[0],t=Array.from(a).join(", ");console.warn(`[fluent] Missing translations in ${e}: ${t}`)}}return n||"undefined"==typeof console||console.warn(`[fluent] Request for keys failed because no resource bundles got generated.\n  keys: ${JSON.stringify(e)}.\n  resourceIds: ${JSON.stringify(this.resourceIds)}.`),i}formatMessages(e){return this.formatWithFallback(e,yi)}formatValues(e){return this.formatWithFallback(e,wi)}async formatValue(e,t){const[i]=await this.formatValues([{id:e,args:t}]);return i}handleEvent(){this.onChange()}onChange(e=!1){this.bundles=bi.from(this.generateBundles(this.resourceIds)),e&&this.bundles.touchNext(2)}}function wi(e,t,i,n){return i.value?e.formatPattern(i.value,n,t):null}function yi(e,t,i,n){const s={value:null,attributes:null};i.value&&(s.value=e.formatPattern(i.value,n,t));let a=Object.keys(i.attributes);if(a.length>0){s.attributes=new Array(a.length);for(let[r,o]of a.entries()){let a=e.formatPattern(i.attributes[o],n,t);s.attributes[r]={name:o,value:a}}}return s}function Ci(e,t,i,n){const s=[],a=new Set;return i.forEach(({id:i,args:r},o)=>{if(void 0!==n[o])return;let l=t.getMessage(i);if(l){if(s.length=0,n[o]=e(t,s,l,r),s.length>0&&"undefined"!=typeof console){const e=t.locales[0],n=s.join(", ");console.warn(`[fluent][resolver] errors in ${e}/${i}: ${n}.`)}}else a.add(i)}),a}const Pi="data-l10n-id",Si="data-l10n-args",Ei=`[${Pi}]`;class xi extends vi{constructor(e,t){super(e,t),this.roots=new Set,this.pendingrAF=null,this.pendingElements=new Set,this.windowElement=null,this.mutationObserver=null,this.observerConfig={attributes:!0,characterData:!1,childList:!0,subtree:!0,attributeFilter:[Pi,Si]}}onChange(e=!1){super.onChange(e),this.roots&&this.translateRoots()}setAttributes(e,t,i){return e.setAttribute(Pi,t),i?e.setAttribute(Si,JSON.stringify(i)):e.removeAttribute(Si),e}getAttributes(e){return{id:e.getAttribute(Pi),args:JSON.parse(e.getAttribute(Si)||null)}}connectRoot(e){for(const t of this.roots)if(t===e||t.contains(e)||e.contains(t))throw new Error("Cannot add a root that overlaps with existing root.");if(this.windowElement){if(this.windowElement!==e.ownerDocument.defaultView)throw new Error("Cannot connect a root:\n          DOMLocalization already has a root from a different window.")}else this.windowElement=e.ownerDocument.defaultView,this.mutationObserver=new this.windowElement.MutationObserver(e=>this.translateMutations(e));this.roots.add(e),this.mutationObserver.observe(e,this.observerConfig)}disconnectRoot(e){return this.roots.delete(e),this.pauseObserving(),0===this.roots.size?(this.mutationObserver=null,this.windowElement&&this.pendingrAF&&this.windowElement.cancelAnimationFrame(this.pendingrAF),this.windowElement=null,this.pendingrAF=null,this.pendingElements.clear(),!0):(this.resumeObserving(),!1)}translateRoots(){const e=Array.from(this.roots);return Promise.all(e.map(e=>this.translateFragment(e)))}pauseObserving(){this.mutationObserver&&(this.translateMutations(this.mutationObserver.takeRecords()),this.mutationObserver.disconnect())}resumeObserving(){if(this.mutationObserver)for(const e of this.roots)this.mutationObserver.observe(e,this.observerConfig)}translateMutations(e){for(const t of e)switch(t.type){case"attributes":t.target.hasAttribute("data-l10n-id")&&this.pendingElements.add(t.target);break;case"childList":for(const e of t.addedNodes)if(e.nodeType===e.ELEMENT_NODE)if(e.childElementCount)for(const t of this.getTranslatables(e))this.pendingElements.add(t);else e.hasAttribute(Pi)&&this.pendingElements.add(e)}this.pendingElements.size>0&&null===this.pendingrAF&&(this.pendingrAF=this.windowElement.requestAnimationFrame(()=>{this.translateElements(Array.from(this.pendingElements)),this.pendingElements.clear(),this.pendingrAF=null}))}translateFragment(e){return this.translateElements(this.getTranslatables(e))}async translateElements(e){if(!e.length)return;const t=e.map(this.getKeysForElement),i=await this.formatMessages(t);return this.applyTranslations(e,i)}applyTranslations(e,t){this.pauseObserving();for(let i=0;i<e.length;i++)void 0!==t[i]&&oi(e[i],t[i]);this.resumeObserving()}getTranslatables(e){const t=Array.from(e.querySelectorAll(Ei));return"function"==typeof e.hasAttribute&&e.hasAttribute(Pi)&&t.push(e),t}getKeysForElement(e){return{id:e.getAttribute(Pi),args:JSON.parse(e.getAttribute(Si)||null)}}}class Ti{#d;#h;#c;#u;constructor({lang:e,isRTL:t},i=null){this.#c=Ti.#g(e),this.#u=i,this.#d=t??Ti.#p(this.#c)?"rtl":"ltr"}_setL10n(e){this.#u=e}getLanguage(){return this.#c}getDirection(){return this.#d}async get(e,t=null,i){if(Array.isArray(e)){e=e.map(e=>({id:e}));return(await this.#u.formatMessages(e)).map(e=>e.value)}const n=await this.#u.formatMessages([{id:e,args:t}]);return n[0]?.value||i}async translate(e){(this.#h||=new Set).add(e);try{this.#u.connectRoot(e),await this.#u.translateRoots()}catch{}}async translateOnce(e){try{await this.#u.translateElements([e])}catch(e){console.error("translateOnce:",e)}}async destroy(){if(this.#h){for(const e of this.#h)this.#u.disconnectRoot(e);this.#h.clear(),this.#h=null}this.#u.pauseObserving()}pause(){this.#u.pauseObserving()}resume(){this.#u.resumeObserving()}static#g(e){return{en:"en-us",es:"es-es",fy:"fy-nl",ga:"ga-ie",gu:"gu-in",hi:"hi-in",hy:"hy-am",nb:"nb-no",ne:"ne-np",nn:"nn-no",pa:"pa-in",pt:"pt-pt",sv:"sv-se",zh:"zh-cn"}[e=e?.toLowerCase()||"en-us"]||e}static#p(e){const t=e.split("-",1)[0];return["ar","he","fa","ps","ur"].includes(t)}}function Li(){const{isAndroid:e,isLinux:t,isMac:i,isWindows:n}=pe.platform;return t?"linux":n?"windows":i?"macos":e?"android":"other"}function _i(e,t){const i=new ii(t),n=new At(e,{functions:{PLATFORM:Li}}),s=n.addResource(i);return s.length&&console.error("L10n errors",s),n}class Mi extends Ti{constructor(e){super({lang:e});const t=e?Mi.#m.bind(Mi,"en-us",this.getLanguage()):Mi.#f.bind(Mi,this.getLanguage());this._setL10n(new xi([],t))}static async*#m(e,t){const{baseURL:i,paths:n}=await this.#b(),s=[t];if(e!==t){const i=t.split("-",1)[0];i!==t&&s.push(i),s.push(e)}const a=s.map(e=>[e,this.#v(e,i,n)]);for(const[e,t]of a){const i=await t;i?yield i:"en-us"===e&&(yield this.#w(e))}}static async#v(e,t,i){const n=i[e];if(!n)return null;const s=new URL(n,t);return _i(e,await me(s,"text"))}static async#b(){try{const{href:e}=document.querySelector('link[type="application/l10n"]'),t=await me(e,"json");return{baseURL:e.substring(0,e.lastIndexOf("/")+1)||"./",paths:t}}catch{}return{baseURL:"./",paths:Object.create(null)}}static async*#f(e){yield this.#w(e)}static async#w(e){return _i(e,'pdfjs-previous-button =\n    .title = Previous Page\npdfjs-previous-button-label = Previous\npdfjs-next-button =\n    .title = Next Page\npdfjs-next-button-label = Next\npdfjs-page-input =\n    .title = Page\npdfjs-of-pages = of { $pagesCount }\npdfjs-page-of-pages = ({ $pageNumber } of { $pagesCount })\npdfjs-zoom-out-button =\n    .title = Zoom Out\npdfjs-zoom-out-button-label = Zoom Out\npdfjs-zoom-in-button =\n    .title = Zoom In\npdfjs-zoom-in-button-label = Zoom In\npdfjs-zoom-select =\n    .title = Zoom\npdfjs-presentation-mode-button =\n    .title = Switch to Presentation Mode\npdfjs-presentation-mode-button-label = Presentation Mode\npdfjs-open-file-button =\n    .title = Open File\npdfjs-open-file-button-label = Open\npdfjs-print-button =\n    .title = Print\npdfjs-print-button-label = Print\npdfjs-save-button =\n    .title = Save\npdfjs-save-button-label = Save\npdfjs-download-button =\n    .title = Download\npdfjs-download-button-label = Download\npdfjs-bookmark-button =\n    .title = Current Page (View URL from Current Page)\npdfjs-bookmark-button-label = Current Page\npdfjs-tools-button =\n    .title = Tools\npdfjs-tools-button-label = Tools\npdfjs-first-page-button =\n    .title = Go to First Page\npdfjs-first-page-button-label = Go to First Page\npdfjs-last-page-button =\n    .title = Go to Last Page\npdfjs-last-page-button-label = Go to Last Page\npdfjs-page-rotate-cw-button =\n    .title = Rotate Clockwise\npdfjs-page-rotate-cw-button-label = Rotate Clockwise\npdfjs-page-rotate-ccw-button =\n    .title = Rotate Counterclockwise\npdfjs-page-rotate-ccw-button-label = Rotate Counterclockwise\npdfjs-cursor-text-select-tool-button =\n    .title = Enable Text Selection Tool\npdfjs-cursor-text-select-tool-button-label = Text Selection Tool\npdfjs-cursor-hand-tool-button =\n    .title = Enable Hand Tool\npdfjs-cursor-hand-tool-button-label = Hand Tool\npdfjs-scroll-page-button =\n    .title = Use Page Scrolling\npdfjs-scroll-page-button-label = Page Scrolling\npdfjs-scroll-vertical-button =\n    .title = Use Vertical Scrolling\npdfjs-scroll-vertical-button-label = Vertical Scrolling\npdfjs-scroll-horizontal-button =\n    .title = Use Horizontal Scrolling\npdfjs-scroll-horizontal-button-label = Horizontal Scrolling\npdfjs-scroll-wrapped-button =\n    .title = Use Wrapped Scrolling\npdfjs-scroll-wrapped-button-label = Wrapped Scrolling\npdfjs-spread-none-button =\n    .title = Do not join page spreads\npdfjs-spread-none-button-label = No Spreads\npdfjs-spread-odd-button =\n    .title = Join page spreads starting with odd-numbered pages\npdfjs-spread-odd-button-label = Odd Spreads\npdfjs-spread-even-button =\n    .title = Join page spreads starting with even-numbered pages\npdfjs-spread-even-button-label = Even Spreads\npdfjs-document-properties-button =\n    .title = Document Properties…\npdfjs-document-properties-button-label = Document Properties…\npdfjs-document-properties-file-name = File name:\npdfjs-document-properties-file-size = File size:\npdfjs-document-properties-size-kb = { NUMBER($kb, maximumSignificantDigits: 3) } KB ({ $b } bytes)\npdfjs-document-properties-size-mb = { NUMBER($mb, maximumSignificantDigits: 3) } MB ({ $b } bytes)\npdfjs-document-properties-title = Title:\npdfjs-document-properties-author = Author:\npdfjs-document-properties-subject = Subject:\npdfjs-document-properties-keywords = Keywords:\npdfjs-document-properties-creation-date = Creation Date:\npdfjs-document-properties-modification-date = Modification Date:\npdfjs-document-properties-date-time-string = { DATETIME($dateObj, dateStyle: "short", timeStyle: "medium") }\npdfjs-document-properties-creator = Creator:\npdfjs-document-properties-producer = PDF Producer:\npdfjs-document-properties-version = PDF Version:\npdfjs-document-properties-page-count = Page Count:\npdfjs-document-properties-page-size = Page Size:\npdfjs-document-properties-page-size-unit-inches = in\npdfjs-document-properties-page-size-unit-millimeters = mm\npdfjs-document-properties-page-size-orientation-portrait = portrait\npdfjs-document-properties-page-size-orientation-landscape = landscape\npdfjs-document-properties-page-size-name-a-three = A3\npdfjs-document-properties-page-size-name-a-four = A4\npdfjs-document-properties-page-size-name-letter = Letter\npdfjs-document-properties-page-size-name-legal = Legal\npdfjs-document-properties-page-size-dimension-string = { $width } × { $height } { $unit } ({ $orientation })\npdfjs-document-properties-page-size-dimension-name-string = { $width } × { $height } { $unit } ({ $name }, { $orientation })\npdfjs-document-properties-linearized = Fast Web View:\npdfjs-document-properties-linearized-yes = Yes\npdfjs-document-properties-linearized-no = No\npdfjs-document-properties-close-button = Close\npdfjs-print-progress-message = Preparing document for printing…\npdfjs-print-progress-percent = { $progress }%\npdfjs-print-progress-close-button = Cancel\npdfjs-printing-not-supported = Warning: Printing is not fully supported by this browser.\npdfjs-printing-not-ready = Warning: The PDF is not fully loaded for printing.\npdfjs-current-outline-item-button =\n    .title = Find Current Outline Item\npdfjs-current-outline-item-button-label = Current Outline Item\npdfjs-findbar-button =\n    .title = Find in Document\npdfjs-findbar-button-label = Find\npdfjs-additional-layers = Additional Layers\npdfjs-thumb-page-title1 =\n    .title = Page { $page } of { $total }\npdfjs-thumb-page-canvas =\n    .aria-label = Thumbnail of Page { $page }\npdfjs-thumb-page-checkbox1 =\n    .title = Select page { $page }\npdfjs-find-input =\n    .title = Find\n    .placeholder = Find in document…\npdfjs-find-previous-button =\n    .title = Find the previous occurrence of the phrase\npdfjs-find-previous-button-label = Previous\npdfjs-find-next-button =\n    .title = Find the next occurrence of the phrase\npdfjs-find-next-button-label = Next\npdfjs-find-highlight-checkbox = Highlight All\npdfjs-find-match-case-checkbox-label = Match Case\npdfjs-find-match-diacritics-checkbox-label = Match Diacritics\npdfjs-find-entire-word-checkbox-label = Whole Words\npdfjs-find-reached-top = Reached top of document, continued from bottom\npdfjs-find-reached-bottom = Reached end of document, continued from top\npdfjs-find-match-count =\n    { $total ->\n        [one] { $current } of { $total } match\n       *[other] { $current } of { $total } matches\n    }\npdfjs-find-match-count-limit =\n    { $limit ->\n        [one] More than { $limit } match\n       *[other] More than { $limit } matches\n    }\npdfjs-find-not-found = Phrase not found\npdfjs-page-scale-width = Page Width\npdfjs-page-scale-fit = Page Fit\npdfjs-page-scale-auto = Automatic Zoom\npdfjs-page-scale-actual = Actual Size\npdfjs-page-scale-percent = { $scale }%\npdfjs-page-landmark =\n    .aria-label = Page { $page }\npdfjs-loading-error = An error occurred while loading the PDF.\npdfjs-invalid-file-error = Invalid or corrupted PDF file.\npdfjs-missing-file-error = Missing PDF file.\npdfjs-unexpected-response-error = Unexpected server response.\npdfjs-rendering-error = An error occurred while rendering the page.\npdfjs-annotation-date-time-string = { DATETIME($dateObj, dateStyle: "short", timeStyle: "medium") }\npdfjs-text-annotation-type =\n    .alt = [{ $type } Annotation]\npdfjs-password-label = Enter the password to open this PDF file.\npdfjs-password-invalid = Invalid password. Please try again.\npdfjs-password-ok-button = OK\npdfjs-password-cancel-button = Cancel\npdfjs-web-fonts-disabled = Web fonts are disabled: unable to use embedded PDF fonts.\npdfjs-editor-free-text-button =\n    .title = Text\npdfjs-editor-color-picker-free-text-input =\n    .title = Change text color\npdfjs-editor-free-text-button-label = Text\npdfjs-editor-ink-button =\n    .title = Draw\npdfjs-editor-color-picker-ink-input =\n    .title = Change drawing color\npdfjs-editor-ink-button-label = Draw\npdfjs-editor-stamp-button =\n    .title = Add or edit images\npdfjs-editor-stamp-button-label = Add or edit images\npdfjs-editor-highlight-button =\n    .title = Highlight\npdfjs-editor-highlight-button-label = Highlight\npdfjs-highlight-floating-button1 =\n    .title = Highlight\n    .aria-label = Highlight\npdfjs-highlight-floating-button-label = Highlight\npdfjs-comment-floating-button =\n    .title = Comment\n    .aria-label = Comment\npdfjs-comment-floating-button-label = Comment\npdfjs-editor-comment-button =\n    .title = Comment\n    .aria-label = Comment\npdfjs-editor-comment-button-label = Comment\npdfjs-editor-signature-button =\n    .title = Add signature\npdfjs-editor-signature-button-label = Add signature\npdfjs-editor-highlight-editor =\n    .aria-label = Highlight editor\npdfjs-editor-ink-editor =\n    .aria-label = Drawing editor\npdfjs-editor-signature-editor1 =\n    .aria-description = Signature editor: { $description }\npdfjs-editor-stamp-editor =\n    .aria-label = Image editor\npdfjs-editor-remove-ink-button =\n    .title = Remove drawing\npdfjs-editor-remove-freetext-button =\n    .title = Remove text\npdfjs-editor-remove-stamp-button =\n    .title = Remove image\npdfjs-editor-remove-highlight-button =\n    .title = Remove highlight\npdfjs-editor-remove-signature-button =\n    .title = Remove signature\npdfjs-editor-free-text-color-input = Color\npdfjs-editor-free-text-size-input = Size\npdfjs-editor-ink-color-input = Color\npdfjs-editor-ink-thickness-input = Thickness\npdfjs-editor-ink-opacity-input = Opacity\npdfjs-editor-stamp-add-image-button =\n    .title = Add image\npdfjs-editor-stamp-add-image-button-label = Add image\npdfjs-editor-free-highlight-thickness-input = Thickness\npdfjs-editor-free-highlight-thickness-title =\n    .title = Change thickness when highlighting items other than text\npdfjs-editor-add-signature-container =\n    .aria-label = Signature controls and saved signatures\npdfjs-editor-signature-add-signature-button =\n    .title = Add new signature\npdfjs-editor-signature-add-signature-button-label = Add new signature\npdfjs-editor-add-saved-signature-button =\n    .title = Saved signature: { $description }\npdfjs-free-text2 =\n    .aria-label = Text Editor\n    .default-content = Start typing…\npdfjs-editor-comments-sidebar-title =\n    { $count ->\n        [one] Comment\n       *[other] Comments\n    }\npdfjs-editor-comments-sidebar-close-button =\n    .title = Close the sidebar\n    .aria-label = Close the sidebar\npdfjs-editor-comments-sidebar-close-button-label = Close the sidebar\npdfjs-editor-comments-sidebar-no-comments1 = See something noteworthy? Highlight it and leave a comment.\npdfjs-editor-comments-sidebar-no-comments-link = Learn more\npdfjs-editor-alt-text-button =\n    .aria-label = Alt text\npdfjs-editor-alt-text-button-label = Alt text\npdfjs-editor-alt-text-edit-button =\n    .aria-label = Edit alt text\npdfjs-editor-alt-text-dialog-label = Choose an option\npdfjs-editor-alt-text-dialog-description = Alt text (alternative text) helps when people can’t see the image or when it doesn’t load.\npdfjs-editor-alt-text-add-description-label = Add a description\npdfjs-editor-alt-text-add-description-description = Aim for 1-2 sentences that describe the subject, setting, or actions.\npdfjs-editor-alt-text-mark-decorative-label = Mark as decorative\npdfjs-editor-alt-text-mark-decorative-description = This is used for ornamental images, like borders or watermarks.\npdfjs-editor-alt-text-cancel-button = Cancel\npdfjs-editor-alt-text-save-button = Save\npdfjs-editor-alt-text-decorative-tooltip = Marked as decorative\npdfjs-editor-alt-text-textarea =\n    .placeholder = For example, “A young man sits down at a table to eat a meal”\npdfjs-editor-resizer-top-left =\n    .aria-label = Top left corner — resize\npdfjs-editor-resizer-top-middle =\n    .aria-label = Top middle — resize\npdfjs-editor-resizer-top-right =\n    .aria-label = Top right corner — resize\npdfjs-editor-resizer-middle-right =\n    .aria-label = Middle right — resize\npdfjs-editor-resizer-bottom-right =\n    .aria-label = Bottom right corner — resize\npdfjs-editor-resizer-bottom-middle =\n    .aria-label = Bottom middle — resize\npdfjs-editor-resizer-bottom-left =\n    .aria-label = Bottom left corner — resize\npdfjs-editor-resizer-middle-left =\n    .aria-label = Middle left — resize\npdfjs-editor-highlight-colorpicker-label = Highlight color\npdfjs-editor-colorpicker-button =\n    .title = Change color\npdfjs-editor-colorpicker-dropdown =\n    .aria-label = Color choices\npdfjs-editor-colorpicker-yellow =\n    .title = Yellow\npdfjs-editor-colorpicker-green =\n    .title = Green\npdfjs-editor-colorpicker-blue =\n    .title = Blue\npdfjs-editor-colorpicker-pink =\n    .title = Pink\npdfjs-editor-colorpicker-red =\n    .title = Red\npdfjs-editor-highlight-show-all-button-label = Show all\npdfjs-editor-highlight-show-all-button =\n    .title = Show all\npdfjs-editor-new-alt-text-dialog-edit-label = Edit alt text (image description)\npdfjs-editor-new-alt-text-dialog-add-label = Add alt text (image description)\npdfjs-editor-new-alt-text-textarea =\n    .placeholder = Write your description here…\npdfjs-editor-new-alt-text-description = Short description for people who can’t see the image or when the image doesn’t load.\npdfjs-editor-new-alt-text-disclaimer1 = This alt text was created automatically and may be inaccurate.\npdfjs-editor-new-alt-text-disclaimer-learn-more-url = Learn more\npdfjs-editor-new-alt-text-create-automatically-button-label = Create alt text automatically\npdfjs-editor-new-alt-text-not-now-button = Not now\npdfjs-editor-new-alt-text-error-title = Couldn’t create alt text automatically\npdfjs-editor-new-alt-text-error-description = Please write your own alt text or try again later.\npdfjs-editor-new-alt-text-error-close-button = Close\npdfjs-editor-new-alt-text-ai-model-downloading-progress = Downloading alt text AI model ({ $downloadedSize } of { $totalSize } MB)\n    .aria-valuetext = Downloading alt text AI model ({ $downloadedSize } of { $totalSize } MB)\npdfjs-editor-new-alt-text-added-button =\n    .aria-label = Alt text added\npdfjs-editor-new-alt-text-added-button-label = Alt text added\npdfjs-editor-new-alt-text-missing-button =\n    .aria-label = Missing alt text\npdfjs-editor-new-alt-text-missing-button-label = Missing alt text\npdfjs-editor-new-alt-text-to-review-button =\n    .aria-label = Review alt text\npdfjs-editor-new-alt-text-to-review-button-label = Review alt text\npdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer = Created automatically: { $generatedAltText }\npdfjs-image-alt-text-settings-button =\n    .title = Image alt text settings\npdfjs-image-alt-text-settings-button-label = Image alt text settings\npdfjs-editor-alt-text-settings-dialog-label = Image alt text settings\npdfjs-editor-alt-text-settings-automatic-title = Automatic alt text\npdfjs-editor-alt-text-settings-create-model-button-label = Create alt text automatically\npdfjs-editor-alt-text-settings-create-model-description = Suggests descriptions to help people who can’t see the image or when the image doesn’t load.\npdfjs-editor-alt-text-settings-editor-title = Alt text editor\npdfjs-editor-alt-text-settings-show-dialog-button-label = Show alt text editor right away when adding an image\npdfjs-editor-alt-text-settings-show-dialog-description = Helps you make sure all your images have alt text.\npdfjs-editor-alt-text-settings-close-button = Close\npdfjs-editor-highlight-added-alert = Highlight added\npdfjs-editor-freetext-added-alert = Text added\npdfjs-editor-ink-added-alert = Drawing added\npdfjs-editor-stamp-added-alert = Image added\npdfjs-editor-signature-added-alert = Signature added\npdfjs-editor-undo-bar-message-highlight = Highlight removed\npdfjs-editor-undo-bar-message-freetext = Text removed\npdfjs-editor-undo-bar-message-ink = Drawing removed\npdfjs-editor-undo-bar-message-stamp = Image removed\npdfjs-editor-undo-bar-message-signature = Signature removed\npdfjs-editor-undo-bar-message-comment = Comment removed\npdfjs-editor-undo-bar-message-multiple =\n    { $count ->\n        [one] { $count } annotation removed\n       *[other] { $count } annotations removed\n    }\npdfjs-editor-undo-bar-undo-button =\n    .title = Undo\npdfjs-editor-undo-bar-undo-button-label = Undo\npdfjs-editor-undo-bar-close-button =\n    .title = Close\npdfjs-editor-undo-bar-close-button-label = Close\npdfjs-editor-add-signature-dialog-label = This modal allows the user to create a signature to add to a PDF document. The user can edit the name (which also serves as the alt text), and optionally save the signature for repeated use.\npdfjs-editor-add-signature-dialog-title = Add a signature\npdfjs-editor-add-signature-type-button = Type\n    .title = Type\npdfjs-editor-add-signature-draw-button = Draw\n    .title = Draw\npdfjs-editor-add-signature-image-button = Image\n    .title = Image\npdfjs-editor-add-signature-type-input =\n    .aria-label = Type your signature\n    .placeholder = Type your signature\npdfjs-editor-add-signature-draw-placeholder = Draw your signature\npdfjs-editor-add-signature-draw-thickness-range-label = Thickness\npdfjs-editor-add-signature-draw-thickness-range =\n    .title = Drawing thickness: { $thickness }\npdfjs-editor-add-signature-image-placeholder = Drag a file here to upload\npdfjs-editor-add-signature-image-browse-link =\n    { PLATFORM() ->\n        [macos] Or choose image files\n       *[other] Or browse image files\n    }\npdfjs-editor-add-signature-description-label = Description (alt text)\npdfjs-editor-add-signature-description-input =\n    .title = Description (alt text)\npdfjs-editor-add-signature-description-default-when-drawing = Signature\npdfjs-editor-add-signature-clear-button-label = Clear signature\npdfjs-editor-add-signature-clear-button =\n    .title = Clear signature\npdfjs-editor-add-signature-save-checkbox = Save signature\npdfjs-editor-add-signature-save-warning-message = You’ve reached the limit of 5 saved signatures. Remove one to save more.\npdfjs-editor-add-signature-image-upload-error-title = Couldn’t upload image\npdfjs-editor-add-signature-image-upload-error-description = Check your network connection or try another image.\npdfjs-editor-add-signature-image-no-data-error-title = Can’t convert this image into a signature\npdfjs-editor-add-signature-image-no-data-error-description = Please try uploading a different image.\npdfjs-editor-add-signature-error-close-button = Close\npdfjs-editor-add-signature-cancel-button = Cancel\npdfjs-editor-add-signature-add-button = Add\npdfjs-editor-delete-signature-button1 =\n    .title = Remove saved signature\npdfjs-editor-delete-signature-button-label1 = Remove saved signature\npdfjs-editor-add-signature-edit-button-label = Edit description\npdfjs-editor-edit-signature-dialog-title = Edit description\npdfjs-editor-edit-signature-update-button = Update\npdfjs-show-comment-button =\n    .title = Show comment\npdfjs-editor-edit-comment-popup-button-label = Edit comment\npdfjs-editor-edit-comment-popup-button =\n    .title = Edit comment\npdfjs-editor-delete-comment-popup-button-label = Remove comment\npdfjs-editor-delete-comment-popup-button =\n    .title = Remove comment\npdfjs-editor-edit-comment-dialog-title-when-editing = Edit comment\npdfjs-editor-edit-comment-dialog-save-button-when-editing = Update\npdfjs-editor-edit-comment-dialog-title-when-adding = Add comment\npdfjs-editor-edit-comment-dialog-save-button-when-adding = Add\npdfjs-editor-edit-comment-dialog-text-input =\n    .placeholder = Start typing…\npdfjs-editor-edit-comment-dialog-cancel-button = Cancel\npdfjs-editor-add-comment-button =\n    .title = Add comment\npdfjs-toggle-views-manager-button1 =\n    .title = Manage pages\npdfjs-toggle-views-manager-notification-button =\n    .title = Toggle Sidebar (document contains thumbnails/outline/attachments/layers)\npdfjs-toggle-views-manager-button1-label = Manage pages\npdfjs-views-manager-sidebar =\n    .aria-label = Sidebar\npdfjs-views-manager-sidebar-resizer =\n    .aria-label = Sidebar resizer\npdfjs-views-manager-view-selector-button =\n    .title = Views\npdfjs-views-manager-view-selector-button-label = Views\npdfjs-views-manager-pages-title = Pages\npdfjs-views-manager-outlines-title1 = Document outline\n    .title = Document outline (double-click to expand/collapse all items)\npdfjs-views-manager-attachments-title = Attachments\npdfjs-views-manager-layers-title1 = Layers\n    .title = Layers (double-click to reset all layers to the default state)\npdfjs-views-manager-pages-option-label = Pages\npdfjs-views-manager-outlines-option-label = Document outline\npdfjs-views-manager-attachments-option-label = Attachments\npdfjs-views-manager-layers-option-label = Layers\npdfjs-views-manager-add-file-button =\n    .title = Add file\npdfjs-views-manager-add-file-button-label = Add file\npdfjs-views-manager-pages-status-action-label =\n    { $count ->\n        [one] { $count } selected\n        *[other] { $count } selected\n    }\npdfjs-views-manager-pages-status-none-action-label = Select pages\npdfjs-views-manager-pages-status-action-button-label = Manage\npdfjs-views-manager-pages-status-copy-button-label = Copy\npdfjs-views-manager-pages-status-cut-button-label = Cut\npdfjs-views-manager-pages-status-delete-button-label = Delete\npdfjs-views-manager-pages-status-export-selected-button-label = Export selected…\npdfjs-views-manager-status-undo-cut-label =\n    { $count ->\n        [one] 1 page cut\n        *[other] { $count } pages cut\n    }\npdfjs-views-manager-pages-status-undo-copy-label =\n    { $count ->\n        [one] 1 page copied\n        *[other] { $count } pages copied\n    }\npdfjs-views-manager-pages-status-undo-delete-label =\n    { $count ->\n        [one] 1 page deleted\n        *[other] { $count } pages deleted\n    }\npdfjs-views-manager-pages-status-waiting-ready-label = Getting your file ready…\npdfjs-views-manager-pages-status-waiting-uploading-label = Uploading file…\npdfjs-views-manager-status-warning-cut-label = Couldn’t cut. Refresh page and try again.\npdfjs-views-manager-status-warning-copy-label = Couldn’t copy. Refresh page and try again.\npdfjs-views-manager-status-warning-delete-label = Couldn’t delete. Refresh page and try again.\npdfjs-views-manager-status-warning-save-label = Couldn’t save. Refresh page and try again.\npdfjs-views-manager-status-undo-button-label = Undo\npdfjs-views-manager-status-done-button-label = Done\npdfjs-views-manager-status-close-button =\n    .title = Close\npdfjs-views-manager-status-close-button-label = Close\npdfjs-views-manager-paste-button-label = Paste\npdfjs-views-manager-paste-button-before =\n    .title = Paste before the first page\npdfjs-views-manager-paste-button-after =\n    .title = Paste after page { $page }\npdfjs-new-badge-content = NEW\npdfjs-views-manager-waiting-for-file = Uploading file…')}}class Ii{constructor(e,t){this._ready=new Promise((i,n)=>{import(e).then(e=>{i(e.QuickJSSandbox(new URL(t,location.href).href))}).catch(n)})}async createSandbox(e){(await this._ready).create(e)}async dispatchEventInSandbox(e){const t=await this._ready;setTimeout(()=>t.dispatchEvent(e),0)}async destroySandbox(){(await this._ready).nukeSandbox()}}const Ai="pdfjs.signature";class Bi{#y;#C=null;#P=null;constructor(e,t){this.#y=e,this.#P=t}#S(){localStorage.setItem(Ai,JSON.stringify(Object.fromEntries(this.#C)))}async getAll(){if(this.#P&&(window.addEventListener("storage",({key:e})=>{e===Ai&&(this.#C=null,this.#y?.dispatch("storedsignatureschanged",{source:this}))},{signal:this.#P}),this.#P=null),!this.#C){this.#C=new Map;const e=localStorage.getItem(Ai);if(e)for(const[t,i]of Object.entries(JSON.parse(e)))this.#C.set(t,i)}return this.#C}async isFull(){return 5===await this.size()}async size(){return(await this.getAll()).size}async create(e){if(await this.isFull())return null;const t=Pe();return this.#C.set(t,e),this.#S(),t}async delete(e){const t=await this.getAll();return!!t.has(e)&&(t.delete(e),this.#S(),!0)}}class ki extends ut{constructor(){super()}async createL10n(){return new Mi(Z.get("localeProperties")?.lang)}createScripting(){return new Ii(Z.get("sandboxBundleSrc"),Z.get("wasmUrl"))}createSignatureStorage(e,t){return new Bi(e,t)}}class Di{#E=this.#x.bind(this);#T;#L=null;#_;#M;#I;#A;#B;#k;#y;#D=!1;#N;#O=null;#R=null;#j;#V;#F=!1;#U=!1;#z;#H;#$;#W;#X;#G;#Y=null;constructor({descriptionContainer:e,dialog:t,imagePreview:i,cancelButton:n,disclaimer:s,notNowButton:a,saveButton:r,textarea:o,learnMore:l,errorCloseButton:d,createAutomaticallyButton:h,downloadModel:c,downloadModelDescription:u,title:g},p,m){this.#_=n,this.#T=h,this.#M=e,this.#I=t,this.#A=s,this.#H=a,this.#j=i,this.#W=o,this.#z=l,this.#X=g,this.#B=c,this.#k=u,this.#$=p,this.#y=m,t.addEventListener("close",this.#K.bind(this)),t.addEventListener("contextmenu",e=>{e.target!==this.#W&&e.preventDefault()}),n.addEventListener("click",this.#E),a.addEventListener("click",this.#E),r.addEventListener("click",this.#S.bind(this)),d.addEventListener("click",()=>{this.#Z(!1)}),h.addEventListener("click",async()=>{const e="true"!==h.getAttribute("aria-pressed");if(this.#L._reportTelemetry({action:"pdfjs.image.alt_text.ai_generation_check",data:{status:e}}),this.#G){const t=await this.#G.mlManager.isEnabledFor("altText");this.#T.disabled=!0,e&&!t?(this.#W.value="",this.#q(),this.#G.setPreference("enableGuessAltText",!0),await this.#G.mlManager.downloadModel("altText"),this.#Q("enableAltTextModelDownload",!0)):!e&&t&&(this.#G.setPreference("enableGuessAltText",!1),await this.#G.mlManager.deleteModel("altText"),this.#Q("enableAltTextModelDownload",!1)),this.#T.disabled=!1,await this.#G.mlManager.toggleService("altText",e)}this.#J(e,!1)}),o.addEventListener("focus",()=>{this.#U=this.#F,this.#ee(!1),this.#te()}),o.addEventListener("blur",()=>{o.value||this.#ee(this.#U),this.#te()}),o.addEventListener("input",()=>{this.#te()}),o.addEventListener("keydown",e=>{!e.ctrlKey&&!e.metaKey||"Enter"!==e.key||r.disabled||this.#S()}),m.on("enableguessalttext",({value:e})=>{this.#J(e,!1)},Q),this.#$.register(t),this.#z.addEventListener("click",()=>{this.#L._reportTelemetry({action:"pdfjs.image.alt_text.info",data:{topic:"alt_text"}})})}#Q(e,t){this.#y.dispatch("setpreference",{source:this,name:e,value:t})}#ee(e){this.#G&&this.#F!==e&&(this.#F=e,this.#M.classList.toggle("loading",e))}#Z(e){this.#G&&this.#I.classList.toggle("error",e)}async#J(e,t){if(this.#G)if(this.#I.classList.toggle("aiDisabled",!e),this.#T.setAttribute("aria-pressed",e),e){const{altTextLearnMoreUrl:e}=this.#G.mlManager;e&&(this.#z.href=e),this.#ie(t)}else this.#ee(!1),this.#F=!1,this.#te()}#ne(){this.#H.classList.toggle("hidden",!this.#D),this.#_.classList.toggle("hidden",this.#D)}#se(e){this.#G&&this.#O!==e&&(this.#O=e,this.#I.classList.toggle("noAi",!e),this.#te())}#te(){const e=this.#F||this.#N&&this.#N===this.#W.value;this.#A.hidden=!e;const t=this.#F||!!this.#W.value;this.#R!==t&&(this.#R=t,this.#X.setAttribute("data-l10n-id",t?"pdfjs-editor-new-alt-text-dialog-edit-label":"pdfjs-editor-new-alt-text-dialog-add-label"))}async#ie(e){if(this.#F)return;if(this.#W.value)return;if(e&&null!==this.#Y)return;if(this.#N=this.#L.guessedAltText,null===this.#Y&&this.#N)return void this.#ae(this.#N);this.#ee(!0),this.#te();let t=!1;try{const e=await this.#L.mlGuessAltText(this.#V,!1);e&&(this.#N=e,this.#U=this.#F,this.#F&&this.#ae(e))}catch(e){console.error(e),t=!0}this.#ee(!1),this.#te(),t&&this.#G&&this.#Z(!0)}#ae(e){this.#G&&!this.#W.value&&(this.#W.value=e,this.#te())}#q(){this.#B.classList.toggle("hidden",!1);const e=async({detail:{finished:t,total:i,totalLoaded:n}})=>{const s=1e6;n=Math.min(.99*i,n);const a=this.#k.ariaValueMax=Math.round(i/s),r=this.#k.ariaValueNow=Math.round(n/s);if(this.#k.setAttribute("data-l10n-args",JSON.stringify({totalSize:a,downloadedSize:r})),!t)return;if(this.#y.off("loadaiengineprogress",e),this.#B.classList.toggle("hidden",!0),this.#se(!0),!this.#G)return;const{mlManager:o}=this.#G;o.toggleService("altText",!0),this.#J(await o.isEnabledFor("altText"),!0)};this.#y.on("loadaiengineprogress",e,Q)}async editAltText(e,t,i){if(this.#L||!t)return;if(i&&t.hasAltTextData())return void t.altTextFinish();this.#D=i;const{mlManager:n}=e,s=!!n;this.#te(),n&&!n.isReady("altText")?n.hasProgress?this.#q():this.#T.setAttribute("aria-pressed",!1):this.#B.classList.toggle("hidden",!0);const a=n?.isEnabledFor("altText");this.#L=t,this.#G=e,this.#G.removeEditListeners(),({altText:this.#Y}=t.altTextData),this.#W.value=this.#Y??"";let r,o,l;n?(({canvas:r,width:o,height:l,imageData:this.#V}=t.copyCanvas(224,180,!0)),s&&this.#J(await a,!0)):({canvas:r,width:o,height:l}=t.copyCanvas(224,180,!1)),r.setAttribute("role","presentation");const{style:d}=r;d.width=`${o}px`,d.height=`${l}px`,this.#j.append(r),this.#ne(),this.#se(s),this.#Z(!1);try{await this.#$.open(this.#I)}catch(e){throw this.#K(),e}}#x(){this.#L.altTextData={cancel:!0};const e=this.#W.value.trim();this.#L._reportTelemetry({action:"pdfjs.image.alt_text.dismiss",data:{alt_text_type:e?"present":"empty",flow:this.#D?"image_add":"alt_text_edit"}}),this.#L._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!0,alt_text_type:"skipped"}}),this.#re()}#re(){this.#$.closeIfActive(this.#I)}#K(){const e=this.#j.firstElementChild;e.remove(),e.width=e.height=0,this.#V=null,this.#ee(!1),this.#G?.addEditListeners(),this.#L.altTextFinish(),this.#G?.setSelected(this.#L),this.#L=null,this.#G=null}#oe(e){return new Set(e.toLowerCase().split(/[^\p{L}\p{N}]+/gu).filter(e=>!!e))}#S(){const e=this.#W.value.trim();if(this.#L.altTextData={altText:e,decorative:!1},this.#L.altTextData.guessedAltText=this.#N,this.#N&&this.#N!==e){const t=this.#oe(this.#N),i=this.#oe(e);this.#L._reportTelemetry({action:"pdfjs.image.alt_text.user_edit",data:{total_words:t.size,words_removed:t.difference(i).size,words_added:i.difference(t).size}})}this.#L._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!0,alt_text_type:e?"present":"empty"}}),this.#L._reportTelemetry({action:"pdfjs.image.alt_text.save",data:{alt_text_type:e?"present":"empty",flow:this.#D?"image_add":"alt_text_edit"}}),this.#re()}destroy(){this.#G=null,this.#re()}}class Ni{#le;#I;#y;#de;#$;#he;constructor({dialog:e,createModelButton:t,learnMore:i,closeButton:n,showAltTextDialogButton:s},a,r,o){this.#I=e,this.#le=t,this.#he=s,this.#$=a,this.#y=r,this.#de=o;const{altTextLearnMoreUrl:l}=o;l&&(i.href=l),e.addEventListener("contextmenu",ke),t.addEventListener("click",async e=>{const t=this.#ce("enableGuessAltText",e);await(t?this.#ue(!0):this.#ge(!0)),await o.toggleService("altText",t),this.#pe({type:"stamp",action:"pdfjs.image.alt_text.settings_ai_generation_check",data:{status:t}})}),s.addEventListener("click",e=>{const t=this.#ce("enableNewAltTextWhenAddingImage",e);this.#pe({type:"stamp",action:"pdfjs.image.alt_text.settings_edit_alt_text_check",data:{status:t}})}),n.addEventListener("click",this.#re.bind(this)),i.addEventListener("click",()=>{this.#pe({type:"stamp",action:"pdfjs.image.alt_text.info",data:{topic:"ai_generation"}})}),r.on("enablealttextmodeldownload",({value:e})=>{e?this.#ue(!1):this.#ge(!1)},Q),this.#$.register(e)}#pe(e){this.#y.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:e}})}async#ue(e=!1){e&&(await this.#de.downloadModel("altText"),this.#Q("enableGuessAltText",!0),this.#de.toggleService("altText",!0),this.#Q("enableAltTextModelDownload",!0))}async#ge(e=!1){e&&(await this.#de.deleteModel("altText"),this.#Q("enableGuessAltText",!1),this.#Q("enableAltTextModelDownload",!1)),this.#le.setAttribute("aria-pressed",!1)}async open({enableGuessAltText:e,enableNewAltTextWhenAddingImage:t}){const{enableAltTextModelDownload:i}=this.#de;this.#le.setAttribute("aria-pressed",i&&e),this.#he.setAttribute("aria-pressed",t),await this.#$.open(this.#I),this.#pe({type:"stamp",action:"pdfjs.image.alt_text.settings_displayed"})}#ce(e,{target:t}){const i="true"!==t.getAttribute("aria-pressed");return this.#Q(e,i),t.setAttribute("aria-pressed",i),i}#Q(e,t){this.#y.dispatch("setpreference",{source:this,name:e,value:t})}#re(){this.#$.closeIfActive(this.#I)}}class Oi{#me=null;#L=null;#_;#I;#y;#fe=!1;#be;#ve;#$;#we;#W;#G;#Y=null;#ye=null;#Ce=null;#Pe=null;#Se;#Ee=null;constructor({dialog:e,optionDescription:t,optionDecorative:i,textarea:n,cancelButton:s,saveButton:a},r,o,l){this.#I=e,this.#be=t,this.#ve=i,this.#W=n,this.#_=s,this.#we=a,this.#$=o,this.#y=l,this.#Se=r;const d=this.#xe.bind(this);e.addEventListener("close",this.#K.bind(this)),e.addEventListener("contextmenu",e=>{e.target!==this.#W&&e.preventDefault()}),s.addEventListener("click",this.#re.bind(this)),a.addEventListener("click",this.#S.bind(this)),t.addEventListener("change",d),i.addEventListener("change",d),n.addEventListener("keydown",e=>{!e.ctrlKey&&!e.metaKey||"Enter"!==e.key||a.disabled||this.#S()}),this.#$.register(e)}#Te(){if(this.#Ce)return;const e=new ue,t=this.#Ce=e.createElement("svg");t.setAttribute("width","0"),t.setAttribute("height","0");const i=e.createElement("defs");t.append(i);const n=e.createElement("mask");i.append(n),n.setAttribute("id","alttext-manager-mask"),n.setAttribute("maskContentUnits","objectBoundingBox");let s=e.createElement("rect");n.append(s),s.setAttribute("fill","white"),s.setAttribute("width","1"),s.setAttribute("height","1"),s.setAttribute("x","0"),s.setAttribute("y","0"),s=this.#Pe=e.createElement("rect"),n.append(s),s.setAttribute("fill","black"),this.#I.append(t)}async editAltText(e,t){if(this.#L||!t)return;this.#Te(),this.#fe=!1,this.#me=new AbortController;const i={signal:this.#me.signal},n=this.#Le.bind(this);for(const e of[this.#be,this.#ve,this.#W,this.#we,this.#_])e.addEventListener("click",n,i);const{altText:s,decorative:a}=t.altTextData;!0===a?(this.#ve.checked=!0,this.#be.checked=!1):(this.#ve.checked=!1,this.#be.checked=!0),this.#Y=this.#W.value=s?.trim()||"",this.#xe(),this.#L=t,this.#G=e,this.#G.removeEditListeners(),this.#ye=new AbortController,this.#y.on("resize",this.#_e.bind(this),{signal:this.#ye.signal,...Q});try{await this.#$.open(this.#I),this.#_e()}catch(e){throw this.#K(),e}}#_e(){if(!this.#L)return;const e=this.#I,{style:t}=e,{x:i,y:n,width:s,height:a}=this.#Se.getBoundingClientRect(),{innerWidth:r,innerHeight:o}=window,{width:l,height:d}=e.getBoundingClientRect(),{x:h,y:c,width:u,height:g}=this.#L.getClientDimensions(),p=10,m="ltr"===this.#G.direction,f=Math.max(h,i),b=Math.min(h+u,i+s),v=Math.max(c,n),w=Math.min(c+g,n+a);this.#Pe.setAttribute("width",""+(b-f)/r),this.#Pe.setAttribute("height",""+(w-v)/o),this.#Pe.setAttribute("x",""+f/r),this.#Pe.setAttribute("y",""+v/o);let y=null,C=Math.max(c,0);C+=Math.min(o-(C+d),0),m?h+u+p+l<r?y=h+u+p:h>l+p&&(y=h-l-p):h>l+p?y=h-l-p:h+u+p+l<r&&(y=h+u+p),null===y&&(C=null,y=Math.max(h,0),y+=Math.min(r-(y+l),0),c>d+p?C=c-d-p:c+g+p+d<o&&(C=c+g+p)),null!==C?(e.classList.add("positioned"),m?t.left=`${y}px`:t.right=r-y-l+"px",t.top=`${C}px`):(e.classList.remove("positioned"),t.left="",t.top="")}#re(){this.#$.closeIfActive(this.#I)}#K(){this.#L._reportTelemetry(this.#Ee||{action:"alt_text_cancel",alt_text_keyboard:!this.#fe}),this.#Ee=null,this.#Me(),this.#G?.addEditListeners(),this.#ye?.abort(),this.#ye=null,this.#L.altTextFinish(),this.#L=null,this.#G=null}#xe(){this.#W.disabled=this.#ve.checked}#S(){const e=this.#W.value.trim(),t=this.#ve.checked;this.#L.altTextData={altText:e,decorative:t},this.#Ee={action:"alt_text_save",alt_text_description:!!e,alt_text_edit:!!this.#Y&&this.#Y!==e,alt_text_decorative:t,alt_text_keyboard:!this.#fe},this.#re()}#Le(e){0!==e.detail&&(this.#fe=!0,this.#Me())}#Me(){this.#me?.abort(),this.#me=null}destroy(){this.#G=null,this.#re(),this.#Ce?.remove(),this.#Ce=this.#Pe=null}}class Ri{constructor(e,t){this.eventBus=t,this.#Ie(e)}#Ie({editorFreeTextFontSize:e,editorFreeTextColor:t,editorInkColor:i,editorInkThickness:n,editorInkOpacity:s,editorStampAddImage:a,editorFreeHighlightThickness:r,editorHighlightShowAll:o,editorSignatureAddSignature:l}){const{eventBus:d}=this,h=(e,t)=>{d.dispatch("switchannotationeditorparams",{source:this,type:te[e],value:t})};let c,u;if(e.addEventListener("input",function(){h("FREETEXT_SIZE",this.valueAsNumber)}),t.addEventListener("input",function(){h("FREETEXT_COLOR",this.value)}),pe.isAlphaColorInputSupported){i.setAttribute("alpha",""),s.closest(".editorParamsSetter").remove();let e="#000000",t=1;i.addEventListener("input",function(){const i=Ce(this.value);if(!i)return;const[n,s,a,r]=i,o=tt.makeHexColor(n,s,a);e=o,t=r,h("INK_COLOR_AND_OPACITY",{color:o,opacity:r})}),c=n=>{e=n;const s=tt.hexNums[Math.round(255*t)];i.value=e+s},u=n=>{t=n;const s=tt.hexNums[Math.round(255*t)];i.value=e+s}}else i.addEventListener("input",function(){h("INK_COLOR",this.value)}),s.addEventListener("input",function(){h("INK_OPACITY",this.valueAsNumber)}),c=e=>{i.value=e},u=e=>{s.value=e};n.addEventListener("input",function(){h("INK_THICKNESS",this.valueAsNumber)}),a.addEventListener("click",()=>{d.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{action:"pdfjs.image.add_image_click"}}}),h("CREATE")}),r.addEventListener("input",function(){h("HIGHLIGHT_THICKNESS",this.valueAsNumber)}),o.addEventListener("click",function(){const e="true"===this.getAttribute("aria-pressed");this.setAttribute("aria-pressed",!e),h("HIGHLIGHT_SHOW_ALL",!e)}),l.addEventListener("click",()=>{h("CREATE")}),d.on("annotationeditorparamschanged",i=>{for(const[s,a]of i.details)switch(s){case te.FREETEXT_SIZE:e.value=a;break;case te.FREETEXT_COLOR:t.value=a;break;case te.INK_COLOR:c(a);break;case te.INK_THICKNESS:n.value=a;break;case te.INK_OPACITY:u(a);break;case te.HIGHLIGHT_COLOR:d.dispatch("mainhighlightcolorpickerupdatecolor",{source:this,value:a});break;case te.HIGHLIGHT_THICKNESS:r.value=a;break;case te.HIGHLIGHT_FREE:r.disabled=!a;break;case te.HIGHLIGHT_SHOW_ALL:o.setAttribute("aria-pressed",a)}},Q)}}const ji=.1;class Vi{#Ae;#Be=0;#ke;constructor(e,t,i,n){if(this.#Ae=t,this.#ke=i,!n)return;this.#Be=n.getBoundingClientRect().height;const s=new ResizeObserver(e=>{for(const t of e)if(t.target===n){this.#Be=Math.floor(t.borderBoxSize[0].blockSize);break}});s.observe(n),e.addEventListener("abort",()=>s.disconnect(),{once:!0})}#De(e,t){const i=e.y,n=e.bottom,s=e.y+e.height/2,a=t.y,r=t.bottom,o=t.y+t.height/2;return i<=o&&o<=n||a<=s&&s<=r}#Ne(e,t,i,n){const s=e.y+e.height/2;return(n?i>=s:i<=s)&&e.x-ji<=t&&t<=e.right+ji}#Oe(e){return e.top>=this.#Be&&e.left>=0&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&e.right<=(window.innerWidth||document.documentElement.clientWidth)}#Re(e,t){const{focusNode:i,focusOffset:n}=e,s=document.createRange();s.setStart(i,n),s.setEnd(i,n);const a=s.getBoundingClientRect();return[a.x,t?a.top:a.bottom]}static#je(e,t){if(!document.caretPositionFromPoint){const{startContainer:i,startOffset:n}=document.caretRangeFromPoint(e,t);return{offsetNode:i,offset:n}}return document.caretPositionFromPoint(e,t)}#Ve(e,t,i,n,s){if(s||=n.getBoundingClientRect(),t<=s.x+ji)return void(i?e.extend(n.firstChild,0):e.setPosition(n.firstChild,0));if(s.right-ji<=t){const{lastChild:t}=n;return void(i?e.extend(t,t.length):e.setPosition(t,t.length))}const a=s.y+s.height/2;let r=Vi.#je(t,a),o=r.offsetNode?.parentElement;if(o&&o!==n){const e=document.elementsFromPoint(t,a),i=[];for(const t of e){if(t===n)break;const{style:e}=t;i.push([t,e.visibility]),e.visibility="hidden"}r=Vi.#je(t,a),o=r.offsetNode?.parentElement;for(const[e,t]of i)e.style.visibility=t}o===n?i?e.extend(r.offsetNode,r.offset):e.setPosition(r.offsetNode,r.offset):i?e.extend(n.firstChild,0):e.setPosition(n.firstChild,0)}#Fe(e,t,i,n,s){this.#Oe(n)?this.#Ve(t,s,e,i,n):(this.#Ae.addEventListener("scrollend",this.#Ve.bind(this,t,s,e,i,null),{once:!0}),i.scrollIntoView())}#Ue(e,t){for(;;){const i=e.closest(".page"),n=parseInt(i.getAttribute("data-page-number"),10),s=t?n-1:n+1;if(!(e=this.#ke.querySelector(`.page[data-page-number="${s}"] .textLayer`)))return null;const a=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),r=t?a.lastChild():a.firstChild();if(r)return r}}moveCaret(e,t){const i=document.getSelection();if(0===i.rangeCount)return;const{focusNode:n}=i,s=n.nodeType!==Node.ELEMENT_NODE?n.parentElement:n,a=s.closest(".textLayer");if(!a)return;const r=document.createTreeWalker(a,NodeFilter.SHOW_TEXT);r.currentNode=n;const o=s.getBoundingClientRect();let l=null;const d=(e?r.previousSibling:r.nextSibling).bind(r);for(;d();){const e=r.currentNode.parentElement;if(!this.#De(o,e.getBoundingClientRect())){l=e;break}}if(!l){const s=this.#Ue(a,e);if(!s)return;if(t){const t=(e?r.firstChild():r.lastChild())||n;i.extend(t,e?0:t.length);const a=document.createRange();return a.setStart(s,e?s.length:0),a.setEnd(s,e?s.length:0),void i.addRange(a)}const[o]=this.#Re(i,e),{parentElement:l}=s;return void this.#Fe(t,i,l,l.getBoundingClientRect(),o)}const[h,c]=this.#Re(i,e),u=l.getBoundingClientRect();if(this.#Ne(u,h,c,e))this.#Fe(t,i,l,u,h);else{for(;d();){const n=r.currentNode.parentElement,s=n.getBoundingClientRect();if(!this.#De(u,s))break;if(this.#Ne(s,h,c,e))return void this.#Fe(t,i,n,s,h)}this.#Fe(t,i,l,u,h)}}}class Fi{#ze=0;#He=0;#$e;#We=null;#Xe;#Ge;#Ye=!1;#Ke;#Ze=0;constructor({sidebar:e,resizer:t,toggleButton:i},n,s,a){this._sidebar=e,this.#$e=n===s?-1:1,this.#Xe=t,this.#Ge=s;const r=window.getComputedStyle(e);this.#ze=this.#He=parseFloat(r.getPropertyValue("--sidebar-width")),t.ariaValueMin=parseFloat(r.getPropertyValue("--sidebar-min-width"))||0,t.ariaValueMax=parseFloat(r.getPropertyValue("--sidebar-max-width"))||1/0,t.ariaValueNow=this.#He,this.#qe(),i.addEventListener("click",this.toggle.bind(this)),this._isOpen=!1,e.hidden=!0,a?.addEventListener("abort",this.destroy.bind(this),{once:!0}),this.#Ke=new ResizeObserver(([{borderBoxSize:[{inlineSize:e}]}])=>{isNaN(this.#Ze)||(this.#Ze+=this.#$e*(e-this.#He)),this.#Qe(e)}),this.#Ke.observe(e)}#qe(){const e=this._sidebar.style;let t;const i=()=>{this.#We=null,this._sidebar.classList.remove("resizing"),t?.abort(),t=null,this.#Ye=!1,this.onStopResizing(),this.#Ze=NaN};this.#Xe.addEventListener("pointerdown",n=>{if(t)return void i();this.onStartResizing();const{clientX:s}=n;Ke(n),this.#Ze=s,t=new AbortController;const{signal:a}=t,r=this._sidebar;r.classList.add("resizing");r.parentElement.style.minWidth=0,window.addEventListener("contextmenu",ke,{signal:a}),window.addEventListener("pointermove",i=>{!t||Math.abs(i.clientX-this.#Ze)<1||(Ke(i),e.width=`${Math.round(this.#He+this.#$e*(i.clientX-this.#Ze))}px`)},{signal:a,capture:!0}),window.addEventListener("blur",i,{signal:a}),window.addEventListener("pointerup",e=>{t&&(i(),Ke(e))},{signal:a})}),this.#Xe.addEventListener("keydown",t=>{const{key:n}=t,s="ArrowLeft"===n;if(s||"ArrowRight"===n){this.#Ye||(this._sidebar.classList.add("resizing"),this.#Ye=!0,this.onStartResizing());const n=(t.ctrlKey||t.metaKey?10:1)*(s?-1:1);clearTimeout(this.#We),this.#We=setTimeout(i,400),e.width=`${Math.round(this.#He+this.#$e*n)}px`,Ke(t)}})}#Qe(e){this.#He=e,this.#Xe.ariaValueNow=Math.round(e),this.#Ge&&(this._sidebar.parentElement.style.insetInlineStart=`${(this.#ze-e).toFixed(3)}px`),this.onResizing(e)}get width(){return this.#He}set width(e){this._sidebar.style.width=`${e}px`}onStartResizing(){}onStopResizing(){}onResizing(e){}toggle(e=!this._isOpen){this._sidebar.hidden=!(this._isOpen=e)}destroy(){this.#Ke?.disconnect(),this.#Ke=null}}class Ui{#I;#Je;#et;static#tt=null;constructor(e,t,i,n,s,a,r,o){const l=new Intl.DateTimeFormat(void 0,{dateStyle:"long"});this.dialogElement=e.dialog,this.#I=new Hi(e,s,i,a),this.#Je=new $i(i,l,a,this.dialogElement),this.#et=new zi(t,i,n,this.#Je,l,a,o),this.#Je.sidebar=this.#et,Ui.#tt=r}setSidebarUiManager(e){this.#et.setUIManager(e)}showSidebar(e){this.#et.show(e)}hideSidebar(){this.#et.hide()}removeComments(e){this.#et.removeComments(e)}selectComment(e){this.#et.selectComment(null,e)}addComment(e){this.#et.addComment(e)}updateComment(e){this.#et.updateComment(e)}toggleCommentPopup(e,t,i,n){t&&this.selectComment(e.uid),this.#Je.toggle(e,t,i,n)}destroyPopup(){this.#Je.destroy()}updatePopupColor(e){this.#Je.updateColor(e)}showDialog(e,t,i,n,s){return this.#I.open(e,t,i,n,s)}makeCommentColor(e,t){return Ui._makeCommentColor(e,t)}static _makeCommentColor(e,t){return this.#tt?null:fe(oe(e,t??1),ce.commentForegroundColor)}destroy(){this.#I.destroy(),this.#et.hide(),this.#Je.destroy()}}class zi extends Fi{#it=null;#y;#nt=this.#st.bind(this);#at=this.#rt.bind(this);#ot;#lt;#dt;#ht;#ct;#ut;#gt;#Je;#pt=null;#mt=null;#G=null;constructor({learnMoreUrl:e,sidebar:t,sidebarResizer:i,commentsList:n,commentCount:s,sidebarTitle:a,closeButton:r,commentToolbarButton:o},l,d,h,c,u,g){super({sidebar:t,resizer:i,toggleButton:o},u,!0,g),this.#ct=a,this.#lt=n,this.#dt=s,this.#ut=e,this.#gt=d,this.#ot=r,this.#Je=h,this.#ht=c,this.#y=l,r.addEventListener("click",()=>{l.dispatch("switchannotationeditormode",{source:this,mode:ie.NONE})});const p=e=>{"ArrowDown"===e.key||"Home"===e.key||"F6"===e.key?(this.#lt.firstElementChild.focus(),Ke(e)):"ArrowUp"!==e.key&&"End"!==e.key||(this.#lt.lastElementChild.focus(),Ke(e))};o.addEventListener("keydown",p),t.addEventListener("keydown",p)}setUIManager(e){this.#G=e}show(e){if(this.#pt=new WeakMap,this.#mt=new Map,this.#it=e,e.sort(this.#ft.bind(this)),0!==e.length){const t=document.createDocumentFragment();for(const i of e)t.append(this.#bt(i));this.#vt(t),this.#lt.append(t)}else this.#vt();this._sidebar.hidden=!1,this.#y.dispatch("reporttelemetry",{source:this,details:{type:"commentSidebar",data:{numberOfAnnotations:e.length}}})}hide(){this._sidebar.hidden=!0,this.#lt.replaceChildren(),this.#pt=null,this.#mt=null,this.#it=null}removeComments(e){if(0!==e.length&&this.#mt)if(0!==new Set(this.#mt.keys()).difference(new Set(e)).size)for(const t of e)this.#wt(t);else this.#yt()}focusComment(e){const t=this.#mt.get(e);if(t){this._sidebar.scrollTop=t.offsetTop-this._sidebar.offsetTop;for(const e of this.#lt.children)e.classList.toggle("selected",e===t)}}updateComment(e){if(!this.#mt)return;const{id:t,creationDate:i,modificationDate:n,richText:s,contentsObj:a,popupRef:r}=e;r&&(s||a?.str)||this.#wt(t);const o=this.#mt.get(t);if(!o)return;const l=this.#pt.get(o);let d=S(this.#it,e=>this.#ft(e,l)>=0);d>=this.#it.length||(this.#Ct(o.firstElementChild,n||i),this.#Pt(o.lastElementChild,s,a),this.#it.splice(d,1),d=S(this.#it,t=>this.#ft(t,e)>=0),this.#it.splice(d,0,e),d>=this.#lt.children.length?this.#lt.append(o):this.#lt.insertBefore(o,this.#lt.children[d]))}#wt(e){const t=this.#mt?.get(e);if(!t)return;const i=this.#pt.get(t),n=S(this.#it,e=>this.#ft(e,i)>=0);n>=this.#it.length||(this.#it.splice(n,1),t.remove(),this.#mt.delete(e),this.#vt())}#yt(){this.#lt.replaceChildren(),this.#pt=new WeakMap,this.#mt.clear(),this.#it.length=0,this.#vt()}selectComment(e,t=null){if(!this.#mt)return;const i=!e;e||=this.#mt.get(t);for(const t of this.#lt.children)t.classList.toggle("selected",t===e);i&&e?.scrollIntoView({behavior:"instant",block:"center"})}addComment(e){if(this.#mt?.has(e.id))return;const{popupRef:t,contentsObj:i}=e;if(!t||!i?.str)return;const n=this.#bt(e);if(0===this.#it.length)return this.#lt.replaceChildren(n),this.#it.push(e),void this.#vt();const s=S(this.#it,t=>this.#ft(t,e)>=0);this.#it.splice(s,0,e),s>=this.#lt.children.length?this.#lt.append(n):this.#lt.insertBefore(n,this.#lt.children[s]),this.#vt()}#vt(e=this.#lt){const t=this.#mt.size;this.#ct.setAttribute("data-l10n-args",JSON.stringify({count:t})),this.#dt.textContent=t,0===t&&e.append(this.#St())}#St(){const e=document.createElement("li");e.classList.add("sidebarComment","noComments");const t=document.createElement("div");if(t.className="sidebarCommentText",t.setAttribute("data-l10n-id","pdfjs-editor-comments-sidebar-no-comments1"),e.append(t),this.#ut){const t=document.createElement("a");t.setAttribute("data-l10n-id","pdfjs-editor-comments-sidebar-no-comments-link"),t.href=this.#ut,t.target="_blank",t.rel="noopener noreferrer",e.append(t)}return e}#Ct(e,t){t=Ve.toDateObject(t),e.dateTime=t.toISOString(),e.textContent=this.#ht.format(t)}#Pt(e,t,i){e.replaceChildren();const n=!t?.str||i?.str&&t.str!==i.str?i?.str:t.html;$e({html:n,dir:i?.dir||"auto",className:"richText"},e)}#bt(e){const{id:t,creationDate:i,modificationDate:n,richText:s,contentsObj:a,color:r,opacity:o}=e,l=document.createElement("li");l.role="button",l.className="sidebarComment",l.tabIndex=-1,l.style.backgroundColor=r&&Ui._makeCommentColor(r,o)||"";const d=document.createElement("time");this.#Ct(d,n||i);const h=document.createElement("div");return h.className="sidebarCommentText",this.#Pt(h,s,a),l.append(d,h),l.addEventListener("click",this.#nt),l.addEventListener("keydown",this.#at),this.#pt.set(l,e),this.#mt.set(t,l),l}async#st({currentTarget:e}){if(e.classList.contains("selected"))return e.classList.remove("selected"),void this.#Je._hide();const t=this.#pt.get(e);if(!t)return;this.#Je._hide();const{id:i,pageIndex:n,rect:s}=t,a=n+1,r=this.#G?.waitForEditorsRendered(a);this.#gt?.goToXY(a,s[0],s[3],{center:"both"}),this.selectComment(e),await r,this.#G?.selectComment(n,i)}#rt(e){const{key:t,currentTarget:i}=e;switch(t){case"ArrowDown":(i.nextElementSibling||this.#lt.firstElementChild).focus(),Ke(e);break;case"ArrowUp":(i.previousElementSibling||this.#lt.lastElementChild).focus(),Ke(e);break;case"Home":this.#lt.firstElementChild.focus(),Ke(e);break;case"End":this.#lt.lastElementChild.focus(),Ke(e);break;case"Enter":case" ":this.#st(e),Ke(e);break;case"ShiftTab":this.#ot.focus(),Ke(e)}}#ft(e,t){const i=Ve.toDateObject(e.modificationDate||e.creationDate),n=Ve.toDateObject(t.modificationDate||t.creationDate);return i!==n?null!==i&&null!==n?n-i:null!==i?-1:1:e.pageIndex!==t.pageIndex?e.pageIndex-t.pageIndex:e.rect[3]!==t.rect[3]?t.rect[3]-e.rect[3]:e.rect[0]!==t.rect[0]?e.rect[0]-t.rect[0]:e.rect[1]!==t.rect[1]?t.rect[1]-e.rect[1]:e.rect[2]!==t.rect[2]?e.rect[2]-t.rect[2]:e.id.localeCompare(t.id)}}class Hi{#I;#Et;#$;#xt="";#Tt="";#Lt;#X;#we;#G;#_t=0;#Mt=0;#It=0;#At=0;#Bt;#y;constructor({dialog:e,toolbar:t,title:i,textInput:n,cancelButton:s,saveButton:a},r,o,l){this.#I=e,this.#Lt=n,this.#$=r,this.#y=o,this.#we=a,this.#X=i,this.#Bt=l;const d=this.#re.bind(this);let h;e.addEventListener("close",d),e.addEventListener("contextmenu",e=>{e.target!==this.#Lt&&e.preventDefault()}),s.addEventListener("click",d),a.addEventListener("click",this.#S.bind(this)),n.addEventListener("input",()=>{a.disabled=n.value===this.#xt}),n.addEventListener("keydown",e=>{!e.ctrlKey&&!e.metaKey||"Enter"!==e.key||a.disabled||this.#S()});const c=()=>{e.classList.remove("dragging"),h?.abort(),h=null};t.addEventListener("pointerdown",t=>{if(h)return void c();const{clientX:i,clientY:n}=t;Ke(t),this.#_t=i,this.#Mt=n,h=new AbortController;const{signal:s}=h,{innerHeight:a,innerWidth:r}=window;e.classList.add("dragging"),window.addEventListener("pointermove",e=>{if(!h)return;const{clientX:t,clientY:i}=e;this.#_e(this.#It+(t-this.#_t)/r,this.#At+(i-this.#Mt)/a),this.#_t=t,this.#Mt=i,Ke(e)},{signal:s}),window.addEventListener("blur",c,{signal:s}),window.addEventListener("pointerup",e=>{h&&(c(),Ke(e))},{signal:s})}),r.register(e)}async open(e,t,i,n,s){t&&(this.#G=e,this.#Et=t);const{contentsObj:{str:a},color:r,opacity:o}=t.getData(),{style:l}=this.#I;r?(l.backgroundColor=Ui._makeCommentColor(r,o),l.borderColor=tt.makeHexColor(...r)):l.backgroundColor=l.borderColor="",this.#Tt=a||"";const d=this.#Lt;d.value=this.#xt=this.#Tt,a?(this.#X.setAttribute("data-l10n-id","pdfjs-editor-edit-comment-dialog-title-when-editing"),this.#we.setAttribute("data-l10n-id","pdfjs-editor-edit-comment-dialog-save-button-when-editing")):(this.#X.setAttribute("data-l10n-id","pdfjs-editor-edit-comment-dialog-title-when-adding"),this.#we.setAttribute("data-l10n-id","pdfjs-editor-edit-comment-dialog-save-button-when-adding")),s?.height&&(d.style.height=`${s.height}px`),this.#G?.removeEditListeners(),this.#we.disabled=!0;const h=s?.parentDimensions,{innerHeight:c,innerWidth:u}=window;if(t.hasDefaultPopupPosition()){const{dialogWidth:e,dialogHeight:t}=this._dialogDimensions;if(h)if(this.#Bt&&i+e>Math.min(h.x+h.width,u)){i-=e-this.#Et.commentButtonWidth*h.width}else if(!this.#Bt){const t=this.#Et.commentButtonWidth*h.width;i-e<Math.max(0,h.x)?i=Math.max(0,i):i-=e-t}const a=Math.max(t,s?.height||0);n+a>c&&(n=c-a),n<0&&(n=0)}i=Be(i/u,0,1),n=Be(n/c,0,1),this.#_e(i,n),await this.#$.open(this.#I),d.focus()}async#S(){this.#Et.comment=this.#Lt.value,this.#re()}get _dialogDimensions(){const e=this.#I,{style:t}=e;t.opacity="0",t.display="block";const{width:i,height:n}=e.getBoundingClientRect();return t.opacity=t.display="",Ge(this,"_dialogDimensions",{dialogWidth:i,dialogHeight:n})}#_e(e,t){this.#It=e,this.#At=t;const{style:i}=this.#I;i.left=100*e+"%",i.top=100*t+"%"}#re(){if(!this.#Et)return;const e=this.#Lt.value!==this.#Tt;this.#y.dispatch("reporttelemetry",{source:this,details:{type:"comment",data:{edited:e}}}),this.#Et?.focusCommentButton(),this.#Et=null,this.#Lt.value=this.#xt=this.#Tt="",this.#$.closeIfActive(this.#I),this.#Lt.style.height="",this.#G?.addEditListeners(),this.#G=null}destroy(){this.#G=null,this.#Et=null,this.#re()}}class $i{#kt=null;#y;#Dt;#ht;#Et=null;#Bt;#Se=null;#Nt=null;#Ot=null;#_t=0;#Mt=0;#Rt=0;#jt=0;#Vt=null;#Ft=!1;#s=!1;constructor(e,t,i,n){this.#y=e,this.#ht=t,this.#Bt=i,this.#Dt=n,this.sidebar=null}get _popupWidth(){const e=this.#Ut(),{style:t}=e;t.opacity="0",t.display="block",document.body.append(e);const i=e.getBoundingClientRect().width;return e.remove(),t.opacity=t.display="",Ge(this,"_popupWidth",i)}#Ut(){if(this.#Se)return this.#Se;const e=this.#Se=document.createElement("div");e.className="commentPopup",e.id="commentPopup",e.tabIndex=-1,e.role="dialog",e.ariaModal="false",e.addEventListener("contextmenu",ke),e.addEventListener("keydown",e=>{"Escape"===e.key&&(this.toggle(this.#Et,!0,!1),this.#Vt?.focus(),Ke(e))}),e.addEventListener("click",()=>{e.focus()});const t=document.createElement("div");t.className="commentPopupTop";const i=this.#Ot=document.createElement("time");i.className="commentPopupTime";const n=this.#kt=document.createElement("div");n.className="commentPopupButtons";const s=document.createElement("button");s.classList.add("commentPopupEdit","toolbarButton"),s.tabIndex=0,s.setAttribute("data-l10n-id","pdfjs-editor-edit-comment-popup-button"),s.ariaHasPopup="dialog",s.ariaControlsElements=[this.#Dt];const a=document.createElement("span");a.setAttribute("data-l10n-id","pdfjs-editor-edit-comment-popup-button-label"),s.append(a),s.addEventListener("click",()=>{const e=this.#Et,t=parseFloat(getComputedStyle(this.#Nt).height);this.toggle(e,!0,!1),e.editComment({height:t})}),s.addEventListener("contextmenu",ke);const r=document.createElement("button");r.classList.add("commentPopupDelete","toolbarButton"),r.tabIndex=0,r.setAttribute("data-l10n-id","pdfjs-editor-delete-comment-popup-button");const o=document.createElement("span");o.setAttribute("data-l10n-id","pdfjs-editor-delete-comment-popup-button-label"),r.append(o),r.addEventListener("click",()=>{this.#y.dispatch("reporttelemetry",{source:this,details:{type:"comment",data:{deleted:!0}}});const e=this.#Et,t=e.comment;this.destroy(),t?.text?e._uiManager.deleteComment(e,t):e.comment=null,e.focus()}),r.addEventListener("contextmenu",ke),n.append(s,r),t.append(i,n);const l=document.createElement("hr"),d=this.#Nt=document.createElement("div");let h;d.className="commentPopupText",e.append(t,l,d);const c=()=>{e.classList.remove("dragging"),h?.abort(),h=null};return t.addEventListener("pointerdown",t=>{if(h)return void c();const{target:i,clientX:s,clientY:a}=t;if(n.contains(i))return;Ke(t);const{width:r,height:o}=this.#Et.parentBoundingClientRect;this.#_t=s,this.#Mt=a,h=new AbortController;const{signal:l}=h;e.classList.add("dragging"),window.addEventListener("pointermove",e=>{if(!h)return;const{clientX:t,clientY:i}=e;this.#_e(this.#Rt+(t-this.#_t)/r,this.#jt+(i-this.#Mt)/o,!1),this.#_t=t,this.#Mt=i,Ke(e)},{signal:l}),window.addEventListener("blur",c,{signal:l}),window.addEventListener("pointerup",e=>{h&&(c(),Ke(e))},{signal:l})}),e}updateColor(e){if(this.#Et!==e||!this.#s)return;const{color:t,opacity:i}=e.getData();this.#Se.style.backgroundColor=t&&Ui._makeCommentColor(t,i)||""}_hide(e){const t=this.#Ut();t.classList.toggle("hidden",!0),t.classList.toggle("selected",!1),(e||this.#Et)?.setCommentButtonStates({selected:!1,hasPopup:!1}),this.#Et=null,this.#Ft=!1,this.#s=!1,this.#Nt.replaceChildren(),this.sidebar.selectComment(null)}toggle(e,t,i=void 0,n=!0){if(!e)return void this.destroy();if(t)i??=this.#Et!==e||(!this.#Ft||!this.#s);else{if(this.#Ft)return;i??=!this.#s}if(!i)return void this._hide(e);this.#s=!0,this.#Et!==e&&this.#Et?.setCommentButtonStates({selected:!1,hasPopup:!1});const s=this.#Ut();this.#kt.classList.toggle("hidden",!n),s.classList.toggle("hidden",!1),s.classList.toggle("selected",t),this.#Ft=t,this.#Et=e,e.setCommentButtonStates({selected:t,hasPopup:!0});const{contentsObj:a,richText:r,creationDate:o,modificationDate:l,color:d,opacity:h}=e.getData();s.style.backgroundColor=d&&Ui._makeCommentColor(d,h)||"",this.#Nt.replaceChildren();const c=!r?.str||a?.str&&r.str!==a.str?a?.str:r.html;c&&$e({html:c,dir:a?.dir||"auto",className:"richText"},this.#Nt),this.#Ot.textContent=this.#ht.format(Ve.toDateObject(l||o)),this.#_e(...e.commentPopupPosition,e.hasDefaultPopupPosition()),e.elementBeforePopup.after(s),s.addEventListener("focus",({relatedTarget:e})=>{this.#Vt=e},{once:!0}),t&&setTimeout(()=>s.focus(),0)}#_e(e,t,i){if(i){const t=this.#Et.parentBoundingClientRect,i=this._popupWidth/t.width;if(this.#Bt&&e+i>1||!this.#Bt&&e-i>=0){e-=i-this.#Et.commentButtonWidth}const n=.01;e=this.#Bt?Math.max(e,-t.x/t.width+n):Math.min(e,(window.innerWidth-t.x)/t.width-i-n)}else this.#Et.commentPopupPosition=[e,t];this.#Rt=e,this.#jt=t;const{style:n}=this.#Se;n.left=100*e+"%",n.top=100*t+"%"}destroy(){this._hide(),this.#Se?.remove(),this.#Se=this.#Nt=this.#Ot=null,this.#_t=this.#Mt=1/0,this.#Rt=this.#jt=0,this.#Vt=null}}class Wi{#zt=new WeakMap;_triggerDownload(e,t,i,n=!1){throw new Error("Not implemented: _triggerDownload")}_getOpenDataUrl(e,t,i=null){throw new Error("Not implemented: _getOpenDataUrl")}downloadData(e,t,i){const n=URL.createObjectURL(new Blob([e],{type:i}));this._triggerDownload(n,n,t,!0)}openOrDownloadData(e,t,i=null){const n=Le(t),s=n?"application/pdf":"";if(n){const n=this.#zt.getOrInsertComputed(e,()=>URL.createObjectURL(new Blob([e],{type:s})));try{const e=this._getOpenDataUrl(n,t,i);return window.open(e),!0}catch(t){console.error("openOrDownloadData:",t),URL.revokeObjectURL(n),this.#zt.delete(e)}}return this.downloadData(e,t,s),!1}download(e,t,i){const n=e?URL.createObjectURL(new Blob([e],{type:"application/pdf"})):null;this._triggerDownload(n,t,i)}}class Xi extends Wi{_triggerDownload(e,t,i,n=!1){if(!e&&!n){if(!he(t,"http://example.com"))throw new Error(`_triggerDownload - not a valid URL: ${t}`);e=t+"#pdfjs.action=download"}const s=document.createElement("a");s.href=e,s.target="_parent","download"in s&&(s.download=i),(document.body||document.documentElement).append(s),s.click(),s.remove()}_getOpenDataUrl(e,t,i=null){let n="?file="+encodeURIComponent(e+"#"+t);return i&&(n+=`#${escape(i)}`),n}}class Gi{#ot=null;#Se;#y=null;#Ht=null;#$t=null;isOpen=!1;#Wt;#Xt=null;#Gt;static#Yt=Object.freeze({highlight:"pdfjs-editor-undo-bar-message-highlight",freetext:"pdfjs-editor-undo-bar-message-freetext",stamp:"pdfjs-editor-undo-bar-message-stamp",ink:"pdfjs-editor-undo-bar-message-ink",signature:"pdfjs-editor-undo-bar-message-signature",comment:"pdfjs-editor-undo-bar-message-comment",_multiple:"pdfjs-editor-undo-bar-message-multiple"});constructor({container:e,message:t,undoButton:i,closeButton:n},s){this.#Se=e,this.#Wt=t,this.#Gt=i,this.#ot=n,this.#y=s}destroy(){this.#$t?.abort(),this.#$t=null,this.hide()}show(e,t){if(!this.#$t){this.#$t=new AbortController;const e={signal:this.#$t.signal},t={signal:this.#$t.signal,...Q},i=this.hide.bind(this);this.#Se.addEventListener("contextmenu",ke,e),this.#ot.addEventListener("click",i,e),this.#y.on("beforeprint",i,t),this.#y.on("download",i,t)}this.hide(),"string"==typeof t?this.#Wt.setAttribute("data-l10n-id",Gi.#Yt[t]):(this.#Wt.setAttribute("data-l10n-id",Gi.#Yt._multiple),this.#Wt.setAttribute("data-l10n-args",JSON.stringify({count:t}))),this.isOpen=!0,this.#Se.hidden=!1,this.#Xt=new AbortController,this.#Gt.addEventListener("click",()=>{e(),this.hide()},{signal:this.#Xt.signal}),this.#Ht=setTimeout(()=>{this.#Se.contains(document.activeElement)||this.#Se.focus(),this.#Ht=null},100)}hide(){this.isOpen&&(this.isOpen=!1,this.#Se.hidden=!0,this.#Xt?.abort(),this.#Xt=null,this.#Ht&&(clearTimeout(this.#Ht),this.#Ht=null))}}class Yi{#Kt=new WeakMap;#Zt=null;get active(){return this.#Zt}async register(e,t=!1){if("object"!=typeof e)throw new Error("Not enough parameters.");if(this.#Kt.has(e))throw new Error("The overlay is already registered.");this.#Kt.set(e,{canForceClose:t}),e.addEventListener("cancel",({target:e})=>{this.#Zt===e&&(this.#Zt=null)})}async open(e){if(!this.#Kt.has(e))throw new Error("The overlay does not exist.");if(this.#Zt){if(this.#Zt===e)throw new Error("The overlay is already active.");if(!this.#Kt.get(e).canForceClose)throw new Error("Another overlay is currently active.");await this.close()}this.#Zt=e,e.showModal()}async close(e=this.#Zt){if(!this.#Kt.has(e))throw new Error("The overlay does not exist.");if(!this.#Zt)throw new Error("The overlay is currently not active.");if(this.#Zt!==e)throw new Error("Another overlay is currently active.");e.close(),this.#Zt=null}async closeIfActive(e){this.#Zt===e&&await this.close(e)}}class Ki{#qt=null;#Qt=null;#Jt=null;constructor(e,t,i=!1){this.dialog=e.dialog,this.label=e.label,this.input=e.input,this.submitButton=e.submitButton,this.cancelButton=e.cancelButton,this.overlayManager=t,this._isViewerEmbedded=i,this.submitButton.addEventListener("click",this.#ei.bind(this)),this.cancelButton.addEventListener("click",this.close.bind(this)),this.input.addEventListener("keydown",e=>{13===e.keyCode&&this.#ei()}),this.overlayManager.register(this.dialog,!0),this.dialog.addEventListener("close",this.#x.bind(this))}async open(){await(this.#qt?.promise),this.#qt=Promise.withResolvers();try{await this.overlayManager.open(this.dialog)}catch(e){throw this.#qt.resolve(),e}const e=this.#Jt===Re.INCORRECT_PASSWORD;this._isViewerEmbedded&&!e||this.input.focus(),this.label.setAttribute("data-l10n-id",e?"pdfjs-password-invalid":"pdfjs-password-label")}async close(){this.overlayManager.closeIfActive(this.dialog)}#ei(){const e=this.input.value;e?.length>0&&this.#ti(e)}#x(){this.#ti(new Error("PasswordPrompt cancelled.")),this.#qt.resolve()}#ti(e){this.#Qt&&(this.close(),this.input.value="",this.#Qt(e),this.#Qt=null)}async setUpdateCallback(e,t){this.#qt&&await this.#qt.promise,this.#Qt=e,this.#Jt=t}}const Zi="selected";class qi{constructor(e){this.container=e.container,this.eventBus=e.eventBus,this._l10n=e.l10n,this.reset()}reset(){this._pdfDocument=null,this._lastToggleIsShow=!0,this._currentTreeItem=null,this.container.replaceChildren(),this.container.classList.remove("withNesting")}_dispatchEvent(e){throw new Error("Not implemented: _dispatchEvent")}_bindLink(e,t){throw new Error("Not implemented: _bindLink")}_normalizeTextContent(e){return P(e,!0)||"–"}_addToggleButton(e,t=!1){const i=document.createElement("div");i.className="treeItemToggler",t&&i.classList.add("treeItemsHidden"),e.prepend(i)}_toggleTreeItem(e,t=!1){this._l10n.pause(),this._lastToggleIsShow=t;for(const i of e.querySelectorAll(".treeItemToggler"))i.classList.toggle("treeItemsHidden",!t);this._l10n.resume()}_toggleAllTreeItems(){this._toggleTreeItem(this.container,!this._lastToggleIsShow)}_finishRendering(e,t,i=!1){i&&(this.container.classList.add("withNesting"),this._lastToggleIsShow=!e.querySelector(".treeItemsHidden"),this.container.addEventListener("click",e=>{const{target:t}=e;if(t.classList.contains("treeItemToggler")&&(Ke(e),t.classList.toggle("treeItemsHidden"),e.shiftKey)){const e=!t.classList.contains("treeItemsHidden");this._toggleTreeItem(t.parentNode,e)}})),this._l10n.pause(),this.container.append(e),this._l10n.resume(),this._dispatchEvent(t)}render(e){throw new Error("Not implemented: render")}_updateCurrentTreeItem(e=null){this._currentTreeItem&&(this._currentTreeItem.classList.remove(Zi),this._currentTreeItem=null),e&&(e.classList.add(Zi),this._currentTreeItem=e)}_scrollToCurrentTreeItem(e){if(!e)return;this._l10n.pause();let t=e.parentNode;for(;t&&t!==this.container;){if(t.classList.contains("treeItem")){const e=t.firstElementChild;e?.classList.remove("treeItemsHidden")}t=t.parentNode}this._l10n.resume(),this._updateCurrentTreeItem(e),e.scrollIntoView({behavior:"instant",block:"center",inline:"center",container:"nearest"})}}class Qi extends qi{constructor(e){super(e),this.downloadManager=e.downloadManager,this.eventBus.on("fileattachmentannotation",this.#ii.bind(this),Q)}reset(e=!1){super.reset(),this._attachments=null,e||(this._renderedCapability=Promise.withResolvers()),this._pendingDispatchEvent=!1}async _dispatchEvent(e){this._renderedCapability.resolve(),(0!==e||this._pendingDispatchEvent||(this._pendingDispatchEvent=!0,await ht({target:this.eventBus,name:"annotationlayerrendered",delay:1e3}),this._pendingDispatchEvent))&&(this._pendingDispatchEvent=!1,this.eventBus.dispatch("attachmentsloaded",{source:this,attachmentsCount:e}))}_bindLink(e,{content:t,description:i,filename:n}){i&&(e.title=i),e.onclick=()=>(this.downloadManager.openOrDownloadData(t,n),!1)}render({attachments:e,keepRenderedCapability:t=!1}){if(this._attachments&&this.reset(t),this._attachments=e||null,!e)return void this._dispatchEvent(0);const i=document.createDocumentFragment(),n=document.createElement("ul");i.append(n);let s=0;for(const t in e){const i=e[t],a=document.createElement("li");n.append(a);const r=document.createElement("a");a.append(r),this._bindLink(r,i),r.textContent=this._normalizeTextContent(i.filename),s++}this._finishRendering(i,s)}#ii(e){const t=this._renderedCapability.promise;t.then(()=>{if(t!==this._renderedCapability.promise)return;const i=this._attachments||Object.create(null);for(const t in i)if(e.filename===t)return;i[e.filename]=e,this.render({attachments:i,keepRenderedCapability:!0})})}}const Ji="grab-to-pan-grab";class en{#ni=null;#si=null;#ai=null;constructor({element:e}){this.element=e,this.document=e.ownerDocument;(this.overlay=document.createElement("div")).className="grab-to-pan-grabbing"}activate(){this.#ni||(this.#ni=new AbortController,this.element.addEventListener("mousedown",this.#ri.bind(this),{capture:!0,signal:this.#ni.signal}),this.element.classList.add(Ji))}deactivate(){this.#ni&&(this.#ni.abort(),this.#ni=null,this.#oi(),this.element.classList.remove(Ji))}toggle(){this.#ni?this.deactivate():this.activate()}ignoreTarget(e){return e.matches("a[href], a[href] *, input, textarea, button, button *, select, option")}#ri(e){if(0!==e.button||this.ignoreTarget(e.target))return;if(e.originalTarget)try{e.originalTarget.tagName}catch{return}this.scrollLeftStart=this.element.scrollLeft,this.scrollTopStart=this.element.scrollTop,this.clientXStart=e.clientX,this.clientYStart=e.clientY,this.#si=new AbortController;const t=this.#oi.bind(this),i={capture:!0,signal:this.#si.signal};this.document.addEventListener("mousemove",this.#li.bind(this),i),this.document.addEventListener("mouseup",t,i),this.#ai=new AbortController,this.element.addEventListener("scroll",t,{capture:!0,signal:this.#ai.signal}),Ke(e);const n=document.activeElement;n&&!n.contains(e.target)&&n.blur()}#li(e){if(this.#ai?.abort(),this.#ai=null,!(1&e.buttons))return void this.#oi();const t=e.clientX-this.clientXStart,i=e.clientY-this.clientYStart;this.element.scrollTo({top:this.scrollTopStart-i,left:this.scrollLeftStart-t,behavior:"instant"}),this.overlay.parentNode||document.body.append(this.overlay)}#oi(){this.#si?.abort(),this.#si=null,this.#ai?.abort(),this.#ai=null,this.overlay.remove()}}class tn{#Zt=f;#di=null;constructor({container:e,eventBus:t,cursorToolOnLoad:i=f}){this.container=e,this.eventBus=t,this.#hi(),Promise.resolve().then(()=>{this.switchTool(i)})}get activeTool(){return this.#Zt}switchTool(e){null===this.#di&&this.#ci(e)}#ci(e,t=!1){if(e===this.#Zt)return void(null!==this.#di&&this.eventBus.dispatch("cursortoolchanged",{source:this,tool:e,disabled:t}));const i=()=>{switch(this.#Zt){case f:break;case b:this._handTool.deactivate()}};switch(e){case f:i();break;case b:i(),this._handTool.activate();break;default:return void console.error(`switchTool: "${e}" is an unsupported value.`)}this.#Zt=e,this.eventBus.dispatch("cursortoolchanged",{source:this,tool:e,disabled:t})}#hi(){const{eventBus:e}=this;e.on("switchcursortool",e=>{e.reset?null!==this.#di&&(t=ie.NONE,n=i,r()):this.switchTool(e.tool)},Q);let t=ie.NONE,n=i;const a=()=>{this.#di??=this.#Zt,this.#ci(f,!0)},r=()=>{null!==this.#di&&t===ie.NONE&&n===i&&(this.#ci(this.#di),this.#di=null)};e.on("annotationeditormodechanged",({mode:e})=>{t=e,e===ie.NONE?r():a()},Q),e.on("presentationmodechanged",({state:e})=>{n=e,e===i?r():e===s&&a()},Q)}get _handTool(){return Ge(this,"_handTool",new en({element:this.container}))}}const nn=["en-us","en-lr","my"],sn={"8.5x11":"pdfjs-document-properties-page-size-name-letter","8.5x14":"pdfjs-document-properties-page-size-name-legal"},an={"297x420":"pdfjs-document-properties-page-size-name-a-three","210x297":"pdfjs-document-properties-page-size-name-a-four"};function rn(e,t,i){return i[`${t?e.width:e.height}x${t?e.height:e.width}`]}class on{#ui=null;constructor({dialog:e,fields:t,closeButton:i},n,s,a,r,o){this.dialog=e,this.fields=t,this.overlayManager=n,this.l10n=a,this._fileNameLookup=r,this._titleLookup=o,this.#gi(),i.addEventListener("click",this.close.bind(this)),this.overlayManager.register(this.dialog),s.on("pagechanging",e=>{this._currentPageNumber=e.pageNumber},Q),s.on("rotationchanging",e=>{this._pagesRotation=e.pagesRotation},Q)}async open(){await Promise.all([this.overlayManager.open(this.dialog),this._dataAvailableCapability.promise]);const e=this._currentPageNumber,t=this._pagesRotation;if(this.#ui&&e===this.#ui._currentPageNumber&&t===this.#ui._pagesRotation)return void this.#pi();const[{info:i,metadata:n,contentLength:s},a]=await Promise.all([this.pdfDocument.getMetadata(),this.pdfDocument.getPage(e).catch(t=>(console.error(`PDFDocumentProperties - unable to get page ${e}.`,t),null))]),[r,o,l,d,h,c,u]=await Promise.all([this._fileNameLookup(),this.#mi(s),this._titleLookup(),this.#fi(n?.get("xmp:createdate"),i.CreationDate),this.#fi(n?.get("xmp:modifydate"),i.ModDate),this.#bi(a,t),this.#vi(i.IsLinearized)]);this.#ui=Object.freeze({fileName:r,fileSize:o,title:l,author:n?.get("dc:creator")?.join("\n")||i.Author,subject:n?.get("dc:subject")?.join("\n")||i.Subject,keywords:n?.get("pdf:keywords")||i.Keywords,creationDate:d,modificationDate:h,creator:n?.get("xmp:creatortool")||i.Creator,producer:n?.get("pdf:producer")||i.Producer,version:i.PDFFormatVersion,pageCount:this.pdfDocument.numPages,pageSize:c,linearized:u,_currentPageNumber:e,_pagesRotation:t}),this.#pi();const{length:g}=await this.pdfDocument.getDownloadInfo();if(s===g)return;const p=Object.assign(Object.create(null),this.#ui);p.fileSize=await this.#mi(g),this.#ui=Object.freeze(p),this.#pi()}async close(){this.overlayManager.close(this.dialog)}setDocument(e){this.pdfDocument&&(this.#gi(),this.#pi()),e&&(this.pdfDocument=e,this._dataAvailableCapability.resolve())}#gi(){this.pdfDocument=null,this.#ui=null,this._dataAvailableCapability=Promise.withResolvers(),this._currentPageNumber=1,this._pagesRotation=0}#pi(){if(!this.#ui||this.overlayManager.active===this.dialog)for(const e in this.fields){const t=this.#ui?.[e];this.fields[e].textContent=t||0===t?t:"-"}}async#mi(e=0){const t=e/1024,i=t/1024;return t?this.l10n.get(i>=1?"pdfjs-document-properties-size-mb":"pdfjs-document-properties-size-kb",{mb:i,kb:t,b:e}):void 0}async#bi(e,t){if(!e)return;let i=function({view:e,userUnit:t,rotate:i}){const[n,s,a,r]=e,o=i%180!=0,l=(a-n)/72*t,d=(r-s)/72*t;return{width:o?d:l,height:o?l:d}}(e);t%180!=0&&(i={width:i.height,height:i.width});const n=A(i),s=nn.includes(this.l10n.getLanguage());let a={width:Math.round(100*i.width)/100,height:Math.round(100*i.height)/100},r={width:Math.round(25.4*i.width*10)/10,height:Math.round(25.4*i.height*10)/10},o=rn(a,n,sn)||rn(r,n,an);if(!(o||Number.isInteger(r.width)&&Number.isInteger(r.height))){const e={width:25.4*i.width,height:25.4*i.height},t={width:Math.round(r.width),height:Math.round(r.height)};Math.abs(e.width-t.width)<.1&&Math.abs(e.height-t.height)<.1&&(o=rn(t,n,an),o&&(a={width:Math.round(t.width/25.4*100)/100,height:Math.round(t.height/25.4*100)/100},r=t))}const[{width:l,height:d},h,c,u]=await Promise.all([s?a:r,this.l10n.get(s?"pdfjs-document-properties-page-size-unit-inches":"pdfjs-document-properties-page-size-unit-millimeters"),o&&this.l10n.get(o),this.l10n.get(n?"pdfjs-document-properties-page-size-orientation-portrait":"pdfjs-document-properties-page-size-orientation-landscape")]);return this.l10n.get(c?"pdfjs-document-properties-page-size-dimension-name-string":"pdfjs-document-properties-page-size-dimension-string",{width:l,height:d,unit:h,name:c,orientation:u})}async#fi(e,t){const i=Date.parse(e)||Ve.toDateObject(t);return i?this.l10n.get("pdfjs-document-properties-date-time-string",{dateObj:i.valueOf()}):void 0}#vi(e){return this.l10n.get(e?"pdfjs-document-properties-linearized-yes":"pdfjs-document-properties-linearized-no")}}const ln=0,dn=1,hn=2,cn=3,un=4,gn=5,pn=6,mn=7;function fn(e){return function(e){return e<11904}(e)?function(e){return!(65408&e)}(e)?function(e){return 32===e||9===e||13===e||10===e}(e)?ln:function(e){return e>=97&&e<=122||e>=65&&e<=90}(e)||function(e){return e>=48&&e<=57}(e)||95===e?dn:hn:function(e){return 3584==(65408&e)}(e)?mn:160===e?ln:dn:function(e){return e>=13312&&e<=40959||e>=63744&&e<=64255}(e)?cn:function(e){return e>=12448&&e<=12543}(e)?un:function(e){return e>=12352&&e<=12447}(e)?gn:function(e){return e>=65376&&e<=65439}(e)?pn:dn}let bn;const vn=0,wn=1,yn=2,Cn=3,Pn={"‐":"-","‘":"'","’":"'","‚":"'","‛":"'","“":'"',"”":'"',"„":'"',"‟":'"',"¼":"1/4","½":"1/2","¾":"3/4"},Sn=new Set([12441,12442,2381,2509,2637,2765,2893,3021,3149,3277,3387,3388,3405,3530,3642,3770,3972,4153,4154,5908,5940,6098,6752,6980,7082,7083,7154,7155,11647,43014,43052,43204,43347,43456,43766,44013,3158,3953,3954,3962,3963,3964,3965,3968,3956]);let En;const xn=/\p{M}+/gu,Tn=/([+^$|])|(\p{P}+)|(\s+)|(\p{M})|(\p{L})/gu,Ln=/(\P{M})\p{M}*$/u,_n=/^\p{M}*(\P{M})/u,Mn=/[\uAC00-\uD7AF\uFA6C\uFACF-\uFAD1\uFAD5-\uFAD7]+/g,In=new Map,An=new Map;let Bn=null,kn=null;function Dn(e,t={}){const i=[];let n;for(;null!==(n=Mn.exec(e));){let{index:e}=n;for(const t of n[0]){let n=In.get(t);n||(n=t.normalize("NFD").length,In.set(t,n)),i.push([n,e++])}}const s=i.length>0,a=t.ignoreDashEOL??!1;let r;if(!s&&Bn)r=Bn;else if(s&&kn)r=kn;else{const e=Object.keys(Pn).join(""),t=function(){if(!bn){const e=[],t=[],i=/^\p{M}$/u;for(let n=0;n<65536;n++){if(n>=55296&&n<=57343)continue;const s=String.fromCharCode(n);if(s.normalize("NFKC")!==s&&!i.test(s)){if(2!==t.length){t[0]=t[1]=n;continue}t[1]+1!==n?(t[0]===t[1]?e.push(String.fromCharCode(t[0])):e.push(`${String.fromCharCode(t[0])}-${String.fromCharCode(t[1])}`),t[0]=t[1]=n):t[1]=n}}const n=e.join("");if(bn){if(n!==bn){for(let e=1;e<n.length;e++)if(n[e]!==bn[e]){console.log(`Difference at index ${e}: U+${n.charCodeAt(e).toString(16).toUpperCase().padStart(4,"0")}!== U+${bn.charCodeAt(e).toString(16).toUpperCase().padStart(4,"0")}`);break}throw new Error("getNormalizeWithNFKC - update the `NormalizeWithNFKC` string.")}}else bn=n}return bn}();r=new RegExp([`[${e}]`,`[${t}]`,`${"(?:゙|゚)"}\\n`,"\\p{M}+(?:-\\n)?",`${"\\p{Ll}-\\n(?=\\p{Ll})|\\p{Lu}-\\n(?=\\p{L})"}`,"\\S-\\n",`${"(?:\\p{Ideographic}|[぀-ヿ])"}\\n`,"\\n",s?"[\\u1100-\\u1112\\ud7a4-\\ud7af\\ud84a\\ud84c\\ud850\\ud854\\ud857\\ud85f]":"\\u0000"].map(e=>`(${e})`).join("|"),"gmu"),s?kn=r:Bn=r}const o=[];for(;null!==(n=xn.exec(e));)o.push([n[0].length,n.index]);let l=e.normalize("NFD");const d=[0,0];let h=0,c=0,u=0,g=0,p=0,m=!1;l=l.replace(r,(e,t,n,s,r,l,f,b,v,w,y)=>{if(y-=g,t){const e=Pn[t],i=e.length;for(let e=1;e<i;e++)d.push(y-u+e,u-e);return u-=i-1,e}if(n){let e=An.get(n);e||(e=n.normalize("NFKC"),An.set(n,e));const t=e.length;for(let e=1;e<t;e++)d.push(y-u+e,u-e);return u-=t-1,e}if(s)return m=!0,y+p===o[h]?.[1]?++h:(d.push(y-1-u+1,u-1),u-=1,g+=1),d.push(y-u+1,u),g+=1,p+=1,s.charAt(0);if(r){const e=r.endsWith("\n"),t=e?r.length-2:r.length;m=!0;let i=t;y+p===o[h]?.[1]&&(i-=o[h][0],++h);for(let e=1;e<=i;e++)d.push(y-1-u+e,u-e);return u-=i,g+=i,e?(y+=t-1,d.push(y-u+1,1+u),u+=1,g+=1,p+=1,r.slice(0,t)):r}if(l){if(a)return g+=1,p+=1,l.slice(0,-1);const e=l.length-2;return d.push(y-u+e,1+u),u+=1,g+=1,p+=1,l.slice(0,-2)}if(f)return g+=1,p+=1,f.slice(0,-1);if(b){const e=b.length-1;return d.push(y-u+e,u),g+=1,p+=1,b.slice(0,-1)}if(v)return d.push(y-u+1,u-1),u-=1,g+=1,p+=1," ";if(y+p===i[c]?.[1]){const e=i[c][0]-1;++c;for(let t=1;t<=e;t++)d.push(y-(u-t),u-t);u-=e,g+=e}return w}),d.push(l.length,u);const f=new Uint32Array(d.length>>1),b=new Int32Array(d.length>>1);for(let e=0,t=d.length;e<t;e+=2)f[e>>1]=d[e],b[e>>1]=d[e+1];return[l,[f,b],m]}function Nn(e,t,i){if(!e)return[t,i];const[n,s]=e,a=t,r=t+i-1;let o=S(n,e=>e>=a);n[o]>a&&--o;let l=S(n,e=>e>=r,o);n[l]>r&&--l;const d=a+s[o];return[d,r+s[l]+1-d]}class On{#wi=null;#yi=!0;#Ci=0;#Pi=0;#Si=null;#Ei=null;constructor({linkService:e,eventBus:t,delay:i=250,updateMatchesCountOnProgress:n=!0}){this._linkService=e,this._eventBus=t,this.#yi=n,this.#Ci=i,this.onIsPageVisible=null,this.#gi(),t.on("find",this.#xi.bind(this),Q),t.on("findbarclose",this.#Ti.bind(this),Q),t.on("pagesedited",this.#Li.bind(this),Q)}get highlightMatches(){return this._highlightMatches}get pageMatches(){return this._pageMatches}get pageMatchesLength(){return this._pageMatchesLength}get selected(){return this._selected}get state(){return this.#wi}setDocument(e){this._pdfDocument&&this.#gi(),e&&(this._pdfDocument=e,this._firstPageCapability.resolve())}#xi(e){if(!e)return;const t=this._pdfDocument,{type:i}=e;(null===this.#wi||this.#_i(e))&&(this._dirtyMatch=!0),this.#wi=e,"highlightallchange"!==i&&this.#xe(Cn),this._firstPageCapability.promise.then(()=>{if(!this._pdfDocument||t&&this._pdfDocument!==t)return;this.#Mi();const e=!this._highlightMatches,n=!!this._findTimeout;this._findTimeout&&(clearTimeout(this._findTimeout),this._findTimeout=null),i?this._dirtyMatch?this.#Ii():"again"===i?(this.#Ii(),e&&this.#wi.highlightAll&&this.#Ai()):"highlightallchange"===i?(n?this.#Ii():this._highlightMatches=!0,this.#Ai()):this.#Ii():this._findTimeout=setTimeout(()=>{this.#Ii(),this._findTimeout=null},this.#Ci)})}scrollMatchIntoView({element:e=null,pageIndex:t=-1,matchIndex:i=-1}){this._scrollMatches&&e&&-1!==i&&i===this._selected.matchIdx&&-1!==t&&t===this._selected.pageIdx&&(this._scrollMatches=!1,e.scrollIntoView({block:"start",inline:"center"}))}#gi(){this._highlightMatches=!1,this._scrollMatches=!1,this._pdfDocument=null,this._pageMatches=[],this._pageMatchesLength=[],this.#Pi=0,this.#wi=null,this._selected={pageIdx:-1,matchIdx:-1},this._offset={pageIdx:null,matchIdx:null,wrapped:!1},this._extractTextPromises=[],this._pageContents=[],this._pageDiffs=[],this._hasDiacritics=[],this._matchesCountTotal=0,this._pagesToSearch=null,this._pendingFindMatches=new Set,this._resumePageIdx=null,this._dirtyMatch=!1,clearTimeout(this._findTimeout),this._findTimeout=null,this.#Si=null,this._firstPageCapability=Promise.withResolvers()}get#Bi(){const{query:e}=this.#wi;return"string"==typeof e?(e!==this._rawQuery&&(this._rawQuery=e,[this._normalizedQuery]=Dn(e)),this._normalizedQuery):(e||[]).filter(e=>!!e).map(e=>Dn(e)[0])}#_i(e){const t=e.query,i=this.#wi.query,n=typeof t;if(n!==typeof i)return!0;if("string"===n){if(t!==i)return!0}else if(JSON.stringify(t)!==JSON.stringify(i))return!0;switch(e.type){case"again":const e=this._selected.pageIdx+1,t=this._linkService;return e>=1&&e<=t.pagesCount&&e!==t.page&&!(this.onIsPageVisible?.(e)??1);case"highlightallchange":return!1}return!0}#ki(e,t,i){let n=e.slice(0,t).match(Ln);if(n){const i=e.charCodeAt(t),s=n[1].charCodeAt(0);if(fn(i)===fn(s))return!1}if(n=e.slice(t+i).match(_n),n){const s=e.charCodeAt(t+i-1),a=n[1].charCodeAt(0);if(fn(s)===fn(a))return!1}return!0}#Di(e,t){const{matchDiacritics:i}=this.#wi;let n=!1;const s=(t,i)=>t===e?i:e.startsWith(t)?`${i}[ ]*`:e.endsWith(t)?`[ ]*${i}`:`[ ]*${i}[ ]*`,a="[ ]*";return(e=e.replaceAll(Tn,(e,a,r,o,l,d)=>a?s(a,RegExp.escape(a)):r?s(r,RegExp.escape(r)):o?"[ ]+":i?l||d:l?Sn.has(l.charCodeAt(0))?l:"":t?(n=!0,`${d}\\p{M}*`):d)).endsWith(a)&&(e=e.slice(0,e.length-4)),i&&t&&(En||=String.fromCharCode(...Sn),n=!0,e=`${e}(?=[${En}]|[^\\p{M}]|$)`),[n,e]}#Ni(e){if(!this.#wi)return;const t=this.#Bi;if(0===t.length)return;const i=this._pageContents[e],n=this.match(t,i,e),s=this._pageMatches[e]=[],a=this._pageMatchesLength[e]=[],r=this._pageDiffs[e];n?.forEach(({index:e,length:t})=>{const[i,n]=Nn(r,e,t);n&&(s.push(i),a.push(n))}),this.#wi.highlightAll&&this.#Oi(e),this._resumePageIdx===e&&(this._resumePageIdx=null,this.#Ri());const o=s.length;this._matchesCountTotal+=o,this.#yi?o>0&&this.#ji():++this.#Pi===this._linkService.pagesCount&&this.#ji()}match(e,t,i){const n=this._hasDiacritics[i];let s=!1;if("string"==typeof e?[s,e]=this.#Di(e,n):e=e.sort().reverse().map(e=>{const[t,i]=this.#Di(e,n);return s||=t,`(${i})`}).join("|"),!e)return;const{caseSensitive:a,entireWord:r}=this.#wi;e=new RegExp(e,`g${s?"u":""}${a?"":"i"}`);const o=[];let l;for(;null!==(l=e.exec(t));)r&&!this.#ki(t,l.index,l[0].length)||o.push({index:l.index,length:l[0].length});return o}#Mi(){if(this._extractTextPromises.length>0)return;let e=Promise.resolve();const t={disableNormalization:!0},i=this._pdfDocument;for(let n=0,s=this._linkService.pagesCount;n<s;n++){const{promise:s,resolve:a}=Promise.withResolvers();this._extractTextPromises[n]=s,e=e.then(async()=>{if(i===this._pdfDocument){try{const e=await i.getPage(n+1),s=await e.getTextContent(t);if(i!==this._pdfDocument)return void a();const r=[];for(const e of s.items)r.push(e.str),e.hasEOL&&r.push("\n");[this._pageContents[n],this._pageDiffs[n],this._hasDiacritics[n]]=Dn(r.join(""))}catch(e){if(i!==this._pdfDocument)return void a();console.error(`Unable to get text content for page ${n+1}`,e),[this._pageContents[n],this._pageDiffs[n],this._hasDiacritics[n]]=["",null,!1]}a()}else a()})}}#Oi(e){this._scrollMatches&&this._selected.pageIdx===e&&(this._linkService.page=e+1),this._eventBus.dispatch("updatetextlayermatches",{source:this,pageIndex:e})}#Ai(){this._eventBus.dispatch("updatetextlayermatches",{source:this,pageIndex:-1})}#Ii(){const e=this.#wi.findPrevious,t=this._linkService.page-1,i=this._linkService.pagesCount;if(this._highlightMatches=!0,this._dirtyMatch){this._dirtyMatch=!1,this._selected.pageIdx=this._selected.matchIdx=-1,this._offset.pageIdx=t,this._offset.matchIdx=null,this._offset.wrapped=!1,this._resumePageIdx=null,this._pageMatches.length=0,this._pageMatchesLength.length=0,this.#Pi=0,this._matchesCountTotal=0,this.#Ai();for(let e=0;e<i;e++)this._pendingFindMatches.has(e)||(this._pendingFindMatches.add(e),this._extractTextPromises[e].then(()=>{this._pendingFindMatches.delete(e),this.#Ni(e)}))}if(0===this.#Bi.length)return void this.#xe(vn);if(this._resumePageIdx)return;const n=this._offset;if(this._pagesToSearch=i,null!==n.matchIdx){const t=this._pageMatches[n.pageIdx].length;if(!e&&n.matchIdx+1<t||e&&n.matchIdx>0)return n.matchIdx=e?n.matchIdx-1:n.matchIdx+1,void this.#Vi(!0);this.#Fi(e)}this.#Ri()}#Ui(e){const t=this._offset,i=e.length,n=this.#wi.findPrevious;return i?(t.matchIdx=n?i-1:0,this.#Vi(!0),!0):(this.#Fi(n),!!(t.wrapped&&(t.matchIdx=null,this._pagesToSearch<0))&&(this.#Vi(!1),!0))}#Ri(){null!==this._resumePageIdx&&console.error("There can only be one pending page.");let e=null;do{const t=this._offset.pageIdx;if(e=this._pageMatches[t],!e){this._resumePageIdx=t;break}}while(!this.#Ui(e))}#Fi(e){const t=this._offset,i=this._linkService.pagesCount;t.pageIdx=e?t.pageIdx-1:t.pageIdx+1,t.matchIdx=null,this._pagesToSearch--,(t.pageIdx>=i||t.pageIdx<0)&&(t.pageIdx=e?i-1:0,t.wrapped=!0)}#Vi(e=!1){let t=wn;const i=this._offset.wrapped;if(this._offset.wrapped=!1,e){const e=this._selected.pageIdx;this._selected.pageIdx=this._offset.pageIdx,this._selected.matchIdx=this._offset.matchIdx,t=i?yn:vn,-1!==e&&e!==this._selected.pageIdx&&this.#Oi(e)}this.#xe(t,this.#wi.findPrevious),-1!==this._selected.pageIdx&&(this._scrollMatches=!0,this.#Oi(this._selected.pageIdx))}#Li({pagesMapper:e,type:t,pageNumbers:i}){if(0===this._extractTextPromises.length)return;if("copy"===t){const e=new Map,t=new Map,n=new Map,s=new Map;for(const a of i)e.set(a,this._extractTextPromises[a-1]),t.set(a,this._pageContents[a-1]),n.set(a,this._pageDiffs[a-1]),s.set(a,this._hasDiacritics[a-1]);return void(this.#Si={promises:e,contents:t,diffs:n,diacritics:s})}if("cancelCopy"===t)return void(this.#Si=null);if("delete"===t&&(this.#Ei={promises:this._extractTextPromises,contents:this._pageContents,diffs:this._pageDiffs,diacritics:this._hasDiacritics}),"cancelDelete"===t)return this._extractTextPromises=this.#Ei.promises,this._pageContents=this.#Ei.contents,this._pageDiffs=this.#Ei.diffs,void(this._hasDiacritics=this.#Ei.diacritics);if("cleanSavedData"===t)return void(this.#Ei=null);this._findTimeout&&(clearTimeout(this._findTimeout),this._findTimeout=null),this._resumePageIdx=null,this._dirtyMatch=!0;const n=this._extractTextPromises,s=this._pageContents,a=this._pageDiffs,r=this._hasDiacritics,o=this._extractTextPromises=[],l=this._pageContents=[],d=this._pageDiffs=[],h=this._hasDiacritics=[];for(let t=1,i=e.pagesNumber;t<=i;t++){const i=e.getPrevPageNumber(t);if(i<0){const e=-i;o.push(this.#Si?.promises.get(e)||Promise.resolve()),l.push(this.#Si?.contents.get(e)??""),d.push(this.#Si?.diffs.get(e)??null),h.push(this.#Si?.diacritics.get(e)??!1);continue}o.push(n[i-1]||Promise.resolve()),l.push(s[i-1]??""),d.push(a[i-1]??null),h.push(r[i-1]??!1)}this.#wi&&this.#Ii()}#Ti(e){const t=this._pdfDocument;this._firstPageCapability.promise.then(()=>{!this._pdfDocument||t&&this._pdfDocument!==t||(this._findTimeout&&(clearTimeout(this._findTimeout),this._findTimeout=null),this._resumePageIdx&&(this._resumePageIdx=null,this._dirtyMatch=!0),this.#xe(vn),this._highlightMatches=!1,this.#Ai())})}#zi(){const{pageIdx:e,matchIdx:t}=this._selected;let i=0,n=this._matchesCountTotal;if(-1!==t){for(let t=0;t<e;t++)i+=this._pageMatches[t]?.length||0;i+=t+1}return(i<1||i>n)&&(i=n=0),{current:i,total:n}}#ji(){this._eventBus.dispatch("updatefindmatchescount",{source:this,matchesCount:this.#zi()})}#xe(e,t=!1){(this.#yi||this.#Pi===this._linkService.pagesCount&&e!==Cn)&&this._eventBus.dispatch("updatefindcontrolstate",{source:this,state:e,previous:t,entireWord:this.#wi?.entireWord??null,matchesCount:this.#zi(),rawQuery:this.#wi?.query??null})}}class Rn{#Ae;#Ke=new ResizeObserver(this.#Hi.bind(this));opened=!1;constructor(e,t,i){this.bar=e.bar,this.toggleButton=e.toggleButton,this.findField=e.findField,this.highlightAll=e.highlightAllCheckbox,this.caseSensitive=e.caseSensitiveCheckbox,this.matchDiacritics=e.matchDiacriticsCheckbox,this.entireWord=e.entireWordCheckbox,this.findMsg=e.findMsg,this.findResultsCount=e.findResultsCount,this.findPreviousButton=e.findPreviousButton,this.findNextButton=e.findNextButton,this.eventBus=i,this.#Ae=t;const n=new Map([[this.highlightAll,"highlightallchange"],[this.caseSensitive,"casesensitivitychange"],[this.entireWord,"entirewordchange"],[this.matchDiacritics,"diacriticmatchingchange"]]);this.toggleButton.addEventListener("click",()=>{this.toggle()}),this.findField.addEventListener("input",()=>{this.dispatchEvent("")}),this.bar.addEventListener("keydown",({keyCode:e,shiftKey:t,target:i})=>{switch(e){case 13:i===this.findField?this.dispatchEvent("again",t):n.has(i)&&(i.checked=!i.checked,this.dispatchEvent(n.get(i)));break;case 27:this.close()}}),this.findPreviousButton.addEventListener("click",()=>{this.dispatchEvent("again",!0)}),this.findNextButton.addEventListener("click",()=>{this.dispatchEvent("again",!1)});for(const[e,t]of n)e.addEventListener("click",()=>{this.dispatchEvent(t)})}reset(){this.updateUIState()}dispatchEvent(e,t=!1){this.eventBus.dispatch("find",{source:this,type:e,query:this.findField.value,caseSensitive:this.caseSensitive.checked,entireWord:this.entireWord.checked,highlightAll:this.highlightAll.checked,findPrevious:t,matchDiacritics:this.matchDiacritics.checked})}updateUIState(e,t,i){const{findField:n,findMsg:s}=this;let a="",r="";switch(e){case vn:break;case Cn:r="pending";break;case wn:a="pdfjs-find-not-found",r="notFound";break;case yn:a=t?"pdfjs-find-reached-top":"pdfjs-find-reached-bottom"}n.setAttribute("data-status",r),n.setAttribute("aria-invalid",e===wn),s.setAttribute("data-status",r),a?s.setAttribute("data-l10n-id",a):(s.removeAttribute("data-l10n-id"),s.textContent=""),this.updateResultsCount(i)}updateResultsCount({current:e=0,total:t=0}={}){const{findResultsCount:i}=this;if(t>0){const n=1e3;i.setAttribute("data-l10n-id",t>n?"pdfjs-find-match-count-limit":"pdfjs-find-match-count"),i.setAttribute("data-l10n-args",JSON.stringify({limit:n,current:e,total:t}))}else i.removeAttribute("data-l10n-id"),i.textContent=""}open(){this.opened||(this.#Ke.observe(this.#Ae),this.#Ke.observe(this.bar),this.opened=!0,V(this.toggleButton,!0,this.bar)),this.findField.select(),this.findField.focus()}close(){this.opened&&(this.#Ke.disconnect(),this.opened=!1,V(this.toggleButton,!1,this.bar),this.eventBus.dispatch("findbarclose",{source:this}))}toggle(){this.opened?this.close():this.open()}#Hi(){const{bar:e}=this;e.classList.remove("wrapContainers");e.clientHeight>e.firstElementChild.clientHeight&&e.classList.add("wrapContainers")}}function jn(){return document.location.hash}class Vn{#$i=null;constructor({linkService:e,eventBus:t}){this.linkService=e,this.eventBus=t,this._initialized=!1,this._fingerprint="",this.reset(),this.eventBus.on("pagesinit",()=>{this._isPagesLoaded=!1,this.eventBus.on("pagesloaded",e=>{this._isPagesLoaded=!!e.pagesCount},{once:!0,...Q})},Q)}initialize({fingerprint:e,resetHistory:t=!1,updateUrl:i=!1}){if(!e||"string"!=typeof e)return void console.error('PDFHistory.initialize: The "fingerprint" must be a non-empty string.');this._initialized&&this.reset();const n=""!==this._fingerprint&&this._fingerprint!==e;this._fingerprint=e,this._updateUrl=!0===i,this._initialized=!0,this.#Wi();const s=window.history.state;if(this._popStateInProgress=!1,this._blockHashChange=0,this._currentHash=jn(),this._numPositionUpdates=0,this._uid=this._maxUid=0,this._destination=null,this._position=null,!this.#Xi(s,!0)||t){const{hash:e,page:i,rotation:s}=this.#Gi(!0);return!e||n||t?void this.#Yi(null,!0):void this.#Yi({hash:e,page:i,rotation:s},!0)}const a=s.destination;this.#Ki(a,s.uid,!0),void 0!==a.rotation&&(this._initialRotation=a.rotation),a.dest?(this._initialBookmark=JSON.stringify(a.dest),this._destination.page=null):a.hash?this._initialBookmark=a.hash:a.page&&(this._initialBookmark=`page=${a.page}`)}reset(){this._initialized&&(this.#Zi(),this._initialized=!1,this.#qi()),this._updateViewareaTimeout&&(clearTimeout(this._updateViewareaTimeout),this._updateViewareaTimeout=null),this._initialBookmark=null,this._initialRotation=null}push({namedDest:e=null,explicitDest:t,pageNumber:i}){if(!this._initialized)return;if(e&&"string"!=typeof e)return void console.error(`PDFHistory.push: "${e}" is not a valid namedDest parameter.`);if(!Array.isArray(t))return void console.error(`PDFHistory.push: "${t}" is not a valid explicitDest parameter.`);if(!this.#Qi(i)&&(null!==i||this._destination))return void console.error(`PDFHistory.push: "${i}" is not a valid pageNumber parameter.`);const n=e||JSON.stringify(t);if(!n)return;let s=!1;if(this._destination&&(function(e,t){if("string"!=typeof e||"string"!=typeof t)return!1;if(e===t)return!0;if(y(e).get("nameddest")===t)return!0;return!1}(this._destination.hash,n)||function(e,t){function i(e,t){if(typeof e!=typeof t)return!1;if(Array.isArray(e)||Array.isArray(t))return!1;if(null!==e&&"object"==typeof e&&null!==t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(!i(e[n],t[n]))return!1;return!0}return e===t||Number.isNaN(e)&&Number.isNaN(t)}if(!Array.isArray(e)||!Array.isArray(t))return!1;if(e.length!==t.length)return!1;for(let n=0,s=e.length;n<s;n++)if(!i(e[n],t[n]))return!1;return!0}(this._destination.dest,t))){if(this._destination.page)return;s=!0}this._popStateInProgress&&!s||(this.#Yi({dest:t,hash:n,page:i,rotation:this.linkService.rotation},s),this._popStateInProgress||(this._popStateInProgress=!0,Promise.resolve().then(()=>{this._popStateInProgress=!1})))}pushPage(e){this._initialized&&(this.#Qi(e)?this._destination?.page!==e&&(this._popStateInProgress||(this.#Yi({dest:null,hash:`page=${e}`,page:e,rotation:this.linkService.rotation}),this._popStateInProgress||(this._popStateInProgress=!0,Promise.resolve().then(()=>{this._popStateInProgress=!1})))):console.error(`PDFHistory.pushPage: "${e}" is not a valid page number.`))}pushCurrentPosition(){this._initialized&&!this._popStateInProgress&&this.#Ji()}back(){if(!this._initialized||this._popStateInProgress)return;const e=window.history.state;this.#Xi(e)&&e.uid>0&&window.history.back()}forward(){if(!this._initialized||this._popStateInProgress)return;const e=window.history.state;this.#Xi(e)&&e.uid<this._maxUid&&window.history.forward()}get popStateInProgress(){return this._initialized&&(this._popStateInProgress||this._blockHashChange>0)}get initialBookmark(){return this._initialized?this._initialBookmark:null}get initialRotation(){return this._initialized?this._initialRotation:null}#Yi(e,t=!1){const i=t||!this._destination,n={fingerprint:this._fingerprint,uid:i?this._uid:this._uid+1,destination:e};let s;if(this.#Ki(e,n.uid),this._updateUrl&&e?.hash){const{href:t,protocol:i}=document.location;"file:"!==i&&(s=et(t,e.hash))}i?window.history.replaceState(n,"",s):window.history.pushState(n,"",s)}#Ji(e=!1){if(!this._position)return;let t=this._position;if(e&&(t=Object.assign(Object.create(null),this._position),t.temporary=!0),!this._destination)return void this.#Yi(t);if(this._destination.temporary)return void this.#Yi(t,!0);if(this._destination.hash===t.hash)return;if(!this._destination.page&&this._numPositionUpdates<=50)return;let i=!1;if(this._destination.page>=t.first&&this._destination.page<=t.page){if(void 0!==this._destination.dest||!this._destination.first)return;i=!0}this.#Yi(t,i)}#Qi(e){return Number.isInteger(e)&&e>0&&e<=this.linkService.pagesCount}#Xi(e,t=!1){if(!e)return!1;if(e.fingerprint!==this._fingerprint){if(!t)return!1;{if("string"!=typeof e.fingerprint||e.fingerprint.length!==this._fingerprint.length)return!1;const[t]=performance.getEntriesByType("navigation");if("reload"!==t?.type)return!1}}return!(!Number.isInteger(e.uid)||e.uid<0)&&(null!==e.destination&&"object"==typeof e.destination)}#Ki(e,t,i=!1){this._updateViewareaTimeout&&(clearTimeout(this._updateViewareaTimeout),this._updateViewareaTimeout=null),i&&e?.temporary&&delete e.temporary,this._destination=e,this._uid=t,this._maxUid=Math.max(this._maxUid,t),this._numPositionUpdates=0}#Gi(e=!1){const t=unescape(jn()).substring(1),i=y(t),n=i.get("nameddest")||"";let s=0|i.get("page");return(!this.#Qi(s)||e&&n.length>0)&&(s=null),{hash:t,page:s,rotation:this.linkService.rotation}}#en({location:e}){this._updateViewareaTimeout&&(clearTimeout(this._updateViewareaTimeout),this._updateViewareaTimeout=null),this._position={hash:e.pdfOpenParams.substring(1),page:this.linkService.page,first:e.pageNumber,rotation:e.rotation},this._popStateInProgress||(this._isPagesLoaded&&this._destination&&!this._destination.page&&this._numPositionUpdates++,this._updateViewareaTimeout=setTimeout(()=>{this._popStateInProgress||this.#Ji(!0),this._updateViewareaTimeout=null},1e3))}#tn({state:e}){const t=jn(),i=this._currentHash!==t;if(this._currentHash=t,!e){this._uid++;const{hash:e,page:t,rotation:i}=this.#Gi();return void this.#Yi({hash:e,page:t,rotation:i},!0)}if(!this.#Xi(e))return;this._popStateInProgress=!0,i&&(this._blockHashChange++,ht({target:window,name:"hashchange",delay:1e3}).then(()=>{this._blockHashChange--}));const n=e.destination;this.#Ki(n,e.uid,!0),_(n.rotation)&&(this.linkService.rotation=n.rotation),n.dest?this.linkService.goToDestination(n.dest):n.hash?this.linkService.setHash(n.hash):n.page&&(this.linkService.page=n.page),Promise.resolve().then(()=>{this._popStateInProgress=!1})}#Zi(){this._destination&&!this._destination.temporary||this.#Ji()}#Wi(){if(this.#$i)return;this.#$i=new AbortController;const{signal:e}=this.#$i;this.eventBus.on("updateviewarea",this.#en.bind(this),{signal:e,...Q}),window.addEventListener("popstate",this.#tn.bind(this),{signal:e}),window.addEventListener("pagehide",this.#Zi.bind(this),{signal:e})}#qi(){this.#$i?.abort(),this.#$i=null}}class Fn extends qi{constructor(e){super(e);const{eventBus:t}=this;t.on("optionalcontentconfigchanged",e=>{this.#in(e.promise)},Q),t.on("resetlayers",()=>{this.#in()},Q),t.on("togglelayerstree",this._toggleAllTreeItems.bind(this),Q)}reset(){super.reset(),this._optionalContentConfig=null,this._optionalContentVisibility?.clear(),this._optionalContentVisibility=null}_dispatchEvent(e){this.eventBus.dispatch("layersloaded",{source:this,layersCount:e})}_bindLink(e,{groupId:t,input:i}){const n=()=>{const e=i.checked;this._optionalContentConfig.setVisibility(t,e);const n=this._optionalContentVisibility.get(t);n&&(n.visible=e),this.eventBus.dispatch("optionalcontentconfig",{source:this,promise:Promise.resolve(this._optionalContentConfig)})};e.onclick=t=>t.target===i?(n(),!0):t.target!==e||(i.checked=!i.checked,n(),!1)}_setNestedName(e,{name:t=null}){"string"!=typeof t?(e.setAttribute("data-l10n-id","pdfjs-additional-layers"),e.style.fontStyle="italic",this._l10n.translateOnce(e)):e.textContent=this._normalizeTextContent(t)}_addToggleButton(e,{name:t=null}){super._addToggleButton(e,null===t)}_toggleAllTreeItems(){this._optionalContentConfig&&super._toggleAllTreeItems()}render({optionalContentConfig:e,pdfDocument:t}){this._optionalContentConfig&&this.reset(),this._optionalContentConfig=e||null,this._pdfDocument=t||null;const i=e?.getOrder();if(!i)return void this._dispatchEvent(0);this._optionalContentVisibility=new Map;const n=document.createDocumentFragment(),s=[{parent:n,groups:i}];let a=0,r=!1;for(;s.length>0;){const t=s.shift();for(const i of t.groups){const n=document.createElement("div");n.className="treeItem";const o=document.createElement("a");if(n.append(o),"object"==typeof i){r=!0,this._addToggleButton(n,i),this._setNestedName(o,i);const e=document.createElement("div");e.className="treeItems",n.append(e),s.push({parent:e,groups:i.order})}else{const t=e.getGroup(i),n=document.createElement("label"),s=document.createElement("input");n.append(s,document.createTextNode(this._normalizeTextContent(t.name))),this._bindLink(o,{groupId:i,input:s}),s.type="checkbox",s.checked=t.visible,this._optionalContentVisibility.set(i,{input:s,visible:s.checked}),o.append(n),a++}t.parent.append(n)}}this._finishRendering(n,a,r)}async#in(e=null){if(!this._optionalContentConfig)return;const t=this._pdfDocument,i=await(e||t.getOptionalContentConfig({intent:"display"}));if(t===this._pdfDocument)if(e)for(const[e,t]of this._optionalContentVisibility){const n=i.getGroup(e);n&&t.visible!==n.visible&&(t.input.checked=t.visible=!t.visible)}else this.eventBus.dispatch("optionalcontentconfig",{source:this,promise:Promise.resolve(i)}),this.render({optionalContentConfig:i,pdfDocument:this._pdfDocument})}}class Un extends qi{constructor(e){super(e),this.linkService=e.linkService,this.downloadManager=e.downloadManager;const{eventBus:t}=this;t.on("toggleoutlinetree",this._toggleAllTreeItems.bind(this),Q),t.on("currentoutlineitem",this._currentOutlineItem.bind(this),Q),t.on("pagechanging",e=>{this._currentPageNumber=e.pageNumber},Q),t.on("pagesloaded",e=>{this._isPagesLoaded=!!e.pagesCount,this._currentOutlineItemCapability?.resolve(this._isPagesLoaded)},Q),t.on("sidebarviewchanged",e=>{this._sidebarView=e.view},Q)}reset(){super.reset(),this._outline=null,this._pageNumberToDestHashCapability=null,this._currentPageNumber=1,this._isPagesLoaded=null,this._currentOutlineItemCapability?.resolve(!1),this._currentOutlineItemCapability=null}_dispatchEvent(e){this._currentOutlineItemCapability=Promise.withResolvers(),0===e||this._pdfDocument?.loadingParams.disableAutoFetch?this._currentOutlineItemCapability.resolve(!1):null!==this._isPagesLoaded&&this._currentOutlineItemCapability.resolve(this._isPagesLoaded),this.eventBus.dispatch("outlineloaded",{source:this,outlineCount:e,currentOutlineItemPromise:this._currentOutlineItemCapability.promise})}_bindLink(e,{url:t,newWindow:i,action:n,attachment:s,dest:a,setOCGState:r}){const{linkService:o}=this;if(t)o.addLinkAttributes(e,t,i);else{if(n)return e.href=o.getAnchorUrl(""),void(e.onclick=()=>(o.executeNamedAction(n),!1));if(s)return e.href=o.getAnchorUrl(""),void(e.onclick=()=>(this.downloadManager.openOrDownloadData(s.content,s.filename),!1));if(r)return e.href=o.getAnchorUrl(""),void(e.onclick=()=>(o.executeSetOCGState(r),!1));e.href=o.getDestinationHash(a),e.onclick=e=>(this._updateCurrentTreeItem(e.target.parentNode),a&&o.goToDestination(a),!1)}}_setStyles(e,{bold:t,italic:i}){t&&(e.style.fontWeight="bold"),i&&(e.style.fontStyle="italic")}_addToggleButton(e,{count:t,items:i}){let n=!1;if(t<0){let e=i.length;if(e>0){const t=[...i];for(;t.length>0;){const{count:i,items:n}=t.shift();i>0&&n.length>0&&(e+=n.length,t.push(...n))}}Math.abs(t)===e&&(n=!0)}super._addToggleButton(e,n)}_toggleAllTreeItems(){this._outline&&super._toggleAllTreeItems()}render({outline:e,pdfDocument:t}){if(this._outline&&this.reset(),this._outline=e||null,this._pdfDocument=t||null,!e)return void this._dispatchEvent(0);const i=document.createDocumentFragment(),n=[{parent:i,items:e}];let s=0,a=!1;for(;n.length>0;){const e=n.shift();for(const t of e.items){const i=document.createElement("div");i.className="treeItem";const r=document.createElement("a");if(this._bindLink(r,t),this._setStyles(r,t),r.textContent=this._normalizeTextContent(t.title),i.append(r),t.items.length>0){a=!0,this._addToggleButton(i,t);const e=document.createElement("div");e.className="treeItems",i.append(e),n.push({parent:e,items:t.items})}e.parent.append(i),s++}}this._finishRendering(i,s,a)}async _currentOutlineItem(){if(!this._isPagesLoaded)throw new Error("_currentOutlineItem: All pages have not been loaded.");if(!this._outline||!this._pdfDocument)return;const e=await this._getPageNumberToDestHash(this._pdfDocument);if(e&&(this._updateCurrentTreeItem(null),this._sidebarView===l))for(let t=this._currentPageNumber;t>0;t--){const i=e.get(t);if(!i)continue;const n=this.container.querySelector(`a[href="${i}"]`);if(n){this._scrollToCurrentTreeItem(n.parentNode);break}}}async _getPageNumberToDestHash(e){if(this._pageNumberToDestHashCapability)return this._pageNumberToDestHashCapability.promise;this._pageNumberToDestHashCapability=Promise.withResolvers();const t=new Map,i=new Map,n=[{nesting:0,items:this._outline}];for(;n.length>0;){const s=n.shift(),a=s.nesting;for(const{dest:r,items:o}of s.items){let s,l;if("string"==typeof r){if(s=await e.getDestination(r),e!==this._pdfDocument)return null}else s=r;if(Array.isArray(s)){const[n]=s;if(n&&"object"==typeof n?l=e.cachedPageNumber(n):Number.isInteger(n)&&(l=n+1),Number.isInteger(l)&&(!t.has(l)||a>i.get(l))){const e=this.linkService.getDestinationHash(r);t.set(l,e),i.set(l,a)}}o.length>0&&n.push({nesting:a+1,items:o})}}return this._pageNumberToDestHashCapability.resolve(t.size>0?t:null),this._pageNumberToDestHashCapability.promise}}const zn="pdfPresentationMode",Hn="pdfPresentationModeControls",$n=Math.PI/6;class Wn{#wi=t;#nn=null;#sn=null;#an=null;constructor({container:e,pdfViewer:t,eventBus:i}){this.container=e,this.pdfViewer=t,this.eventBus=i,this.contextMenuOpen=!1,this.mouseScrollTimeStamp=0,this.mouseScrollDelta=0,this.touchSwipeState=null}async request(){const{container:e,pdfViewer:t}=this;if(this.active||!t.pagesCount||!e.requestFullscreen)return!1;this.#rn(),this.#on(n);const s=e.requestFullscreen();this.#nn={pageNumber:t.currentPageNumber,scaleValue:t.currentScaleValue,scrollMode:t.scrollMode,spreadMode:null,annotationEditorMode:null},t.spreadMode===m.NONE||t.pageViewsReady&&t.hasEqualPageSizes||(console.warn("Ignoring Spread modes when entering PresentationMode, since the document may contain varying page sizes."),this.#nn.spreadMode=t.spreadMode),t.annotationEditorMode!==ie.DISABLE&&(this.#nn.annotationEditorMode=t.annotationEditorMode);try{return await s,t.focus(),!0}catch{this.#ln(),this.#on(i)}return!1}get active(){return this.#wi===n||this.#wi===s}#dn(e){if(!this.active)return;e.preventDefault();const t=function(e){const t=e.deltaMode;let i=L(e);return t===WheelEvent.DOM_DELTA_PIXEL?i/=900:t===WheelEvent.DOM_DELTA_LINE&&(i/=30),i}(e),i=Date.now(),n=this.mouseScrollTimeStamp;if(!(i>n&&i-n<50)&&((this.mouseScrollDelta>0&&t<0||this.mouseScrollDelta<0&&t>0)&&this.#hn(),this.mouseScrollDelta+=t,Math.abs(this.mouseScrollDelta)>=.1)){const e=this.mouseScrollDelta;this.#hn();(e>0?this.pdfViewer.previousPage():this.pdfViewer.nextPage())&&(this.mouseScrollTimeStamp=i)}}#on(e){this.#wi=e,this.eventBus.dispatch("presentationmodechanged",{source:this,state:e})}#cn(){this.#on(s),this.container.classList.add(zn),setTimeout(()=>{this.pdfViewer.scrollMode=p.PAGE,null!==this.#nn.spreadMode&&(this.pdfViewer.spreadMode=m.NONE),this.pdfViewer.currentPageNumber=this.#nn.pageNumber,this.pdfViewer.currentScaleValue="page-fit",null!==this.#nn.annotationEditorMode&&(this.pdfViewer.annotationEditorMode={mode:ie.NONE})},0),this.#un(),this.#gn(),this.contextMenuOpen=!1,document.getSelection().empty()}#pn(){const e=this.pdfViewer.currentPageNumber;this.container.classList.remove(zn),setTimeout(()=>{this.#ln(),this.#on(i),this.pdfViewer.scrollMode=this.#nn.scrollMode,null!==this.#nn.spreadMode&&(this.pdfViewer.spreadMode=this.#nn.spreadMode),this.pdfViewer.currentScaleValue=this.#nn.scaleValue,this.pdfViewer.currentPageNumber=e,null!==this.#nn.annotationEditorMode&&(this.pdfViewer.annotationEditorMode={mode:this.#nn.annotationEditorMode}),this.#nn=null},0),this.#mn(),this.#fn(),this.#hn(),this.contextMenuOpen=!1}#bn(e){if(this.contextMenuOpen)return this.contextMenuOpen=!1,void e.preventDefault();0===e.button&&(e.target.href&&e.target.parentNode?.hasAttribute("data-internal-link")||(e.preventDefault(),e.shiftKey?this.pdfViewer.previousPage():this.pdfViewer.nextPage()))}#vn(){this.contextMenuOpen=!0}#gn(){this.controlsTimeout?clearTimeout(this.controlsTimeout):this.container.classList.add(Hn),this.controlsTimeout=setTimeout(()=>{this.container.classList.remove(Hn),delete this.controlsTimeout},3e3)}#fn(){this.controlsTimeout&&(clearTimeout(this.controlsTimeout),this.container.classList.remove(Hn),delete this.controlsTimeout)}#hn(){this.mouseScrollTimeStamp=0,this.mouseScrollDelta=0}#wn(e){if(this.active)if(e.touches.length>1)this.touchSwipeState=null;else switch(e.type){case"touchstart":this.touchSwipeState={startX:e.touches[0].pageX,startY:e.touches[0].pageY,endX:e.touches[0].pageX,endY:e.touches[0].pageY};break;case"touchmove":if(null===this.touchSwipeState)return;this.touchSwipeState.endX=e.touches[0].pageX,this.touchSwipeState.endY=e.touches[0].pageY,e.preventDefault();break;case"touchend":if(null===this.touchSwipeState)return;let t=0;const i=this.touchSwipeState.endX-this.touchSwipeState.startX,n=this.touchSwipeState.endY-this.touchSwipeState.startY,s=Math.abs(Math.atan2(n,i));Math.abs(i)>50&&(s<=$n||s>=Math.PI-$n)?t=i:Math.abs(n)>50&&Math.abs(s-Math.PI/2)<=$n&&(t=n),t>0?this.pdfViewer.previousPage():t<0&&this.pdfViewer.nextPage()}}#un(){if(this.#an)return;this.#an=new AbortController;const{signal:e}=this.#an,t=this.#wn.bind(this);window.addEventListener("mousemove",this.#gn.bind(this),{signal:e}),window.addEventListener("mousedown",this.#bn.bind(this),{signal:e}),window.addEventListener("wheel",this.#dn.bind(this),{passive:!1,signal:e}),window.addEventListener("keydown",this.#hn.bind(this),{signal:e}),window.addEventListener("contextmenu",this.#vn.bind(this),{signal:e}),window.addEventListener("touchstart",t,{signal:e}),window.addEventListener("touchmove",t,{signal:e}),window.addEventListener("touchend",t,{signal:e})}#mn(){this.#an?.abort(),this.#an=null}#rn(){this.#sn||(this.#sn=new AbortController,window.addEventListener("fullscreenchange",()=>{document.fullscreenElement?this.#cn():this.#pn()},{signal:this.#sn.signal}))}#ln(){this.#sn?.abort(),this.#sn=null}}class Xn{#yn=!1;div=null;constructor({pdfPage:e,annotationStorage:t=null,linkService:i,xfaHtml:n=null}){this.pdfPage=e,this.annotationStorage=t,this.linkService=i,this.xfaHtml=n}async render({viewport:e,intent:t="display"}){let i;if("print"===t)i=this.xfaHtml;else if(i=await this.pdfPage.getXfa(),this.#yn||!i)return{textDivs:[]};const n=!!this.div,s={viewport:e.clone({dontFlip:!0}),div:this.div??=document.createElement("div"),xfaHtml:i,annotationStorage:this.annotationStorage,linkService:this.linkService,intent:t};return n?st.update(s):st.render(s)}cancel(){this.#yn=!0}hide(){this.div&&(this.div.hidden=!0)}}class Gn{static initGlobals(e){}static get supportsPrinting(){throw new Error("Not implemented: supportsPrinting")}static createPrintService(e){throw new Error("Not implemented: createPrintService")}}let Yn=null,Kn=null,Zn=null,qn={initialized:!1};class Qn{constructor({pdfDocument:e,pagesOverview:t,printContainer:i,printResolution:n,printAnnotationStoragePromise:s=null}){this.pdfDocument=e,this.pagesOverview=t,this.printContainer=i,this._printResolution=n||150,this._optionalContentConfigPromise=e.getOptionalContentConfig({intent:"print"}),this._printAnnotationStoragePromise=s||Promise.resolve(),this.currentPage=-1,this.scratchCanvas=document.createElement("canvas")}layout(){this.throwIfInactive();const e=document.querySelector("body");e.setAttribute("data-pdfjsprinting",!0);const{width:t,height:i}=this.pagesOverview[0];this.pagesOverview.every(e=>e.width===t&&e.height===i)||console.warn("Not all pages have the same size. The printed result may be incorrect!"),this.pageStyleSheet=document.createElement("style"),this.pageStyleSheet.textContent=`@page { size: ${t}pt ${i}pt;}`,e.append(this.pageStyleSheet)}destroy(){if(Yn!==this)return;this.printContainer.textContent="";if(document.querySelector("body").removeAttribute("data-pdfjsprinting"),this.pageStyleSheet&&(this.pageStyleSheet.remove(),this.pageStyleSheet=null),this._blobURLs){for(const e of this._blobURLs)URL.revokeObjectURL(e);this._blobURLs=null}this.scratchCanvas.width=this.scratchCanvas.height=0,this.scratchCanvas=null,Yn=null,ss().then(function(){Zn.closeIfActive(Kn)})}renderPages(){if(this.pdfDocument.isPureXfa)return function(e,t){const i=t.allXfaHtml,n=new ot,s=Math.round(100*ze.PDF_TO_CSS_UNITS)/100;for(const a of i.children){const i=document.createElement("div");i.className="xfaPrintedPage",e.append(i);const r=new Xn({pdfPage:null,annotationStorage:t.annotationStorage,linkService:n,xfaHtml:a}),o=st.getPageViewport(a,{scale:s});r.render({viewport:o,intent:"print"}),i.append(r.div)}}(this.printContainer,this.pdfDocument),Promise.resolve();const e=this.pagesOverview.length,t=(i,n)=>{if(this.throwIfInactive(),++this.currentPage>=e)return is(e,e),void i();const s=this.currentPage;is(s,e),function(e,t,i,n,s,a,r){const o=Yn.scratchCanvas,l=s/ze.PDF;o.width=Math.floor(n.width*l),o.height=Math.floor(n.height*l);const d=o.getContext("2d");return d.save(),d.fillStyle="rgb(255, 255, 255)",d.fillRect(0,0,o.width,o.height),d.restore(),Promise.all([t.getPage(i),r]).then(function([e,t]){const i={canvas:o,transform:[l,0,0,l,0,0],viewport:e.getViewport({scale:1,rotation:n.rotation}),intent:"print",annotationMode:ae.ENABLE_STORAGE,optionalContentConfigPromise:a,printAnnotationStorage:t};return e.render(i).promise.catch(e=>{throw e instanceof He||console.error(e),e})})}(0,this.pdfDocument,s+1,this.pagesOverview[s],this._printResolution,this._optionalContentConfigPromise,this._printAnnotationStoragePromise).then(this.useRenderedPage.bind(this)).then(function(){t(i,n)},n)};return new Promise(t)}useRenderedPage(){this.throwIfInactive();const e=document.createElement("img");this.scratchCanvas.toBlob(t=>{const i=URL.createObjectURL(t);e.src=i,(this._blobURLs??=[]).push(i)});const t=document.createElement("div");t.className="printedPage",t.append(e),this.printContainer.append(t);const{promise:i,resolve:n,reject:s}=Promise.withResolvers();return e.onload=n,e.onerror=s,i.catch(()=>{}),i}performPrint(){return this.throwIfInactive(),new Promise(e=>{setTimeout(()=>{this.active?(Jn.call(window),setTimeout(e,20)):e()},0)})}get active(){return this===Yn}throwIfInactive(){if(!this.active)throw new Error("This print request was cancelled or completed.")}}const Jn=window.print;function es(e){const t=new CustomEvent(e,{bubbles:!1,cancelable:!1,detail:"custom"});window.dispatchEvent(t)}function ts(){Yn&&(Yn.destroy(),es("afterprint"))}function is(e,t){Kn||=document.getElementById("printServiceDialog");const i=Math.round(100*e/t),n=Kn.querySelector("progress"),s=Kn.querySelector(".relative-progress");n.value=i,s.setAttribute("data-l10n-args",JSON.stringify({progress:i}))}if(window.print=function(){if(Yn)console.warn("Ignored window.print() because of a pending print job.");else{ss().then(function(){Yn&&Zn.open(Kn)});try{es("beforeprint")}finally{if(Yn){const e=Yn;Yn.renderPages().then(()=>e.performPrint()).catch(()=>{}).then(()=>{e.active&&ts()})}else console.error("Expected print service to be initialized."),ss().then(function(){Zn.closeIfActive(Kn)})}}},window.addEventListener("keydown",function(e){80!==e.keyCode||!e.ctrlKey&&!e.metaKey||e.altKey||e.shiftKey&&!window.chrome&&!window.opera||(window.print(),e.preventDefault(),e.stopImmediatePropagation())},!0),"onbeforeprint"in window){const e=function(e){"custom"!==e.detail&&e.stopImmediatePropagation()};window.addEventListener("beforeprint",e),window.addEventListener("afterprint",e)}let ns;function ss(){if(!ns){if(Zn=qn.overlayManager,!Zn)throw new Error("The overlay manager has not yet been initialized.");Kn||=document.getElementById("printServiceDialog"),ns=Zn.register(Kn,!0),document.getElementById("printCancel").onclick=ts,Kn.addEventListener("close",ts)}return ns}class as extends Gn{static initGlobals(e){qn=e}static get supportsPrinting(){return Ge(this,"supportsPrinting",!0)}static createPrintService(e){if(Yn)throw new Error("The print service is created and active.");return Yn=new Qn(e)}}const rs={INITIAL:0,RUNNING:1,PAUSED:2,FINISHED:3};class os{renderingId="";renderTask=null;resume=null;get renderingState(){throw new Error("Abstract getter `renderingState` accessed")}set renderingState(e){throw new Error("Abstract setter `renderingState` accessed")}async draw(){throw new Error("Not implemented: draw")}}class ls{#Cn=null;#Pn=null;#Sn=null;#En=null;isThumbnailViewEnabled=!1;onIdle=null;printing=!1;constructor(){Object.defineProperty(this,"hasViewer",{value:()=>!!this.#En})}setViewer(e){this.#En=e}setThumbnailViewer(e){this.#Sn=e}isHighestPriority(e){return this.#Cn===e.renderingId}renderHighestPriority(e){this.#Pn&&(clearTimeout(this.#Pn),this.#Pn=null),this.#En.forceRendering(e)||this.isThumbnailViewEnabled&&this.#Sn?.forceRendering()||this.printing||this.onIdle&&(this.#Pn=setTimeout(this.onIdle.bind(this),3e4))}getHighestPriority(e,t,i,n=!1,s=!1){const a=e.views,r=a.length;if(0===r)return null;for(let e=0;e<r;e++){const t=a[e].view;if(!this.isViewFinished(t))return t}if(!s)for(let e=0;e<r;e++){const{detailView:t}=a[e].view;if(t&&!this.isViewFinished(t))return t}const o=e.first.id,l=e.last.id;if(l-o+1>r){const n=e.ids;for(let e=1,s=l-o;e<s;e++){const s=i?o+e:l-e;if(n.has(s))continue;const a=t[s-1];if(!this.isViewFinished(a))return a}}let d=i?l:o-2,h=t[d];return h&&!this.isViewFinished(h)||n&&(d+=i?1:-1,h=t[d],h&&!this.isViewFinished(h))?h:null}isViewFinished(e){return e.renderingState===rs.FINISHED}renderView(e){switch(e.renderingState){case rs.FINISHED:return!1;case rs.PAUSED:this.#Cn=e.renderingId,e.resume();break;case rs.RUNNING:this.#Cn=e.renderingId;break;case rs.INITIAL:this.#Cn=e.renderingId,e.draw().finally(()=>{this.renderHighestPriority()}).catch(e=>{e instanceof He||console.error("renderView:",e)})}return!0}}class ds{#xn=null;#Tn=null;#Ln=null;#$i=null;#y=null;#_n=null;#Mn=null;#En=null;#In=!1;#An=null;#Bn=null;constructor({eventBus:e,externalServices:t=null,docProperties:i=null}){this.#y=e,this.#_n=t,this.#Ln=i}setViewer(e){this.#En=e}async setDocument(e){if(this.#Mn&&await this.#kn(),this.#Mn=e,!e)return;const[t,i,n]=await Promise.all([e.getFieldObjects(),e.getCalculationOrderIds(),e.getJSActions()]);if(!t&&!n)return void await this.#kn();if(e!==this.#Mn)return;try{this.#An=this.#Dn()}catch(e){return console.error("setDocument:",e),void await this.#kn()}const s=this.#y;this.#$i=new AbortController;const a={signal:this.#$i.signal,...Q};s.on("updatefromsandbox",e=>{e?.source===window&&this.#Nn(e.detail)},a),s.on("dispatcheventinsandbox",e=>{this.#An?.dispatchEventInSandbox(e.detail)},a),s.on("pagechanging",({pageNumber:e,previous:t})=>{e!==t&&(this.#On(t),this.#Rn(e))},a),s.on("pagerendered",({pageNumber:e})=>{this._pageOpenPending.has(e)&&e===this.#En.currentPageNumber&&this.#Rn(e)},a),s.on("pagesdestroy",async()=>{await this.#On(this.#En.currentPageNumber),await(this.#An?.dispatchEventInSandbox({id:"doc",name:"WillClose"})),this.#xn?.resolve()},a);try{const a=await this.#Ln(e);if(e!==this.#Mn)return;await this.#An.createSandbox({objects:t,calculationOrder:i,appInfo:{platform:navigator.platform,language:navigator.language},docInfo:{...a,actions:n}}),s.dispatch("sandboxcreated",{source:this})}catch(e){return console.error("setDocument:",e),void await this.#kn()}await(this.#An?.dispatchEventInSandbox({id:"doc",name:"Open"})),await this.#Rn(this.#En.currentPageNumber,!0),Promise.resolve().then(()=>{e===this.#Mn&&(this.#In=!0)})}async dispatchWillSave(){return this.#An?.dispatchEventInSandbox({id:"doc",name:"WillSave"})}async dispatchDidSave(){return this.#An?.dispatchEventInSandbox({id:"doc",name:"DidSave"})}async dispatchWillPrint(){if(this.#An){await(this.#Bn?.promise),this.#Bn=Promise.withResolvers();try{await this.#An.dispatchEventInSandbox({id:"doc",name:"WillPrint"})}catch(e){throw this.#Bn.resolve(),this.#Bn=null,e}await this.#Bn.promise}}async dispatchDidPrint(){return this.#An?.dispatchEventInSandbox({id:"doc",name:"DidPrint"})}get destroyPromise(){return this.#Tn?.promise||null}get ready(){return this.#In}get _pageOpenPending(){return Ge(this,"_pageOpenPending",new Set)}get _visitedPages(){return Ge(this,"_visitedPages",new Map)}async#Nn(e){const t=this.#En,i=t.isInPresentationMode||t.isChangingPresentationMode,{id:n,siblings:s,command:a,value:r}=e;if(!n){switch(a){case"clear":console.clear();break;case"error":console.error(r);break;case"layout":if(!i){const e=O(r);t.spreadMode=e.spreadMode}break;case"page-num":t.currentPageNumber=r+1;break;case"print":await t.pagesPromise,this.#y.dispatch("print",{source:this});break;case"println":console.log(r);break;case"zoom":i||(t.currentScaleValue=r);break;case"SaveAs":this.#y.dispatch("download",{source:this});break;case"FirstPage":t.currentPageNumber=1;break;case"LastPage":t.currentPageNumber=t.pagesCount;break;case"NextPage":t.nextPage();break;case"PrevPage":t.previousPage();break;case"ZoomViewIn":i||t.increaseScale();break;case"ZoomViewOut":i||t.decreaseScale();break;case"WillPrintFinished":this.#Bn?.resolve(),this.#Bn=null}return}if(i&&e.focus)return;delete e.id,delete e.siblings;const o=s?[n,...s]:[n];for(const t of o){const i=document.querySelector(`[data-element-id="${t}"]`);i?i.dispatchEvent(new CustomEvent("updatefromsandbox",{detail:e})):this.#Mn?.annotationStorage.setValue(t,e)}}async#Rn(e,t=!1){const i=this.#Mn,n=this._visitedPages;if(t&&(this.#xn=Promise.withResolvers()),!this.#xn)return;const s=this.#En.getPageView(e-1);if(s?.renderingState!==rs.FINISHED)return void this._pageOpenPending.add(e);this._pageOpenPending.delete(e);const a=(async()=>{const t=await(n.has(e)?null:s.pdfPage?.getJSActions());i===this.#Mn&&await(this.#An?.dispatchEventInSandbox({id:"page",name:"PageOpen",pageNumber:e,actions:t}))})();n.set(e,a)}async#On(e){const t=this.#Mn,i=this._visitedPages;if(!this.#xn)return;if(this._pageOpenPending.has(e))return;const n=i.get(e);n&&(i.set(e,null),await n,t===this.#Mn&&await(this.#An?.dispatchEventInSandbox({id:"page",name:"PageClose",pageNumber:e})))}#Dn(){if(this.#Tn=Promise.withResolvers(),this.#An)throw new Error("#initScripting: Scripting already exists.");return this.#_n.createScripting()}async#kn(){if(!this.#An)return this.#Mn=null,void this.#Tn?.resolve();this.#xn&&(await Promise.race([this.#xn.promise,new Promise(e=>{setTimeout(e,1e3)})]).catch(()=>{}),this.#xn=null),this.#Mn=null;try{await this.#An.destroySandbox()}catch{}this.#Bn?.reject(new Error("Scripting destroyed.")),this.#Bn=null,this.#$i?.abort(),this.#$i=null,this._pageOpenPending.clear(),this._visitedPages.clear(),this.#An=null,this.#In=!1,this.#Tn?.resolve()}}class hs{#jn;#Vn;#Fn;#Un=null;#zn=new AbortController;#Hn=-1;#$n=this.#Wn.bind(this);constructor(e,t,i){if(this.#Vn=e,this.#jn=t,Array.isArray(i))this.#Fn=i;else{this.#Fn=[];for(const e of this.#Vn.querySelectorAll("button"))this.#Fn.push(e)}this.#Xn()}#Gn(){if(!this.#Un)return;const e=this.#Vn;this.#jn.ariaExpanded="false",this.#Un.abort(),this.#Un=null,e.contains(document.activeElement)&&setTimeout(()=>{e.contains(document.activeElement)||this.#jn.focus()},0),this.#Hn=-1}#Yn(){if(this.#Un)return;const e=this.#Vn;this.#jn.ariaExpanded="true",this.#Un=new AbortController;const t=AbortSignal.any([this.#zn.signal,this.#Un.signal]);window.addEventListener("pointerdown",({target:t})=>{this.#jn.contains(t)||e.contains(t)||this.#Gn()},{signal:t});const i=this.#Gn.bind(this);window.addEventListener("blur",i,{signal:t}),e.addEventListener("focusout",this.#$n,{signal:t})}#Wn({relatedTarget:e}){this.#jn.contains(e)||this.#Vn.contains(e)||this.#Gn()}#Xn(){this.#jn.addEventListener("click",e=>{this.#Un?this.#Gn():this.#Yn()}),this.#jn.addEventListener("focusout",this.#$n);const{signal:e}=this.#zn;this.#Vn.addEventListener("keydown",e=>{switch(e.key){case"Escape":this.#Gn(),Ke(e);break;case"ArrowDown":this.#Kn(e.target,!0),Ke(e);break;case"ArrowUp":this.#Kn(e.target,!1),Ke(e);break;case"Home":this.#Fn.find(e=>!e.disabled&&!e.classList.contains("hidden"))?.focus(),Ke(e);break;case"End":this.#Fn.findLast(e=>!e.disabled&&!e.classList.contains("hidden"))?.focus(),Ke(e);break;default:const{key:t}=e;if(!/^\p{L}$/u.test(t))break;const i=t.toLocaleLowerCase();this.#Kn(e.target,!0,e=>e.textContent.trim().toLowerCase().startsWith(i)),Ke(e)}},{signal:e,capture:!0}),this.#Vn.addEventListener("contextmenu",ke,{signal:e}),this.#Vn.addEventListener("click",this.#Gn.bind(this),{signal:e,capture:!0}),this.#jn.addEventListener("keydown",e=>{switch(e.key){case" ":case"Enter":case"ArrowDown":case"Home":Ke(e),this.#Un||this.#Yn(),this.#Fn.find(e=>!e.disabled&&!e.classList.contains("hidden"))?.focus();break;case"ArrowUp":case"End":Ke(e),this.#Un||this.#Yn(),this.#Fn.findLast(e=>!e.disabled&&!e.classList.contains("hidden"))?.focus();break;case"Escape":this.#Gn(),Ke(e)}},{signal:e})}#Kn(e,t,i=()=>!0){const n=-1===this.#Hn?this.#Fn.indexOf(e):this.#Hn,s=this.#Fn.length,a=t?1:s-1;for(let e=(n+a)%s;e!==n;e=(e+a)%s){const t=this.#Fn[e];if(!t.disabled&&!t.classList.contains("hidden")&&i(t)){t.focus(),this.#Hn=e;break}}}destroy(){this.#Gn(),this.#zn?.abort(),this.#zn=null}}class cs extends os{#Zn=rs.INITIAL;constructor({container:e,eventBus:t,id:i,defaultViewport:n,optionalContentConfigPromise:s,linkService:a,renderingQueue:r,maxCanvasPixels:o,maxCanvasDim:l,pageColors:d,enableSplitMerge:h=!1}){super(),this.id=i,this.renderingId=`thumbnail${i}`,this.pageLabel=null,this.pdfPage=null,this.rotation=0,this.viewport=n,this.pdfPageRotate=n.rotation,this._optionalContentConfigPromise=s||null,this.maxCanvasPixels=o??Z.get("maxCanvasPixels"),this.maxCanvasDim=l||Z.get("maxCanvasDim"),this.pageColors=d||null,this.eventBus=t,this.linkService=a,this.renderingQueue=r,this.placeholder=null;const c=this.div=document.createElement("div");c.className="thumbnail",c.setAttribute("page-number",i);const u=this.imageContainer=document.createElement("div");c.append(u),u.classList.add("thumbnailImageContainer","missingThumbnailImage"),u.role="button",u.tabIndex=-1,u.draggable=!1,u.setAttribute("page-number",i),u.setAttribute("data-l10n-id","pdfjs-thumb-page-title1"),u.setAttribute("data-l10n-args",this.#qn(!0));const g=this.image=document.createElement("img");if(u.append(g),h){const e=this.checkbox=document.createElement("input");e.type="checkbox",e.tabIndex=-1,e.setAttribute("data-l10n-id","pdfjs-thumb-page-checkbox1"),e.setAttribute("data-l10n-args",this.#qn()),c.append(e),this.pasteButton=null}this.#Qn(),e.append(c)}clone(e,t){const i=new cs({container:e,id:t,eventBus:this.eventBus,defaultViewport:this.viewport,optionalContentConfigPromise:this._optionalContentConfigPromise,linkService:this.linkService,renderingQueue:this.renderingQueue,maxCanvasPixels:this.maxCanvasPixels,maxCanvasDim:this.maxCanvasDim,pageColors:this.pageColors,enableSplitMerge:!!this.checkbox}),{imageContainer:n}=this;return n.classList.contains("missingThumbnailImage")||(i.image.replaceWith(this.image.cloneNode(!0)),i.imageContainer.classList.remove("missingThumbnailImage")),i}addPasteButton(e){if(this.pasteButton)return;const t=this.pasteButton=document.createElement("button");t.classList.add("thumbnailPasteButton","viewsManagerButton"),t.tabIndex=0,t.setAttribute("data-l10n-id","pdfjs-views-manager-paste-button-after"),t.setAttribute("data-l10n-args",JSON.stringify({page:this.pageLabel??this.id}));const i=document.createElement("span");if(i.setAttribute("data-l10n-id","pdfjs-views-manager-paste-button-label"),t.append(i),t.addEventListener("click",()=>{e(this.id)}),1===this.id){const i=this.prevPasteButton=t.cloneNode(!0);i.setAttribute("data-l10n-id","pdfjs-views-manager-paste-button-before"),i.addEventListener("click",()=>{e(0)}),this.imageContainer.before(i)}this.imageContainer.after(t)}removePasteButton(){this.pasteButton?.remove(),this.pasteButton=null,this.prevPasteButton?.remove(),this.prevPasteButton=null}toggleSelected(e){this.checkbox&&(this.checkbox.checked=e)}updateId(e){this.id=e,this.renderingId=`thumbnail${e}`,this.div.setAttribute("page-number",e),this.imageContainer.setAttribute("page-number",e),this.setPageLabel(this.pageLabel)}#Qn(){const{width:e,height:t}=this.viewport,i=e/t,n=this.canvasWidth=126,s=this.canvasHeight=n/i|0;this.scale=n/e,this.imageContainer.style.height=`${s}px`}get renderingState(){return this.#Zn}set renderingState(e){this.#Zn=e}setPdfPage(e){this.pdfPage=e,this.pdfPageRotate=e.rotate;const t=(this.rotation+this.pdfPageRotate)%360;this.viewport=e.getViewport({scale:1,rotation:t}),this.reset()}reset(){this.cancelRendering(),this.renderingState=rs.INITIAL,this.#Qn();const{image:e,imageContainer:t}=this,i=e.src;i&&(URL.revokeObjectURL(i),e.src="",t.removeAttribute("data-l10n-id"),t.removeAttribute("data-l10n-args"),t.classList.add("missingThumbnailImage"))}destroy(){this.reset(),this.toggleCurrent(!1),this.div.remove()}update({rotation:e=null}){"number"==typeof e&&(this.rotation=e);const t=(this.rotation+this.pdfPageRotate)%360;this.viewport=this.viewport.clone({scale:1,rotation:t}),this.reset()}toggleCurrent(e){const{imageContainer:t}=this;e?(t.ariaCurrent="page",t.tabIndex=0,this.checkbox&&(this.checkbox.tabIndex=0)):(t.ariaCurrent=!1,t.tabIndex=-1,this.checkbox&&(this.checkbox.tabIndex=-1))}cancelRendering(){this.renderTask&&(this.renderTask.cancel(),this.renderTask=null),this.resume=null}#Jn(e=1){const t=new Oe,i=e*this.canvasWidth,n=e*this.canvasHeight;t.limitCanvas(i,n,this.maxCanvasPixels,this.maxCanvasDim);const s=document.createElement("canvas");s.width=i*t.sx|0,s.height=n*t.sy|0;return{canvas:s,transform:t.scaled?[t.sx,0,0,t.sy,0,0]:null}}async#es(e){if(this.renderingState!==rs.FINISHED)throw new Error("#convertCanvasToImage: Rendering has not finished.");const t=this.#ts(e),{imageContainer:i,image:n}=this,{promise:s,resolve:a}=Promise.withResolvers();t.toBlob(a);const r=await s;n.src=URL.createObjectURL(r),n.setAttribute("data-l10n-id","pdfjs-thumb-page-canvas"),n.setAttribute("data-l10n-args",this.#qn()),i.classList.remove("missingThumbnailImage")}async draw(){if(this.renderingState!==rs.INITIAL)return void console.error("Must be in new state before drawing");const{pageColors:e,pdfPage:t}=this;if(!t)throw this.renderingState=rs.FINISHED,new Error("pdfPage is not loaded");this.renderingState=rs.RUNNING;const{canvas:i,transform:n}=this.#Jn(2),s={canvas:i,transform:n,viewport:this.viewport.clone({scale:2*this.scale}),optionalContentConfigPromise:this._optionalContentConfigPromise,pageColors:e},a=this.renderTask=t.render(s);a.onContinue=e=>{if(!this.renderingQueue.isHighestPriority(this))return this.renderingState=rs.PAUSED,void(this.resume=()=>{this.renderingState=rs.RUNNING,e()});e()};let r=null;try{await a.promise}catch(e){if(e instanceof He)return;r=e}finally{a===this.renderTask&&(this.renderTask=null)}if(this.renderingState=rs.FINISHED,await this.#es(i),this.eventBus.dispatch("thumbnailrendered",{source:this,pageNumber:this.id,pdfPage:t}),r)throw r}setImage(e){if(this.renderingState!==rs.INITIAL)return;const{thumbnailCanvas:t,pdfPage:i,scale:n}=e;t&&(this.pdfPage||this.setPdfPage(i),n<this.scale||(this.renderingState=rs.FINISHED,this.#es(t)))}#is(e){const t=e.width<<3,i=e.height<<3,n=new Oe;return n.sx=n.sy=1,n.limitCanvas(t,i,this.maxCanvasPixels,this.maxCanvasDim),[t*n.sx|0,i*n.sy|0]}#ts(e){const{canvas:t}=this.#Jn(1),i=t.getContext("2d",{alpha:!1,willReadFrequently:!1});if(e.width<=2*t.width)return i.drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),t;let[n,s]=this.#is(t);const[a,r]=function(e,t){const i=new OffscreenCanvas(e,t),n=i.getContext("2d",{alpha:!1});return n.save(),n.fillStyle="rgb(255, 255, 255)",n.fillRect(0,0,e,t),n.restore(),[i,n]}(n,s);for(;n>e.width||s>e.height;)n>>=1,s>>=1;for(r.drawImage(e,0,0,e.width,e.height,0,0,n,s);n>2*t.width;)r.drawImage(a,0,0,n,s,0,0,n>>1,s>>1),n>>=1,s>>=1;return i.drawImage(a,0,0,n,s,0,0,t.width,t.height),t}#qn(e=!1){return JSON.stringify({page:this.pageLabel??this.id,total:e?this.linkService.pagesCount:void 0})}setPageLabel(e){this.pageLabel="string"==typeof e?e:null,this.imageContainer.setAttribute("data-l10n-args",this.#qn(!0)),this.image.setAttribute("data-l10n-args",this.#qn()),this.checkbox?.setAttribute("data-l10n-args",this.#qn())}}const us={behavior:"instant",block:"nearest",inline:"nearest",container:"nearest"};class gs{static#ns=0;#ss=!1;#as=!1;#rs=null;#os=void 0;#ls=!1;#ds=null;#hs=null;#cs=NaN;#us=null;#gs=0;#ps=0;#ms=0;#fs=0;#bs=0;#vs=0;#ws=null;#ys=NaN;#Cs=0;#Ps=0;#Ss=null;#Es=null;#xs=null;#Ts=null;#Ls=null;#_s=null;#Ms=null;#Is=null;#As=null;#Bs=this.#ks.bind(this);#Ds=!1;#Ns=!1;#Os=0;#Rs=0;#js=null;#Vs=null;#Fs=null;#Us=null;#zs=null;#Gt=null;#Hs=null;#$s=null;#Ws=!1;#Xs=!1;#Gs=null;constructor({container:e,eventBus:t,linkService:i,renderingQueue:n,maxCanvasPixels:s,maxCanvasDim:a,pageColors:r,abortSignal:o,enableMerge:l,enableSplitMerge:d,enableNewBadge:h,statusBar:c,undoBar:u,waitingBar:g,manageMenu:p,addFileComponent:m}){if(this.scrollableContainer=e.parentElement,this.container=e,this.eventBus=t,this.linkService=i,this.renderingQueue=n,this.maxCanvasPixels=s,this.maxCanvasDim=a,this.pageColors=r||null,this.#os=o,this.#ss=l||!1,this.#as=d||!1,this.#js=c?.viewsManagerStatusActionLabel||null,this.#Fs=c?.viewsManagerStatusActionDeselectButton||null,this.#Vs=c?.viewsManagerStatusAction||null,this.#Us=u?.viewsManagerStatusUndo||null,this.#zs=u?.viewsManagerStatusUndoLabel||null,this.#Gt=u?.viewsManagerStatusUndoButton||null,this.#Hs=u?.viewsManagerStatusUndoCloseButton||null,this.#$s=g||null,this.#as&&p){const{button:e,menu:t,copy:i,cut:n,delete:s,exportSelected:a}=p;if(h){const t=document.createElement("span");t.setAttribute("data-l10n-id","pdfjs-new-badge-content"),t.classList.add("newBadge"),e.parentElement.before(t),this.#Gs=t}if(this.eventBus.on("pagesloaded",()=>{e.disabled=!1},{once:!0}),this._manageMenu=new hs(t,e,[i,n,s,a]),this.#Es=a,a.addEventListener("click",this.#Ys.bind(this)),this.#xs=s,s.addEventListener("click",this.#Ks.bind(this,"delete")),this.#Ts=i,i.addEventListener("click",this.#Zs.bind(this)),this.#Ls=n,n.addEventListener("click",this.#qs.bind(this)),this.#Qs(!1),e.disabled=!0,this.eventBus.on("editingaction",({name:e})=>{switch(e){case"copyPage":this.#Zs();break;case"cutPage":this.#qs();break;case"deletePage":this.#Ks("delete");break;case"savePage":this.#Ys()}}),this.container.addEventListener("contextmenu",e=>{this.eventBus.dispatch("editingstateschanged",{source:this,details:{thumbnailId:parseInt(e.target.closest(".thumbnailImageContainer")?.parentElement.getAttribute("page-number"),10)??-1,hasSelectedPages:!!this.#us?.size,canDeletePages:this.#Js()}})},{signal:o,passive:!0}),this.#Gt?.addEventListener("click",this.#ea.bind(this)),this.#Hs?.addEventListener("click",this.#ta.bind(this,!0)),this.#Fs?.addEventListener("click",()=>{this.#ia(),this.#Qs(!1),this.#na("select")}),this.#Fs.classList.toggle("hidden",!0),this.#ss&&m){const{picker:e,button:t}=m;e.addEventListener("change",()=>{const t=Array.from(e.files??[]);t.length&&this.#sa(t,this._currentPageNumber-1)}),t.addEventListener("click",()=>{e.click()}),this.#$s.closeButton?.addEventListener("click",()=>{this.#aa("status"),e.value=""})}}else p.button.hidden=!0;this.scroll=w(this.scrollableContainer,this.#ra.bind(this),o),this.#oa(),this.#hi()}#ra(){this.renderingQueue.renderHighestPriority()}async#sa(e,t){this.#aa("waiting","pdfjs-views-manager-waiting-for-file");const i=[];for(const n of e){const e=n.type?.startsWith("image/");if(!e&&"application/pdf"!==n.type){if("%PDF-"!==await n.slice(0,5).text())continue}if(e){let e;try{e=await gs.#la(n)}catch{continue}i.push({image:e,insertAfter:t})}else i.push({document:await n.bytes(),insertAfter:t})}if(0===i.length)return void this.#aa("status");const n=this.#Ss.pagesNumber,s=this.hasStructuralChanges()?this.getStructuralChanges():[{document:null}];s.push(...i),this.eventBus.on("pagesloaded",()=>{this.#us=null,this.#da(),this.#aa("status");const e=this.#Ss.pagesNumber-n;for(let i=t+1,n=t+1+e;i<n;i++)this._thumbnails[i].checkbox.checked=!0,this.#ha(i+1,!0);e&&this.#ca(t+2,!0)},{once:!0,...Q}),this.#pe({action:"merge"}),this.eventBus.dispatch("saveandload",{source:this,data:s})}getThumbnail(e){return this._thumbnails[e]}#ua(){return T({scrollEl:this.scrollableContainer,views:this._thumbnails})}#ga(e){if(!this.pdfDocument)return;const t=this._thumbnails[this._currentPageNumber-1];t?.toggleCurrent(!1),this._currentPageNumber=e}scrollThumbnailIntoView(e){if(!this.pdfDocument)return;const t=this._thumbnails[e-1];if(!t)return void console.error('scrollThumbnailIntoView: Invalid "pageNumber" parameter.');e!==this._currentPageNumber&&(this.#ga(e),t.toggleCurrent(!0));const{first:i,last:n,views:s}=this.#ua();if(s.length>0){let a=!1;if(e<=i.id||e>=n.id)a=!0;else for(const{id:t,percent:i}of s)if(t===e){a=i<100;break}a&&t.div.scrollIntoView(us)}this._currentPageNumber=e}get pagesRotation(){return this._pagesRotation}set pagesRotation(e){if(!_(e))throw new Error("Invalid thumbnails rotation angle.");if(!this.pdfDocument)return;if(this._pagesRotation===e)return;this._pagesRotation=e;const t={rotation:e};for(const e of this._thumbnails)e.update(t)}cleanup(){for(const e of this._thumbnails)e.renderingState!==rs.FINISHED&&e.reset()}#oa(){this._thumbnails=[],this._currentPageNumber=1,this._pageLabels=null,this._pagesRotation=0,this.container.textContent=""}setDocument(e){if(this.pdfDocument&&(this.#pa(),this.#oa()),this.pdfDocument=e,!e)return;this.#Ss=e.pagesMapper;const t=e.getPage(1),i=e.getOptionalContentConfig({intent:"display"});t.then(t=>{const n=e.numPages,s=t.getViewport({scale:1}),a=document.createDocumentFragment();for(let e=1;e<=n;++e){const t=new cs({container:a,eventBus:this.eventBus,id:e,defaultViewport:s.clone(),optionalContentConfigPromise:i,linkService:this.linkService,renderingQueue:this.renderingQueue,maxCanvasPixels:this.maxCanvasPixels,maxCanvasDim:this.maxCanvasDim,pageColors:this.pageColors,enableSplitMerge:this.#as});this._thumbnails.push(t)}this._thumbnails[0]?.setPdfPage(t);this._thumbnails[this._currentPageNumber-1].toggleCurrent(!0),this.container.append(a),this.eventBus.dispatch("thumbnailsloaded",{source:this})}).catch(e=>{console.error("Unable to initialize thumbnail viewer",e)})}#pa(){for(const e of this._thumbnails)e.cancelRendering()}setPageLabels(e){if(this.pdfDocument){e?Array.isArray(e)&&this.pdfDocument.numPages===e.length?this._pageLabels=e:(this._pageLabels=null,console.error("PDFThumbnailViewer_setPageLabels: Invalid page labels.")):this._pageLabels=null;for(let e=0,t=this._thumbnails.length;e<t;e++)this._thumbnails[e].setPageLabel(this._pageLabels?.[e]??null)}}async#ma(e){if(e.pdfPage)return e.pdfPage;try{const t=await this.pdfDocument.getPage(e.id);return e.pdfPage||e.setPdfPage(t),t}catch(e){return console.error("Unable to get page for thumb view",e),null}}#fa(e){return 1===e.first?.id||e.last?.id!==this._thumbnails.length&&this.scroll.down}forceRendering(){const e=this.#ua(),t=this.#fa(e),i=this.renderingQueue.getHighestPriority(e,this._thumbnails,t,!1,!0);return!!i&&(this.#ma(i).then(()=>{this.renderingQueue.renderView(i)}),!0)}hasStructuralChanges(){return this.#Ss?.hasBeenAltered()||!1}getStructuralChanges(){return this.#Ss?.getPageMappingForSaving()||null}static#ba(e){return gs.#ns||=parseFloat(getComputedStyle(e).getPropertyValue("--thumbnail-dragging-scale"))}static#va(e,t,{minSide:i=0,maxSide:n}){const s=Math.max(e,t);let a=1;return i>0&&s<i?a=i/s:s>n&&(a=n/s),1===a?{width:e,height:t}:{width:Math.max(1,Math.round(e*a)),height:Math.max(1,Math.round(t*a))}}static async#la(e){const t=1024;if("image/svg+xml"!==e.type){const t=await createImageBitmap(e),{width:i,height:n}=gs.#va(t.width,t.height,{maxSide:4096});if(i===t.width&&n===t.height)return t;const s=new OffscreenCanvas(i,n);return s.getContext("2d").drawImage(t,0,0,i,n),t.close(),s.transferToImageBitmap()}const i=URL.createObjectURL(e);try{const e=new Image;e.src=i,await e.decode();const{width:n,height:s}=gs.#va(e.naturalWidth||t,e.naturalHeight||t,{minSide:t,maxSide:4096}),a=new OffscreenCanvas(n,s);return a.getContext("2d").drawImage(e,0,0,n,s),a.transferToImageBitmap()}finally{URL.revokeObjectURL(i)}}#wa(e){this.#ga(0);let t=0;const i=this.#Ss,n=this.#Ms=this._thumbnails,s=this._thumbnails=[],a=document.createDocumentFragment(),r=this.#Ds;for(let o=1,l=i.pagesNumber;o<=l;o++){const l=i.getPrevPageNumber(o);if(l<0){let e=this.#_s.get(-l);e.checkbox.checked=!1,r?(e.updateId(o),a.append(e.div)):e=e.clone(a,o),s.push(e);continue}l===e&&(t=o);const d=n[l-1];s.push(d),d.updateId(o),d.checkbox.checked=!1,a.append(d.div)}return this.container.replaceChildren(a),t}#ya(e){this.#Ps=this.scrollableContainer.scrollTop,this.#Cs=this.#Ps+this.scrollableContainer.clientHeight,this.#rs=new AbortController,this.container.classList.add("isDragging"),this.#Gs?.classList.add("hidden");const t=parseInt(e.getAttribute("page-number"),10);this.#cs=t-1,this.#us?.has(t)||(this.#ys=t,this.#ha(t,!0));for(const e of this.#us){const i=this._thumbnails[e-1],n=i.placeholder=document.createElement("div");n.classList.add("thumbnailImageContainer","placeholder");const{div:s,imageContainer:a}=i;if(s.classList.add("isDragging"),n.style.height=getComputedStyle(a).height,a.after(n),e!==t){a.classList.add("hidden");continue}if(1===this.#us.size){a.classList.add("draggingThumbnail"),this.#ds=a;continue}const r=this.#ds=document.createElement("div");r.classList.add("draggingThumbnail","thumbnailImageContainer","multiple"),r.style.height=getComputedStyle(a).height,a.replaceWith(r),a.classList.remove("thumbnailImageContainer"),r.append(a),r.setAttribute("data-multiple-count",this.#us.size)}}#Ca(e=!1){const t=this.#ds;this.#ds=null;const i=this.#cs;this.#cs=NaN,this.#ws?.remove(),this.#ws=null,this.#rs.abort(),this.#rs=null,this.#Gs?.classList.remove("hidden"),this.container.classList.remove("isDragging");for(const e of this.#us){const t=this._thumbnails[e-1],{div:i,placeholder:n,imageContainer:s}=t;n.remove(),s.classList.remove("draggingThumbnail","hidden"),i.classList.remove("isDragging")}if(t.classList.contains("multiple")){const e=t.firstElementChild;t.replaceWith(e),e.classList.add("thumbnailImageContainer")}else t.style.translate="";const n=this.#us;if(!isNaN(i)&&e&&(1!==n.size||!n.has(i+1)&&!n.has(i+2))){this._thumbnails[this._currentPageNumber-1]?.toggleCurrent(!1),this._currentPageNumber=-1;const e=i+1,t=Array.from(n).sort((e,t)=>e-t),s=this.#Ss,a=isNaN(this.#ys)?t[0]:this.#ys;s.movePages(n,t,e),this.#ca(this.#wa(a)),this.#hs=null,n.clear(),this.#ys=NaN,this.#Qs(!1),this.#na("select"),this.#pe({action:"move"}),this.eventBus.dispatch("pagesedited",{source:this,pagesMapper:s,type:"move"})}isNaN(this.#ys)||(this.#ha(this.#ys,!1),this.#ys=NaN)}#ia(){for(const e of this.#us)this._thumbnails[e-1].toggleSelected(!1);this.#us.clear()}#ca(e,t=!1){setTimeout(()=>{this.forceRendering();const i=e||1;this.linkService.goToPage(i);const n=this._thumbnails[i-1];!t&&this.container.contains(document.activeElement)||n.imageContainer.focus()},0)}#ea(){if(this.#ia(),this.#Qs(!1),this.#na("select"),this.#_s&&(this.#_s=null,this.#Ss.cancelCopy(),this.#Pa(!1),this.eventBus.dispatch("pagesedited",{source:this,pagesMapper:this.#Ss,type:"cancelCopy"})),this.#Ds=!1,this.#Ms){const e=this._thumbnails[this._currentPageNumber-1];e?.toggleCurrent(!1);const t=document.createDocumentFragment();for(let e=1,i=this.#Ms.length;e<=i;e++){const i=this.#Ms[e-1];i.updateId(e),i.checkbox.checked=!1,t.append(i.div)}this.container.replaceChildren(t),this._thumbnails=this.#Ms,this.#Ms=null;const i=e?this._thumbnails.indexOf(e):-1;this._currentPageNumber=i+1,e?.toggleCurrent(-1!==i),this.#Ss.cancelDelete(),this.eventBus.dispatch("pagesedited",{source:this,pagesMapper:this.#Ss,type:"cancelDelete"})}}#ta(e){if(this.#_s=null,this.#Is){if(this.#Ms){for(const e of this.#Is)this.#Ms[e-1].destroy();this.#Ms=null}this.#Is=null}this.#Ds=!1,e&&this.#na("select"),this.#Pa(!1),this.#Ss.cleanSavedData(),this.eventBus.dispatch("pagesedited",{source:this,pagesMapper:this.#Ss,type:"cleanSavedData"})}#Js(){const e=this.#us?.size||0;return e>0&&e<this._thumbnails.length}#aa(e,t,i){switch(this.#Vs.classList.toggle("hidden","status"!==e),this.#$s.container.classList.toggle("hidden","waiting"!==e),this.#Us.classList.toggle("hidden","undo"!==e),this.#Xs="undo"===e,e){case"waiting":this.#$s.label.setAttribute("data-l10n-id",t);break;case"undo":this.#zs.setAttribute("data-l10n-id",t),i&&this.#zs.setAttribute("data-l10n-args",JSON.stringify(i));break;case"status":i?this.#js.setAttribute("data-l10n-args",JSON.stringify(i)):this.#js.removeAttribute("data-l10n-args"),this.#Gs?.classList.toggle("hidden",!!i),this.#Fs.classList.toggle("hidden",!i)}}#Pa(e){if(this.#Ws=e,e){this.container.classList.add("pasteMode");for(const e of this._thumbnails)e.addPasteButton(this.#Bs)}else{this.container.classList.remove("pasteMode");for(const e of this._thumbnails)e.removePasteButton()}}#pe(e){this.eventBus.dispatch("reporttelemetry",{source:this,details:{type:"pageOrganization",data:e}})}#Ys(){this.#pe({action:"exportSelected"}),this.eventBus.dispatch("saveextractedpages",{source:this,data:this.#Ss.extractPages(this.#us)}),this.#ia(),this.#Qs(!1),this.#na("select")}#Zs(e=!0){this.#Ds||(this.#Ms=null,this.#pe({action:"copy"})),this.#na(this.#Ds?"cut":"copy");const t=this.#As=Uint32Array.from(this.#us).sort((e,t)=>e-t),i=this.#Ss;i.copyPages(t),this.#_s=new Map;for(const e of t)this.#_s.set(e,this._thumbnails[e-1]);this.eventBus.dispatch("pagesedited",{source:this,pagesMapper:i,pageNumbers:t,type:"copy"}),e&&this.#ia(),this.#Pa(!0),this.#Qs(!1)}#qs(){this.#Js()&&(this.#pe({action:"cut"}),this.#Ds=!0,this.#Zs(!1),this.#Ks("cut"))}#ks(e){this.#pe({action:"paste"});const t=this.#Ss,i=this.#As.includes(this._currentPageNumber)?0:this._currentPageNumber;t.pastePages(e),this.#wa(i),this.#ca(e+1,!0),this.#hs=null,this.eventBus.dispatch("pagesedited",{source:this,pagesMapper:t,hasBeenCut:this.#Ds,type:"paste"}),this.#_s=null,this.#Ds=!1,this.#Pa(!1),this.#Qs(!1),this.#na("select")}#Ks(e="delete"){if(!this.#Js())return;const t=this.#us;"delete"===e&&(this.#pe({action:"delete"}),this.#na("delete"));const i=this.#Ss,n=t.has(this._currentPageNumber)?0:this._currentPageNumber,s=this.#Is=Uint32Array.from(t).sort((e,t)=>e-t);i.deletePages(s),this.#ca(this.#wa(n)),this.#hs=null,t.clear(),this.#da(),this.eventBus.dispatch("pagesedited",{source:this,pagesMapper:i,pageNumbers:s,type:e})}#da(){const e=this.#us?.size||0;this.#Es.disabled=this.#Ts.disabled=!e,this.#xs.disabled=this.#Ls.disabled=!this.#Js()}#Qs(e){this.#Es.disabled=this.#xs.disabled=this.#Ts.disabled=this.#Ls.disabled=!e}#na(e){if(!this.#Vs||!this.#Us)return;const t=this.#us?.size||0;if("select"===e)return this.#js.setAttribute("data-l10n-id",t?"pdfjs-views-manager-pages-status-action-label":"pdfjs-views-manager-pages-status-none-action-label"),void this.#aa("status","",t?{count:t}:null);let i;switch(e){case"copy":i="pdfjs-views-manager-pages-status-undo-copy-label";break;case"cut":i="pdfjs-views-manager-status-undo-cut-label";break;case"delete":i="pdfjs-views-manager-pages-status-undo-delete-label"}this.#aa("undo",i,{count:t}),"copy"===e?(this.#Gt.firstElementChild.setAttribute("data-l10n-id","pdfjs-views-manager-status-done-button-label"),this.#Hs.classList.toggle("hidden",!0)):(this.#Gt.firstElementChild.setAttribute("data-l10n-id","pdfjs-views-manager-status-undo-button-label"),this.#Hs.classList.toggle("hidden",!1))}#Sa(e,t){this.#Ns&&(e=0),(this.#gs+e<0||this.#gs+this.#ms+e>this.#Os)&&(e=0),(this.#ps+t<0||this.#ps+this.#fs+t>this.#Rs)&&(t=0),this.#gs+=e,this.#ps+=t,this.#bs+=e,this.#vs+=t,this.#ds.style.translate=`${this.#bs}px ${this.#vs}px`,this.#ps+this.#fs>this.#Cs?this.scrollableContainer.scrollTop=Math.min(this.scrollableContainer.scrollTop+20,this.#Rs):this.#ps<this.#Ps&&(this.scrollableContainer.scrollTop=Math.max(this.scrollableContainer.scrollTop-20,0));const i=this.#Ea(this.#gs+this.#ms/2,this.#ps+this.#fs/2);this.#xa(i)}#xa(e){if(!e)return;let t=this.#ws;t||(t=this.#ws=document.createElement("div"),t.className="dragMarker",this.container.firstChild.before(t));const[i,n]=e,s=t.style,{bbox:a,x:r}=this.#hs;let o,l,d,h;i<0?1===r.length?(l=a[1]-15,o=a[0],d=a[2]):(l=a[1],o=a[0]-15,h=a[3]):1===r.length?(l=a[4*i+1]+a[4*i+3]+n,o=a[4*i],d=a[4*i+2]):(l=a[4*i+1],o=a[4*i]+a[4*i+2]+n,h=a[4*i+3]),s.translate=`${o}px ${l}px`,s.width=d?`${d}px`:"",s.height=h?`${h}px`:""}#Ta(){const e=[],t=[],i=[],n=new Float32Array(4*this._thumbnails.length);let s,a,r,o,l=-1/0,d=-1/0,h=-1;for(let o=0,c=this._thumbnails.length;o<c;o++){const{div:u}=this._thumbnails[o],{offsetTop:g,offsetLeft:p,offsetWidth:m,offsetHeight:f}=u;if(0===m)return;if(n[4*o]=p,n[4*o+1]=g,n[4*o+2]=m,n[4*o+3]=f,p>l&&(l=p+m/2,s??=l+m,e.push(l)),g>d&&(-1===h&&e.length>1&&(h=c%e.length),d=g+f/2,r??=d+f,t.push(d)),h>0&&o>=c-h){const e=p+m/2;i.push(e),a??=e+m}}o=e.length>1?(e[1]-s)/2:t.length>1?(t[1]-r)/2:15,this.#hs={x:e,y:t,lastX:i,space:o,lastSpace:i.length?(i.at(-1)-a)/2:o,bbox:n},this.#Ns=1===e.length,({clientWidth:this.#Os,scrollHeight:this.#Rs}=this.scrollableContainer)}#hi(){this.eventBus.on("resize",({source:e})=>{e.thumbnailsView===this.container&&this.#Ta()}),this.container.addEventListener("keydown",e=>{const{target:t}=e,i=t instanceof HTMLInputElement&&"checkbox"===t.type;switch(e.key){case"ArrowLeft":this.#Kn(t,!1,!0,i),Ke(e);break;case"ArrowRight":this.#Kn(t,!0,!0,i),Ke(e);break;case"ArrowDown":this.#Kn(t,!0,!1,i),Ke(e);break;case"ArrowUp":this.#Kn(t,!1,!1,i),Ke(e);break;case"Home":this.#La(this._thumbnails[0],i),Ke(e);break;case"End":this.#La(this._thumbnails.at(-1),i),Ke(e);break;case"Enter":case" ":i||this.#_a(e);break;case"c":this.#as&&(e.ctrlKey||e.metaKey)&&this.#us?.size&&(this.#Zs(),Ke(e));break;case"x":this.#as&&(e.ctrlKey||e.metaKey)&&this.#us?.size&&(this.#qs(),Ke(e));break;case"Delete":case"Backspace":this.#as&&!this.#Ws&&this.#us?.size&&(this.#Ks(),Ke(e))}}),this.container.addEventListener("click",e=>{const{target:t}=e;if(t instanceof HTMLInputElement){const e=parseInt(t.parentElement.getAttribute("page-number"),10);return void this.#ha(e,t.checked)}this.#_a(e)}),this.#Ma(),this.#Ia()}#ha(e,t){this.#Xs&&this.#ta(!1);const i=this.#us??=new Set;t?i.add(e):i.delete(e),this.#da(),this.#na("select")}#Ma(){this.#as&&this.container.addEventListener("pointerdown",e=>{const{target:t,clientX:i,clientY:n,pointerId:s}=e;if(0!==e.button||this.#Ws||1===this._thumbnails.length||!isNaN(this.#cs)||!t.classList.contains("thumbnailImageContainer"))return;const a=t.parentElement,r=new AbortController,{signal:o}=r;let l=i,d=n,h=this.scrollableContainer.scrollTop;const c=gs.#ba(t);this.#vs=((c-1)*e.layerY+t.offsetTop)/c,this.#Ns?this.#bs=t.offsetLeft+.5*(c-1)*t.offsetWidth/c:this.#bs=((c-1)*e.layerX+t.offsetLeft)/c,this.#gs=a.offsetLeft+this.#bs,this.#ps=a.offsetTop+this.#vs,this.#ms=t.offsetWidth/c,this.#fs=t.offsetHeight/c,this.container.addEventListener("pointermove",e=>{const{clientX:t,clientY:o,pointerId:c}=e;if(isNaN(this.#cs)){if(c!==s||Math.abs(t-i)<=5&&Math.abs(o-n)<=5)return;this.#ya(a);const e=(e,t=!1)=>{this.#Ca(t),r.abort()},{signal:l}=this.#rs;window.addEventListener("touchmove",Ke,{passive:!1,signal:l}),window.addEventListener("contextmenu",ke,{signal:l}),this.scrollableContainer.addEventListener("scrollend",()=>{const{scrollableContainer:{clientHeight:e,scrollTop:t}}=this;this.#Ps=t,this.#Cs=t+e;const i=t-h;h=t,this.#Sa(0,i)},{passive:!0,signal:l}),window.addEventListener("pointerup",t=>{t.pointerId===s&&(window.addEventListener("click",Ke,{capture:!0,once:!0,signal:l}),Ke(t),e(t,!0))},{signal:l}),window.addEventListener("blur",e,{signal:l}),window.addEventListener("pointercancel",e,{signal:l}),window.addEventListener("wheel",Ke,{passive:!1,signal:l}),window.addEventListener("keydown",t=>{"Escape"!==t.key||isNaN(this.#cs)||e(t)},{signal:l})}const u=t-l,g=o-d;l=t,d=o,this.#Sa(u,g)},{passive:!0,signal:o}),window.addEventListener("pointerup",({pointerId:e})=>{e===s&&r.abort()},{signal:o}),window.addEventListener("dragstart",Ke,{capture:!0,signal:o})})}#Ia(){if(!this.#ss)return;const e=this.container,t=this.#os;e.addEventListener("dragenter",e=>{!this.#ls&&isNaN(this.#cs)&&this._thumbnails.length&&(e=>{if(!e)return!1;for(const t of e.items)if("file"===t.kind&&("application/pdf"===t.type||t.type.startsWith("image/")))return!0;return!1})(e.dataTransfer)&&(e.preventDefault(),e.stopPropagation(),e.dataTransfer.dropEffect="copy",this.#ls=!0,this.container.classList.add("isDraggingFile"),this.#hs=null,this.#Ta(),this.#cs=NaN)},{signal:t}),e.addEventListener("dragover",t=>{if(!this.#ls)return;if(t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect="copy",!this.#hs)return;const i=e.getBoundingClientRect(),n=t.clientX-i.left,s=t.clientY-i.top,a=this.#Ea(n,s);this.#xa(a)},{signal:t}),e.addEventListener("dragleave",t=>{this.#ls&&(t.relatedTarget&&e.contains(t.relatedTarget)||(({clientX:t,clientY:i})=>{const{left:n,right:s,top:a,bottom:r}=e.getBoundingClientRect();return t>=n&&t<s&&i>=a&&i<r})(t)||this.#Aa())},{signal:t}),e.addEventListener("drop",t=>{if(!this.#ls)return;t.preventDefault(),t.stopPropagation();const i=Array.from(t.dataTransfer.files??[]);if(isNaN(this.#cs)&&this.#hs){const i=e.getBoundingClientRect();this.#Ea(t.clientX-i.left,t.clientY-i.top)}const n=isNaN(this.#cs)?-1:this.#cs;this.#Aa(),i.length&&this.#sa(i,n)},{signal:t})}#Aa(){this.#ls=!1,this.container.classList.remove("isDraggingFile"),this.#ws?.remove(),this.#ws=null,this.#cs=NaN}#_a(e){const t=e.target.closest(".thumbnailImageContainer");if(t){const i=parseInt(t.getAttribute("page-number"),10);this.linkService.goToPage(i),Ke(e)}}#La(e,t){t&&e.checkbox?e.checkbox.focus():e.imageContainer.focus()}#Kn(e,t,i,n=!1){let s=parseInt(e.parentElement.getAttribute("page-number"),10);isNaN(s)&&(s=this._currentPageNumber);const a=t?1:-1;let r;if(i){const e=Be(s+a,1,this._thumbnails.length+1);r=this._thumbnails[e-1]}else{const e=this._thumbnails[s-1],{x:t,y:i}=e.div.getBoundingClientRect();let n;for(let e=s-1+a;e>=0&&e<this._thumbnails.length;e+=a){const s=this._thumbnails[e],{x:a,y:o}=s.div.getBoundingClientRect();if(n||o===i||(n=s),a===t){r=s;break}}r||(r=n)}r&&this.#La(r,n)}#Ea(e,t){this.#hs||this.#Ta();const{x:i,y:n,lastX:s,space:a,lastSpace:r}=this.#hs,o=this.#cs;let l,d=o%i.length,h=Math.floor(o/i.length),c=h===n.length-1?s:i;if(n[h]<=t&&t<(n[h+1]??1/0)&&c[d]<=e&&e<(c[d+1]??1/0))return null;if(h=S(n,e=>t<e),this.#Ns)l=h-1;else{if(h===n.length)h=n.length-1;else{h=Math.abs(n[h-1]-t)<Math.abs(n[h]-t)?h-1:h}c=h===n.length-1&&s.length>0?s:i,d=S(c,t=>e<t)-1,h<0&&(d<=0&&(d=-1),h=0),l=Be(h*i.length+d,-1,this._thumbnails.length-1)}if(l===o)return null;this.#cs=l;return[l,h===n.length-1&&s.length>0&&d>=0?r:a]}}class ps{#Ba=null;#ka=null;#Da=null;#Na=null;#Oa=null;#G;constructor(e){this.pageIndex=e.pageIndex,this.accessibilityManager=e.accessibilityManager,this.l10n=e.l10n,this.l10n||=new Mi,this.annotationEditorLayer=null,this.div=null,this._cancelled=!1,this.#G=e.uiManager,this.#Ba=e.annotationLayer||null,this.#Oa=e.textLayer||null,this.#ka=e.drawLayer||null,this.#Da=e.onAppend||null,this.#Na=e.structTreeLayer||null}updatePageIndex(e){this.pageIndex=e,this.annotationEditorLayer?.updatePageIndex(e)}async render({viewport:e,intent:t="display"}){if("display"!==t)return;if(this._cancelled)return;const i=e.clone({dontFlip:!0});if(this.div)return this.annotationEditorLayer.update({viewport:i}),void this.show();const n=this.div=document.createElement("div");n.className="annotationEditorLayer",n.hidden=!0,n.dir=this.#G.direction,this.#Da?.(n),this.annotationEditorLayer=new ee({uiManager:this.#G,div:n,structTreeLayer:this.#Na,accessibilityManager:this.accessibilityManager,pageIndex:this.pageIndex,l10n:this.l10n,viewport:i,annotationLayer:this.#Ba,textLayer:this.#Oa,drawLayer:this.#ka});const s={viewport:i,div:n,annotations:null,intent:t};await this.annotationEditorLayer.render(s),this.show()}cancel(){this._cancelled=!0,this.div&&this.annotationEditorLayer.destroy()}hide(){this.div&&(this.annotationEditorLayer.pause(!0),this.div.hidden=!0)}show(){this.div&&!this.annotationEditorLayer.isInvisible&&(this.div.hidden=!1,this.annotationEditorLayer.pause(!1))}}class ms{#it=null;#Ra=null;#ja=!1;#Da=null;#$i=null;#Va=!1;constructor({pdfPage:e,linkService:t,downloadManager:i,annotationStorage:n=null,imageResourcesPath:s="",renderForms:a=!0,enableComment:r=!1,commentManager:o=null,enableScripting:l=!1,hasJSActionsPromise:d=null,fieldObjectsPromise:h=null,annotationCanvasMap:c=null,accessibilityManager:u=null,annotationEditorUIManager:g=null,onAppend:p=null}){this.pdfPage=e,this.linkService=t,this.downloadManager=i,this.imageResourcesPath=s,this.renderForms=a,this.annotationStorage=n,this.enableComment=r,this.#Ra=o,this.enableScripting=l,this._hasJSActionsPromise=d||Promise.resolve(!1),this._fieldObjectsPromise=h||Promise.resolve(null),this._annotationCanvasMap=c,this._accessibilityManager=u,this._annotationEditorUIManager=g,this.#Da=p,this.annotationLayer=null,this.div=null,this._cancelled=!1,this._eventBus=t.eventBus}async render({viewport:e,intent:t="display",structTreeLayer:i=null,optionalContentConfigPromise:n=null}){if(this.div){const t=await n;if(this._cancelled||!this.annotationLayer)return;return void this.annotationLayer.update({viewport:e.clone({dontFlip:!0}),optionalContentConfig:t})}const[a,r,o,l]=await Promise.all([this.pdfPage.getAnnotations({intent:t}),this._hasJSActionsPromise,this._fieldObjectsPromise,n]);if(this._cancelled)return;const d=this.div=document.createElement("div");if(d.className="annotationLayer",this.#Da?.(d),this.#Fa(e,i),0===a.length)return this.#it=a,void Xe(this.div,e);await this.annotationLayer.render({annotations:a,imageResourcesPath:this.imageResourcesPath,renderForms:this.renderForms,downloadManager:this.downloadManager,enableComment:this.enableComment,enableScripting:this.enableScripting,hasJSActions:r,fieldObjects:o,optionalContentConfig:l}),this.#it=a,this.linkService.isInPresentationMode&&this.#Ua(s),this.#$i||(this.#$i=new AbortController,this._eventBus?.on("presentationmodechanged",e=>{this.#Ua(e.state)},{signal:this.#$i.signal,...Q}))}#Fa(e,t){this.annotationLayer=new se({div:this.div,accessibilityManager:this._accessibilityManager,annotationCanvasMap:this._annotationCanvasMap,annotationEditorUIManager:this._annotationEditorUIManager,annotationStorage:this.annotationStorage,page:this.pdfPage,viewport:e.clone({dontFlip:!0}),structTreeLayer:t,commentManager:this.#Ra,linkService:this.linkService})}cancel(){this._cancelled=!0,this.#$i?.abort(),this.#$i=null}hide(e=!1){this.#ja=!e,this.div&&(this.div.hidden=!0)}hasEditableAnnotations(){return!!this.annotationLayer?.hasEditableAnnotations()}async injectLinkAnnotations(e){if(null===this.#it)throw new Error("`render` method must be called before `injectLinkAnnotations`.");if(this._cancelled||this.#Va)return;this.#Va=!0;const t=this.#it.length?this.#za(e):e;t.length&&(await this.annotationLayer.addLinkAnnotations(t),this.#ja||(this.div.hidden=!1))}#Ua(e){if(!this.div)return;let t=!1;switch(e){case s:t=!0;break;case i:break;default:return}for(const e of this.div.childNodes)e.hasAttribute("data-internal-link")||(e.inert=t)}#za(e){function t(e){if(!e.quadPoints)return[e.rect];const t=[];for(let i=2,n=e.quadPoints.length;i<n;i+=8){const n=e.quadPoints[i],s=e.quadPoints[i+1],a=e.quadPoints[i+2],r=e.quadPoints[i+3];t.push([a,r,n,s])}return t}function i(e,i){const n=[],s=t(e),a=t(i);for(const e of s)for(const t of a){const i=tt.intersect(e,t);i&&n.push(i)}return n}function n(e){let t=0;for(const i of e)t+=Math.abs((i[2]-i[0])*(i[3]-i[1]));return t}return e.filter(e=>{let s;for(const a of this.#it){if(a.annotationType!==re.LINK||!a.url)continue;const r=i(a,e);if(0!==r.length&&(s??=n(t(e)),n(r)/s>.5))return!1}return!0})}}function fs({width:e,height:t,left:i,top:n},s){if(0===e||0===t)return null;const a=s.textLayer.div.getBoundingClientRect(),r=s.getPagePoint(i-a.left,n-a.top),o=s.getPagePoint(i-a.left+e,n-a.top+t);return tt.normalizeRect([r[0],r[1],o[0],o[1]])}function bs(e,t){const i=e.getClientRects();if(1===i.length)return{rect:fs(i[0],t)};const n=[1/0,1/0,-1/0,-1/0],s=[];let a=0;for(const e of i){const i=fs(e,t);null!==i&&(s[a]=s[a+4]=i[0],s[a+1]=s[a+3]=i[3],s[a+2]=s[a+6]=i[2],s[a+5]=s[a+7]=i[1],tt.rectBoundingBox(...i,n),a+=8)}return{quadPoints:s,rect:n}}function vs(e,t){let i=e;do{if(i.nodeType===Node.TEXT_NODE){const e=i.textContent.length;if(t<=e)return[i,t];t-=e}else if(i.firstChild){i=i.firstChild;continue}for(;!i.nextSibling&&i!==e;)i=i.parentNode;i!==e&&(i=i.nextSibling)}while(i!==e);throw new Error("Offset is bigger than container's contents length.")}class ws{static#Ha=0;static#$a;static#Wa;static findLinks(e){this.#$a??=/\b(?:https?:\/\/|mailto:|www\.)(?:[\S--[\p{P}<>]]|\/|[\S--[\[\]]]+[\S--[\p{P}<>]])+|(?=\p{L})[\S--[@\p{Ps}\p{Pe}<>]]+@([\S--[[\p{P}--\-]<>]]+(?:\.[\S--[[\p{P}--\-]<>]]+)+)/gv;const[t,i]=Dn(e,{ignoreDashEOL:!0}),n=t.matchAll(this.#$a),s=[];for(const e of n){const[t,n]=e;let a;if(t.startsWith("www.")||t.startsWith("http://")||t.startsWith("https://"))a=t;else if(n){const e=URL.parse(`http://${n}`)?.hostname;if(!e)continue;if(this.#Wa??=/\.\d+$/,this.#Wa.test(e))continue}a??=t.startsWith("mailto:")?t:`mailto:${t}`;const r=he(a,null,{addDefaultProtocol:!0});if(r){const[n,a]=Nn(i,e.index,t.length);s.push({url:r.href,index:n,length:a})}}return s}static processLinks(e){return this.findLinks(e._textHighlighter.textContentItemsStr.join("\n")).map(t=>function({url:e,index:t,length:i},n,s){const a=n._textHighlighter,[{begin:r,end:o}]=a._convertMatches([t],[i]),l=new Range;return l.setStart(...vs(a.textDivs[r.divIdx],r.offset)),l.setEnd(...vs(a.textDivs[o.divIdx],o.offset)),{id:`inferred_link_${s}`,unsafeUrl:e,url:e,annotationType:re.LINK,rotation:0,...bs(l,n),borderStyle:null}}(t,e,this.#Ha++))}}class ys extends os{#Xa=null;#Ga=null;#Zn=rs.INITIAL;#Ya=null;#Ka=0;#Za=null;canvas=null;div=null;enableOptimizedPartialRendering=!1;enableSelectionRendering=!0;imagesRightClickMinSize=-1;eventBus=null;id=null;imageCoordinates=null;pageColors=null;recordedBBoxes=null;renderingQueue=null;constructor(e){super(),this.eventBus=e.eventBus,this.id=e.id,this.pageColors=e.pageColors||null,this.renderingQueue=e.renderingQueue,this.enableOptimizedPartialRendering=e.enableOptimizedPartialRendering??!1,this.enableSelectionRendering=!1!==e.enableSelectionRendering,this.imagesRightClickMinSize=e.imagesRightClickMinSize??-1,this.minDurationToUpdateCanvas=e.minDurationToUpdateCanvas??500}get renderingState(){return this.#Zn}set renderingState(e){if(e!==this.#Zn)switch(this.#Zn=e,this.#Xa&&(clearTimeout(this.#Xa),this.#Xa=null),e){case rs.PAUSED:this.div.classList.remove("loading"),this.#Ka=0,this.#Ya?.(!1);break;case rs.RUNNING:this.div.classList.add("loadingIcon"),this.#Xa=setTimeout(()=>{this.div.classList.add("loading"),this.#Xa=null},0),this.#Ka=Date.now();break;case rs.INITIAL:case rs.FINISHED:this.div.classList.remove("loadingIcon","loading"),this.#Ka=0}}_createCanvas(e,t=!1){const{pageColors:i}=this,n=!(!i?.background||!i?.foreground),s=this.canvas,a=!s&&!n&&!t;let r=this.canvas=document.createElement("canvas");return this.#Ya=t=>{if(a){let i=this.#Za;if(!t&&this.minDurationToUpdateCanvas>0){if(Date.now()-this.#Ka<this.minDurationToUpdateCanvas)return;i||(i=this.#Za=r,r=this.canvas=r.cloneNode(!1),e(r))}if(i){return r.getContext("2d",{alpha:!1}).drawImage(i,0,0),void(t?this.#qa():this.#Ka=Date.now())}return e(r),void(this.#Ya=null)}t&&(s?(s.replaceWith(r),s.width=s.height=0):e(r))},{canvas:r,prevCanvas:s}}#Qa=e=>{if(this.#Ya?.(!1),this.renderingQueue&&!this.renderingQueue.isHighestPriority(this))return this.renderingState=rs.PAUSED,void(this.resume=()=>{this.renderingState=rs.RUNNING,e()});e()};_resetCanvas(){const{canvas:e}=this;e&&(e.remove(),e.width=e.height=0,this.canvas=null,this.#qa())}#qa(){this.#Za&&(this.#Za.width=this.#Za.height=0,this.#Za=null)}async _drawCanvas(e,t,i){const n=this.renderTask=this.pdfPage.render(e);n.onContinue=this.#Qa,n.onError=e=>{e instanceof He&&(t(),this.#Ga=null)};let s=null;try{await n.promise,this.#Ya?.(!0)}catch(e){if(e instanceof He)return;s=e,this.#Ya?.(!0)}finally{this.#Ga=s,n===this.renderTask&&(this.renderTask=null,this.enableOptimizedPartialRendering&&(this.recordedBBoxes??=n.recordedBBoxes),-1!==this.imagesRightClickMinSize&&(this.imageCoordinates??=this.pdfPage.imageCoordinates))}if(this.renderingState=rs.FINISHED,i(n),s)throw s}cancelRendering({cancelExtraDelay:e=0}={}){this.renderTask&&(this.renderTask.cancel(e),this.renderTask=null),this.resume=null}dispatchPageRender(){this.eventBus.dispatch("pagerender",{source:this,pageNumber:this.id})}dispatchPageRendered(e,t){this.eventBus.dispatch("pagerendered",{source:this,pageNumber:this.id,cssTransform:e,isDetailView:t,timestamp:performance.now(),error:this.#Ga})}}class Cs{#ka=null;constructor(e){this.pageIndex=e.pageIndex,this.textLayer=e.textLayer||null,this.filterFactory=e.filterFactory||null,this.pageColors=e.pageColors||null}async render({intent:e="display"}){"display"!==e||this.#ka||this._cancelled||(this.#ka=new ge({pageIndex:this.pageIndex,textLayer:this.textLayer,filterFactory:this.filterFactory,pageColors:this.pageColors}))}cancel(){this._cancelled=!0,this.#ka&&(this.#ka.destroy(),this.#ka=null)}setParent(e){this.#ka?.setParent(e)}getDrawLayer(){return this.#ka}}class Ps extends ys{#Ja=null;renderingCancelled=!1;constructor({pageView:e}){super(e),this.pageView=e,this.renderingId="detail"+this.id,this.div=e.div}setPdfPage(e){this.pageView.setPdfPage(e)}get pdfPage(){return this.pageView.pdfPage}get renderingState(){return super.renderingState}set renderingState(e){this.renderingCancelled=!1,super.renderingState=e}reset({keepCanvas:e=!1}={}){const t=this.renderingCancelled||this.renderingState===rs.RUNNING||this.renderingState===rs.PAUSED;this.cancelRendering(),this.renderingState=rs.INITIAL,this.renderingCancelled=t,e||this._resetCanvas()}#er(e){if(!this.#Ja)return!0;const t=this.#Ja.minX,i=this.#Ja.minY,n=this.#Ja.width+t,s=this.#Ja.height+i;if(e.minX<t||e.minY<i||e.maxX>n||e.maxY>s)return!0;const{width:a,height:r,scale:o}=this.pageView.viewport;if(this.#Ja.scale!==o)return!0;const l=e.minX-t,d=n-e.maxX,h=e.minY-i,c=s-e.maxY;return t>0&&d/l>3||n<a&&l/d>3||i>0&&c/h>3||s<r&&h/c>3}update({visibleArea:e=null,underlyingViewUpdated:t=!1}={}){if(t)return this.cancelRendering(),void(this.renderingState=rs.INITIAL);if(!this.#er(e))return;const{viewport:i,maxCanvasPixels:n,capCanvasAreaFactor:s}=this.pageView,a=e.maxX-e.minX,r=e.maxY-e.minY,o=a*r*Oe.pixelRatio**2,l=(Math.sqrt(Oe.capPixels(n,s)/o)-1)/2;let d=Math.min(1,l);d<0&&(d=0);const h=a*d,c=r*d,u=Math.max(0,e.minX-h),g=Math.min(i.width,e.maxX+h),p=Math.max(0,e.minY-c),m=g-u,f=Math.min(i.height,e.maxY+c)-p;this.#Ja={minX:u,minY:p,width:m,height:f,scale:i.scale},this.reset({keepCanvas:!0})}_getRenderingContext(e,t){const i=this.pageView._getRenderingContext(e,t,!1),n=this.pdfPage.recordedBBoxes;if(!n||!this.enableOptimizedPartialRendering)return i;const{viewport:{width:s,height:a}}=this.pageView,{width:r,height:o,minX:l,minY:d}=this.#Ja,h=l/s,c=d/a,u=(l+r)/s,g=(d+o)/a;return{...i,operationsFilter:e=>!n.isEmpty(e)&&(n.minX(e)<=u&&n.maxX(e)>=h&&n.minY(e)<=g&&n.maxY(e)>=c)}}async draw(){if(this.pageView.detailView!==this)return;const e=this.pageView.renderingState===rs.FINISHED||this.renderingState===rs.FINISHED;this.renderingState!==rs.INITIAL&&(console.error("Must be in new state before drawing"),this.reset());const{div:t,pdfPage:i,viewport:n}=this.pageView;if(!i)throw this.renderingState=rs.FINISHED,new Error("pdfPage is not loaded");this.renderingState=rs.RUNNING;const s=this.pageView._ensureCanvasWrapper(),{canvas:a,prevCanvas:r}=this._createCanvas(e=>{"CANVAS"===s.firstElementChild?.tagName?s.firstElementChild.after(e):s.prepend(e)},e);a.ariaHidden=!0,this.enableOptimizedPartialRendering&&(a.className="detailView");const{width:o,height:l}=n,d=this.#Ja,{pixelRatio:h}=Oe,c=[h,0,0,h,-d.minX*h,-d.minY*h];a.width=d.width*h,a.height=d.height*h;const{style:u}=a;u.width=100*d.width/o+"%",u.height=100*d.height/l+"%",u.top=100*d.minY/l+"%",u.left=100*d.minX/o+"%";const g=this._drawCanvas(this._getRenderingContext(a,c),()=>{this.canvas?.remove(),this.canvas=r},()=>{this.dispatchPageRendered(!1,!0)});return t.setAttribute("data-loaded",!0),this.dispatchPageRender(),g}}const Ss={Document:null,DocumentFragment:null,Part:"group",Sect:"group",Div:"group",Aside:"note",NonStruct:"none",P:null,H:"heading",Title:null,FENote:"note",Sub:"group",Lbl:null,Span:null,Em:null,Strong:null,Link:"link",Annot:"note",Form:"form",Ruby:null,RB:null,RT:null,RP:null,Warichu:null,WT:null,WP:null,L:"list",LI:"listitem",LBody:null,Table:"table",TR:"row",TH:"columnheader",TD:"cell",THead:"rowgroup",TBody:"rowgroup",TFoot:null,Caption:null,Figure:"figure",Formula:null,Artifact:null},Es=new Set(["math","merror","mfrac","mi","mmultiscripts","mn","mo","mover","mpadded","mprescripts","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msubsup","msup","mtable","mtd","mtext","mtr","munder","munderover","semantics"]),xs="http://www.w3.org/1998/Math/MathML";class Ts{static get sanitizer(){return Ge(this,"sanitizer",pe.isSanitizerSupported?new Sanitizer({elements:[...Es].map(e=>({name:e,namespace:xs})),replaceWithChildrenElements:[{name:"maction",namespace:xs}],attributes:["dir","displaystyle","mathbackground","mathcolor","mathsize","scriptlevel","encoding","display","linethickness","intent","arg","form","fence","separator","lspace","rspace","stretchy","symmetric","maxsize","minsize","largeop","movablelimits","width","height","depth","voffset","accent","accentunder","columnspan","rowspan"],comments:!1}):null)}}const Ls=/^H(\d+)$/;class _s{#tr;#ir=null;#nr;#sr=new Map;#ar;#rr=null;#or=null;#lr=null;constructor(e,t){this.#tr=e.getStructTree(),this.#ar=t}async render(){if(this.#nr)return this.#nr;const{promise:e,resolve:t,reject:i}=Promise.withResolvers();this.#nr=e;try{this.#ir=this.#dr(await this.#tr)}catch(e){i(e)}return this.#tr=null,this.#ir?.classList.add("structTree"),t(this.#ir),e}async getAriaAttributes(e){try{return await this.render(),this.#sr.get(e)}catch{}return null}hide(){this.#ir&&!this.#ir.hidden&&(this.#ir.hidden=!0)}show(){this.#ir?.hidden&&(this.#ir.hidden=!1)}#hr(e,t){const{alt:i,id:n,lang:s}=e;if(void 0!==i){let n=!1;const s=P(i);for(const t of e.children)"annotation"===t.type&&(this.#sr.getOrInsertComputed(t.id,Ie).set("aria-label",s),n=!0);n||t.setAttribute("aria-label",s)}void 0!==n&&t.setAttribute("aria-owns",n),void 0!==s&&t.setAttribute("lang",P(s,!0))}#cr(e,t){const{alt:i,bbox:n,children:s}=e,a=s?.[0];if(!this.#ar||!i||!n||"content"!==a?.type)return!1;const{id:r}=a;if(!r)return!1;t.setAttribute("aria-owns",r);const o=document.createElement("span");(this.#rr||=new Map).set(r,o),o.setAttribute("role","img"),o.setAttribute("aria-label",P(i));const{pageHeight:l,pageX:d,pageY:h}=this.#ar,c="calc(var(--total-scale-factor) *",{style:u}=o;return u.width=`${c}${n[2]-n[0]}px)`,u.height=`${c}${n[3]-n[1]}px)`,u.left=`${c}${n[0]-d}px)`,u.top=`${c}${l-n[3]+h}px)`,!0}updateTextLayer(){if(this.#rr){for(const[e,t]of this.#rr)document.getElementById(e)?.append(t);this.#rr.clear(),this.#rr=null}if(this.#or){for(const e of this.#or){const t=document.getElementById(e);t&&(t.ariaHidden=!0)}this.#or.length=0,this.#or=null}if(this.#lr){for(let e=0,t=this.#lr.length;e<t;e+=2){const t=this.#lr[e],i=this.#lr[e+1];let n="";for(const e of i){const t=document.getElementById(e);t&&(n+=t.textContent.trim()||"",t.ariaHidden="true")}n&&(t.textContent=n)}this.#lr.length=0,this.#lr=null}}#ur(e,t){if(e){"id"in e&&t.push(e.id);for(const i of e.children||[])this.#ur(i,t)}}#dr(e,t=[]){if(!e)return null;let i,n=!0;if("role"in e){const{role:s}=e;if(Es.has(s)){i=document.createElementNS(xs,s);const t=[];(this.#lr||=[]).push(i,t);for(const{type:i,id:n}of e.children||[])"content"===i&&n&&t.push(n)}else i=document.createElement("span");const a=s.match(Ls);if(a?(i.setAttribute("role","heading"),i.setAttribute("aria-level",a[1])):Ss[s]&&i.setAttribute("role","TH"===s&&"TR"===t.at(-1)?.role&&"TBody"===t.at(-2)?.role?"rowheader":Ss[s]),"Figure"===s&&this.#cr(e,i))return i;"Formula"===s&&(e.mathML&&Ts.sanitizer&&(n=!1,i.setHTML(e.mathML,{sanitizer:Ts.sanitizer}),this.#ur(e,this.#or||=[]),delete e.alt),e.mathML||1!==e.children.length||"math"===e.children[0].role||(i=document.createElementNS(xs,"math"),delete e.alt))}if(i||=document.createElement("span"),this.#hr(e,i),e.children)if(1===e.children.length&&"id"in e.children[0])this.#hr(e.children[0],i);else if(n){t.push(e);for(const n of e.children)i.append(this.#dr(n,t));t.pop()}return i}}class Ms{#gr=!1;#pr=null;#mr=new Map;#fr=new Map;setTextMapping(e){this.#pr=e}static#br(e,t){const i=e.getBoundingClientRect(),n=t.getBoundingClientRect();if(0===i.width&&0===i.height)return 1;if(0===n.width&&0===n.height)return-1;const s=i.y,a=i.y+i.height,r=i.y+i.height/2,o=n.y,l=n.y+n.height,d=n.y+n.height/2;if(r<=o&&d>=a)return-1;if(d<=s&&r>=l)return 1;return i.x+i.width/2-(n.x+n.width/2)}enable(){if(this.#gr)throw new Error("TextAccessibilityManager is already enabled.");if(!this.#pr)throw new Error("Text divs and strings have not been set.");if(this.#gr=!0,this.#pr=this.#pr.slice(),this.#pr.sort(Ms.#br),this.#mr.size>0){const e=this.#pr;for(const[t,i]of this.#mr){document.getElementById(t)?this.#vr(t,e[i]):this.#mr.delete(t)}}for(const[e,t]of this.#fr)this.addPointerInTextLayer(e,t);this.#fr.clear()}disable(){this.#gr&&(this.#fr.clear(),this.#pr=null,this.#gr=!1)}removePointerInTextLayer(e){if(!this.#gr)return void this.#fr.delete(e);const t=this.#pr;if(!t||0===t.length)return;const{id:i}=e,n=this.#mr.get(i);if(void 0===n)return;const s=t[n];this.#mr.delete(i);let a=s.getAttribute("aria-owns");a?.includes(i)&&(a=a.split(" ").filter(e=>e!==i).join(" "),a?s.setAttribute("aria-owns",a):(s.removeAttribute("aria-owns"),s.setAttribute("role","presentation")))}#vr(e,t){const i=t.getAttribute("aria-owns");i?.includes(e)||t.setAttribute("aria-owns",i?`${i} ${e}`:e),t.removeAttribute("role")}addPointerInTextLayer(e,t){const{id:i}=e;if(!i)return null;if(!this.#gr)return this.#fr.set(e,t),null;t&&this.removePointerInTextLayer(e);const n=this.#pr;if(!n||0===n.length)return null;const s=S(n,t=>Ms.#br(e,t)<0),a=Math.max(0,s-1),r=n[a];this.#vr(i,r),this.#mr.set(i,a);const o=r.parentNode;return o?.classList.contains("markedContent")?o.id:null}moveElementInDOM(e,t,i,n){const s=this.addPointerInTextLayer(i,n);if(!e.hasChildNodes())return e.append(t),s;const a=Array.from(e.childNodes).filter(e=>e!==t);if(0===a.length)return s;const r=S(a,e=>Ms.#br(t,e)<0);return 0===r?a[0].before(t):a[r-1].after(t),s}}class Is{#$i=null;constructor({findController:e,eventBus:t,pageIndex:i}){this.findController=e,this.matches=[],this.eventBus=t,this.pageIdx=i,this.textDivs=null,this.textContentItemsStr=null,this.enabled=!1}setTextMapping(e,t){this.textDivs=e,this.textContentItemsStr=t}enable(){if(!this.textDivs||!this.textContentItemsStr)throw new Error("Text divs and strings have not been set.");if(this.enabled)throw new Error("TextHighlighter is already enabled.");this.enabled=!0,this.#$i||(this.#$i=new AbortController,this.eventBus.on("updatetextlayermatches",e=>{e.pageIndex!==this.pageIdx&&-1!==e.pageIndex||this._updateMatches()},{signal:this.#$i.signal,...Q})),this._updateMatches()}disable(){this.enabled&&(this.enabled=!1,this.#$i?.abort(),this.#$i=null,this._updateMatches(!0))}_convertMatches(e,t){if(!e)return[];const{textContentItemsStr:i}=this;let n=0,s=0;const a=i.length-1,r=[];for(let o=0,l=e.length;o<l;o++){let l=e[o];for(;n!==a&&l>=s+i[n].length;)s+=i[n].length,n++;n===i.length&&console.error("Could not find a matching mapping");const d={begin:{divIdx:n,offset:l-s}};for(l+=t[o];n!==a&&l>s+i[n].length;)s+=i[n].length,n++;d.end={divIdx:n,offset:l-s},r.push(d)}return r}_renderMatches(e){if(0===e.length)return;const{findController:t,pageIdx:i}=this,{textContentItemsStr:n,textDivs:s}=this,a=i===t.selected.pageIdx,r=t.selected.matchIdx;let o=null;const l={divIdx:-1,offset:void 0};function d(e,t){const i=e.divIdx;return s[i].textContent="",h(i,0,e.offset,t)}function h(e,t,i,a){let r=s[e];if(r.nodeType===Node.TEXT_NODE){const t=document.createElement("span");r.before(t),t.append(r),s[e]=t,r=t}const o=n[e].substring(t,i),l=document.createTextNode(o);if(a){const e=document.createElement("span");return e.className=`${a} appended`,e.append(l),r.append(e),a.includes("selected")?e:null}return r.append(l),0}let c=r,u=c+1;if(t.state.highlightAll)c=0,u=e.length;else if(!a)return;let g=-1,p=-1;for(let n=c;n<u;n++){const c=e[n],u=c.begin;if(u.divIdx===g&&u.offset===p)continue;g=u.divIdx,p=u.offset;const m=c.end,f=a&&n===r,b=f?" selected":"";let v=null;if(o&&u.divIdx===o.divIdx?h(o.divIdx,o.offset,u.offset):(null!==o&&h(o.divIdx,o.offset,l.offset),d(u)),u.divIdx===m.divIdx)v=h(u.divIdx,u.offset,m.offset,"highlight"+b);else{v=h(u.divIdx,u.offset,l.offset,"highlight begin"+b);for(let e=u.divIdx+1,t=m.divIdx;e<t;e++)s[e].className="highlight middle"+b;d(m,"highlight end"+b)}o=m,f&&t.scrollMatchIntoView({element:v,pageIndex:i,matchIndex:r})}o&&h(o.divIdx,o.offset,l.offset)}_updateMatches(e=!1){if(!this.enabled&&!e)return;const{findController:t,matches:i,pageIdx:n}=this,{textContentItemsStr:s,textDivs:a}=this;let r=-1;for(const e of i){for(let t=Math.max(r,e.begin.divIdx),i=e.end.divIdx;t<=i;t++){const e=a[t];e.textContent=s[t],e.className=""}r=e.end.divIdx+1}if(!t?.highlightMatches||e)return;const o=t.pageMatches[n]||null,l=t.pageMatchesLength[n]||null;this.matches=this._convertMatches(o,l),this._renderMatches(this.matches)}}class As{#os=null;#wr=!1;#Da=null;#yr=!1;#Oa=null;static#Cr=new Map;static#Pr=null;constructor({pdfPage:e,highlighter:t=null,accessibilityManager:i=null,enablePermissions:n=!1,onAppend:s=null,abortSignal:a=null}){this.pdfPage=e,this.highlighter=t,this.accessibilityManager=i,this.#wr=!0===n,this.#Da=s,this.#os=a,this.div=document.createElement("div"),this.div.tabIndex=0,this.div.className="textLayer"}async render({viewport:e,images:t,textContentParams:i=null}){if(this.#yr&&this.#Oa)return this.#Oa.update({viewport:e,onBefore:this.hide.bind(this)}),void this.show();this.cancel(),this.#Oa=new qe({textContentSource:this.pdfPage.streamTextContent(i||{includeMarkedContent:!0,disableNormalization:!0}),images:t,container:this.div,viewport:e});const{textDivs:n,textContentItemsStr:s}=this.#Oa;this.highlighter?.setTextMapping(n,s),this.accessibilityManager?.setTextMapping(n),await this.#Oa.render(),this.#yr=!0;const a=document.createElement("div");a.className="endOfContent",this.div.append(a),this.#Sr(a),this.#Da?.(this.div),this.highlighter?.enable(),this.accessibilityManager?.enable()}hide(){!this.div.hidden&&this.#yr&&(this.highlighter?.disable(),this.div.hidden=!0)}show(){this.div.hidden&&this.#yr&&(this.div.hidden=!1,this.highlighter?.enable())}cancel(){this.#Oa?.cancel(),this.#Oa=null,this.#yr=!1,this.div.replaceChildren(),this.highlighter?.disable(),this.accessibilityManager?.disable(),As.#Er(this.div)}#Sr(e){const{div:t}=this,i=this.#os,n=i?{signal:i}:null;t.addEventListener("mousedown",()=>{t.classList.add("selecting")},n),t.addEventListener("copy",e=>{if(!this.#wr){const t=document.getSelection();e.clipboardData.setData("text/plain",P(De(t.toString())))}Ke(e)},n),As.#Cr.set(t,e),As.#xr(i)}static#Er(e){this.#Cr.delete(e),0===this.#Cr.size&&(this.#Pr?.abort(),this.#Pr=null)}static#xr(e){if(this.#Pr)return;this.#Pr=new AbortController;const t=e?AbortSignal.any([this.#Pr.signal,e]):this.#Pr.signal,i=(e,t)=>{t.append(e),e.style.width="",e.style.height="",t.classList.remove("selecting")};let n=!1;var s,a;document.addEventListener("pointerdown",()=>{n=!0},{signal:t}),document.addEventListener("pointerup",()=>{n=!1,this.#Cr.forEach(i)},{signal:t}),window.addEventListener("blur",()=>{n=!1,this.#Cr.forEach(i)},{signal:t}),document.addEventListener("keyup",()=>{n||this.#Cr.forEach(i)},{signal:t}),document.addEventListener("selectionchange",()=>{const e=document.getSelection();if(0===e.rangeCount)return void this.#Cr.forEach(i);const t=new Set;for(let i=0;i<e.rangeCount;i++){const n=e.getRangeAt(i);for(const e of this.#Cr.keys())!t.has(e)&&n.intersectsNode(e)&&t.add(e)}for(const[e,n]of this.#Cr)t.has(e)?e.classList.add("selecting"):i(n,e);if(s??="none"===getComputedStyle(this.#Cr.values().next().value).getPropertyValue("-moz-user-select"),s)return;const n=e.getRangeAt(0),r=a&&(0===n.compareBoundaryPoints(Range.END_TO_END,a)||0===n.compareBoundaryPoints(Range.START_TO_END,a));let o=r?n.startContainer:n.endContainer;if(o.nodeType===Node.TEXT_NODE&&(o=o.parentNode),o.classList?.contains("highlight")&&(o=o.parentNode),!r&&0===n.endOffset)do{for(;!o.previousSibling;)o=o.parentNode;o=o.previousSibling}while(!o.childNodes.length);const l=o.parentElement?.closest(".textLayer"),d=this.#Cr.get(l);d&&(d.style.width=l.style.width,d.style.height=l.style.height,d.style.userSelect="text",o.parentElement.insertBefore(d,r?o:o.nextSibling)),a=n.cloneRange()},{signal:t})}}const Bs=new Map([["canvasWrapper",0],["textLayer",1],["annotationLayer",2],["annotationEditorLayer",3],["xfaLayer",3]]);class ks extends ys{#os=null;#Tr=ae.ENABLE_FORMS;#Lr=null;#Ra=null;#_r=!0;#Mr=!1;#R=!1;#Ir=null;#Ar=!1;#Br=null;#kr=null;#Dr=1;#Nr=1;#Or=u;#Rr=1;#jr={directDrawing:!0,initialOptionalContent:!0,regularAnnotations:!0};#Vr=[null,null,null,null];constructor(e){super(e);const{container:t,defaultViewport:i}=e;this.renderingId="page"+this.id,this.#Ir=e.layerProperties||null,this.#os=e.abortSignal||null,this.pdfPage=null,this.pageLabel=null,this.rotation=0,this.scale=e.scale||1,this.viewport=i,this.pdfPageRotate=i.rotation,this._optionalContentConfigPromise=e.optionalContentConfigPromise||null,this.#Or=e.textLayerMode??u,this.#Tr=e.annotationMode??ae.ENABLE_FORMS,this.imageResourcesPath=e.imageResourcesPath||"",this.enableDetailCanvas=e.enableDetailCanvas??!0,this.maxCanvasPixels=e.maxCanvasPixels??Z.get("maxCanvasPixels"),this.maxCanvasDim=e.maxCanvasDim||Z.get("maxCanvasDim"),this.capCanvasAreaFactor=e.capCanvasAreaFactor??Z.get("capCanvasAreaFactor"),this.#_r=!1!==e.enableAutoLinking,this.#Ra=e.commentManager||null,this.l10n=e.l10n,this.l10n||=new Mi,this._isStandalone=!this.renderingQueue?.hasViewer(),this._container=t,this._annotationCanvasMap=null,this.annotationLayer=null,this.annotationEditorLayer=null,this.textLayer=null,this.xfaLayer=null,this.structTreeLayer=null,this.drawLayer=null,this.detailView=null;const n=document.createElement("div");if(n.className="page",n.setAttribute("data-page-number",this.id),n.setAttribute("role","region"),n.setAttribute("data-l10n-id","pdfjs-page-landmark"),n.setAttribute("data-l10n-args",JSON.stringify({page:this.id})),this.div=n,this.#Fr(),t?.append(n),this._isStandalone){t?.style.setProperty("--scale-factor",this.scale*ze.PDF_TO_CSS_UNITS),this.pageColors?.background&&t?.style.setProperty("--page-bg-color",this.pageColors.background);const{optionalContentConfigPromise:i}=e;i&&i.then(e=>{i===this._optionalContentConfigPromise&&(this.#jr.initialOptionalContent=e.hasInitialVisibility)}),e.l10n||this.l10n.translate(this.div)}}clone(e){const t=new ks({container:null,eventBus:this.eventBus,pagesColors:this.pageColors,renderingQueue:this.renderingQueue,enableOptimizedPartialRendering:this.enableOptimizedPartialRendering,minDurationToUpdateCanvas:this.minDurationToUpdateCanvas,defaultViewport:this.viewport,id:e,layerProperties:this.#Ir,abortSignal:this.#os,scale:this.scale,optionalContentConfigPromise:this._optionalContentConfigPromise,textLayerMode:this.#Or,annotationMode:this.#Tr,imageResourcesPath:this.imageResourcesPath,enableDetailCanvas:this.enableDetailCanvas,maxCanvasPixels:this.maxCanvasPixels,maxCanvasDim:this.maxCanvasDim,capCanvasAreaFactor:this.capCanvasAreaFactor,enableAutoLinking:this.#_r,commentManager:this.#Ra,l10n:this.l10n});return t.setPdfPage(this.pdfPage.clone(e-1)),t}#Ur(e,t){const i=Bs.get(t),n=this.#Vr[i];if(this.#Vr[i]=e,n)n.replaceWith(e);else{for(let t=i-1;t>=0;t--){const i=this.#Vr[t];if(i)return void i.after(e)}this.div.prepend(e)}}#Fr(){const{div:e,viewport:t}=this;if(t.userUnit!==this.#Rr&&(1!==t.userUnit?e.style.setProperty("--user-unit",t.userUnit):e.style.removeProperty("--user-unit"),this.#Rr=t.userUnit),this.pdfPage){if(this.#kr===t.rotation)return;this.#kr=t.rotation}Xe(e,t,!0,!1)}updatePageNumber(e){if(this.id===e)return;const t=this.id;this.id=e,this.renderingId=`page${e}`,this.pdfPage&&(this.pdfPage.pageNumber=e),this.setPageLabel(this.pageLabel);const{div:i}=this;i.setAttribute("data-page-number",e),i.setAttribute("data-l10n-args",JSON.stringify({page:e})),this._textHighlighter.pageIdx=e-1,this.#Ir.annotationEditorUIManager?.updatePageIndex(t-1,e-1)}setPdfPage(e){!this._isStandalone||"CanvasText"!==this.pageColors?.foreground&&"Canvas"!==this.pageColors?.background||(this._container?.style.setProperty("--hcm-highlight-filter",e.filterFactory.addHighlightHCMFilter("highlight","CanvasText","Canvas","HighlightText","Highlight")),this._container?.style.setProperty("--hcm-highlight-selected-filter",e.filterFactory.addHighlightHCMFilter("highlight_selected","CanvasText","Canvas","HighlightText","Highlight"))),this.pdfPage=e,this.pdfPageRotate=e.rotate;const t=(this.rotation+this.pdfPageRotate)%360;this.viewport=e.getViewport({scale:this.scale*ze.PDF_TO_CSS_UNITS,rotation:t}),this.#Fr(),this.reset()}destroy(){this.reset(),this.pdfPage?.cleanup()}deleteMe(e){e?this.div.remove():(this.destroy(),this.#Ir.annotationEditorUIManager?.deletePage(this.id))}hasEditableAnnotations(){return!!this.annotationLayer?.hasEditableAnnotations()}get _textHighlighter(){return Ge(this,"_textHighlighter",new Is({pageIndex:this.id-1,eventBus:this.eventBus,findController:this.#Ir.findController}))}#zr(e,t){this.eventBus.dispatch(e,{source:this,pageNumber:this.id,error:t})}async#Hr(){let e=null;try{await this.annotationLayer.render({viewport:this.viewport,intent:"display",structTreeLayer:this.structTreeLayer,optionalContentConfigPromise:this._optionalContentConfigPromise})}catch(t){console.error("#renderAnnotationLayer:",t),e=t}finally{this.#zr("annotationlayerrendered",e)}}async#$r(){let e=null;try{await this.annotationEditorLayer.render({viewport:this.viewport,intent:"display"})}catch(t){console.error("#renderAnnotationEditorLayer:",t),e=t}finally{this.#zr("annotationeditorlayerrendered",e)}}async#Wr(){try{await this.drawLayer.render({intent:"display"})}catch(e){console.error("#renderDrawLayer:",e)}}async#Xr(){let e=null;try{const e=await this.xfaLayer.render({viewport:this.viewport,intent:"display"});e?.textDivs&&this._textHighlighter&&this.#Gr(e.textDivs)}catch(t){console.error("#renderXfaLayer:",t),e=t}finally{this.xfaLayer?.div&&(this.l10n.pause(),this.#Ur(this.xfaLayer.div,"xfaLayer"),this.l10n.resume()),this.#zr("xfalayerrendered",e)}}async#Yr(){if(!this.textLayer)return;let e=null;try{await this.textLayer.render({viewport:this.viewport,images:this.imageCoordinates?new Qe(this.imagesRightClickMinSize,this.imageCoordinates,this.viewport,()=>this.canvas):null})}catch(t){if(t instanceof J)return;console.error("#renderTextLayer:",t),e=t}this.#zr("textlayerrendered",e),this.#Kr()}async#Kr(){if(!this.textLayer)return;const e=await(this.structTreeLayer?.render());e&&(this.l10n.pause(),this.structTreeLayer?.updateTextLayer(),this.canvas&&e.parentNode!==this.canvas&&this.canvas.append(e),this.l10n.resume()),this.structTreeLayer?.show()}async#Gr(e){const t=await this.pdfPage.getTextContent(),i=[];for(const e of t.items)i.push(e.str);this._textHighlighter.setTextMapping(e,i),this._textHighlighter.enable()}async#Zr(e){let t=null;try{if(await e,!this.annotationLayer)return;await this.annotationLayer.injectLinkAnnotations(ws.processLinks(this))}catch(e){console.error("#injectLinkAnnotations:",e),t=e}}_resetCanvas(){super._resetCanvas(),this.#Br=null}reset({keepAnnotationLayer:e=!1,keepAnnotationEditorLayer:t=!1,keepXfaLayer:i=!1,keepTextLayer:n=!1,keepCanvasWrapper:s=!1,preserveDetailViewState:a=!1}={}){const r=this.pdfPage?._pdfBug??!1;this.cancelRendering({keepAnnotationLayer:e,keepAnnotationEditorLayer:t,keepXfaLayer:i,keepTextLayer:n}),this.renderingState=rs.INITIAL;const o=this.div,l=o.childNodes,d=e&&this.annotationLayer?.div||null,h=t&&this.annotationEditorLayer?.div||null,c=i&&this.xfaLayer?.div||null,u=n&&this.textLayer?.div||null,g=s&&this.#Lr||null;for(let e=l.length-1;e>=0;e--){const t=l[e];switch(t){case d:case h:case c:case u:case g:continue}if(r&&t.classList.contains("pdfBugGroupsLayer"))continue;t.remove();const i=this.#Vr.indexOf(t);i>=0&&(this.#Vr[i]=null)}o.removeAttribute("data-loaded"),d&&this.annotationLayer.hide(),h&&this.annotationEditorLayer.hide(),c&&this.xfaLayer.hide(),u&&this.textLayer.hide(),this.structTreeLayer?.hide(),!s&&this.#Lr&&(this.#Lr=null,this._resetCanvas()),a||(this.detailView?.reset({keepCanvas:s}),s||(this.detailView=null))}toggleEditingMode(e){this.#R=e,this.hasEditableAnnotations()&&this.reset({keepAnnotationLayer:!0,keepAnnotationEditorLayer:!0,keepXfaLayer:!0,keepTextLayer:!0,keepCanvasWrapper:!0})}updateVisibleArea(e){this.enableDetailCanvas&&(this.#Ar&&this.maxCanvasPixels>0&&e?(this.detailView??=new Ps({pageView:this,enableOptimizedPartialRendering:this.enableOptimizedPartialRendering,imagesRightClickMinSize:-1}),this.detailView.update({visibleArea:e})):this.detailView&&(this.detailView.reset(),this.detailView=null))}update({scale:e=0,rotation:t=null,optionalContentConfigPromise:i=null,drawingDelay:n=-1}){this.scale=e||this.scale,"number"==typeof t&&(this.rotation=t),i instanceof Promise&&(this._optionalContentConfigPromise=i,i.then(e=>{i===this._optionalContentConfigPromise&&(this.#jr.initialOptionalContent=e.hasInitialVisibility)})),this.#jr.directDrawing=!0;const s=(this.rotation+this.pdfPageRotate)%360;if(this.viewport=this.viewport.clone({scale:this.scale*ze.PDF_TO_CSS_UNITS,rotation:s}),this.#Fr(),this._isStandalone&&this._container?.style.setProperty("--scale-factor",this.viewport.scale),this.#qr(),this.canvas){const e=this.#Mr&&this.#Ar,t=n>=0&&n<1e3;if(t||e)return t&&!e&&this.renderingState!==rs.FINISHED&&(this.cancelRendering({keepAnnotationLayer:!0,keepAnnotationEditorLayer:!0,keepXfaLayer:!0,keepTextLayer:!0,cancelExtraDelay:n}),this.renderingState=rs.FINISHED,this.#jr.directDrawing=!1),this.cssTransform({redrawAnnotationLayer:!0,redrawAnnotationEditorLayer:!0,redrawXfaLayer:!0,redrawTextLayer:!t,hideTextLayer:t}),void(t||(this.detailView?.update({underlyingViewUpdated:!0}),this.dispatchPageRendered(!0,!1)))}this.cssTransform({}),this.reset({keepAnnotationLayer:!0,keepAnnotationEditorLayer:!0,keepXfaLayer:!0,keepTextLayer:!0,keepCanvasWrapper:!0,preserveDetailViewState:!0}),this.detailView?.update({underlyingViewUpdated:!0})}#qr(){const{width:e,height:t}=this.viewport,i=this.outputScale=new Oe;if(0===this.maxCanvasPixels){const e=1/this.scale;i.sx*=e,i.sy*=e,this.#Ar=!0}else if(this.#Ar=i.limitCanvas(e,t,this.maxCanvasPixels,this.maxCanvasDim,this.capCanvasAreaFactor),this.#Ar&&this.enableDetailCanvas){const e=this.enableOptimizedPartialRendering?4:2;i.sx/=e,i.sy/=e}}cancelRendering({keepAnnotationLayer:e=!1,keepAnnotationEditorLayer:t=!1,keepXfaLayer:i=!1,keepTextLayer:n=!1,cancelExtraDelay:s=0}={}){super.cancelRendering({cancelExtraDelay:s}),!this.textLayer||n&&this.textLayer.div||(this.textLayer.cancel(),this.textLayer=null),!this.annotationLayer||e&&this.annotationLayer.div||(this.annotationLayer.cancel(),this.annotationLayer=null,this._annotationCanvasMap=null),this.structTreeLayer&&!this.textLayer&&(this.structTreeLayer=null),!this.annotationEditorLayer||t&&this.annotationEditorLayer.div||(this.drawLayer&&(this.drawLayer.cancel(),this.drawLayer=null),this.annotationEditorLayer.cancel(),this.annotationEditorLayer=null),!this.xfaLayer||i&&this.xfaLayer.div||(this.xfaLayer.cancel(),this.xfaLayer=null,this._textHighlighter?.disable())}cssTransform({redrawAnnotationLayer:e=!1,redrawAnnotationEditorLayer:t=!1,redrawXfaLayer:i=!1,redrawTextLayer:n=!1,hideTextLayer:s=!1}){const{canvas:a}=this;if(!a)return;const r=this.#Br;if(this.viewport!==r){const e=(360+this.viewport.rotation-r.rotation)%360;if(90===e||270===e){const{width:t,height:i}=this.viewport,n=i/t,s=t/i;a.style.transform=`rotate(${e}deg) scale(${n},${s})`}else a.style.transform=0===e?"":`rotate(${e}deg)`}e&&this.annotationLayer&&this.#Hr(),t&&this.annotationEditorLayer&&(this.drawLayer&&this.#Wr(),this.#$r()),i&&this.xfaLayer&&this.#Xr(),this.textLayer&&(s?(this.textLayer.hide(),this.structTreeLayer?.hide()):n&&this.#Yr())}get width(){return this.viewport.width}get height(){return this.viewport.height}getPagePoint(e,t){return this.viewport.convertToPdfPoint(e,t)}_ensureCanvasWrapper(){let e=this.#Lr;return e||(e=this.#Lr=document.createElement("div"),e.classList.add("canvasWrapper"),this.#Ur(e,"canvasWrapper")),e}_getRenderingContext(e,t,i,n){return{canvas:e,transform:t,viewport:this.viewport,annotationMode:this.#Tr,optionalContentConfigPromise:this._optionalContentConfigPromise,annotationCanvasMap:this._annotationCanvasMap,pageColors:this.pageColors,isEditing:this.#R,recordOperations:i,recordImages:n}}async draw(){this.renderingState!==rs.INITIAL&&(console.error("Must be in new state before drawing"),this.reset());const{div:e,l10n:t,pdfPage:i,viewport:n}=this;if(!i)throw this.renderingState=rs.FINISHED,new Error("pdfPage is not loaded");this.renderingState=rs.RUNNING;const s=this._ensureCanvasWrapper();if(this.textLayer||this.#Or===c||i.isPureXfa||(this._accessibilityManager||=new Ms,this.textLayer=new As({pdfPage:i,highlighter:this._textHighlighter,accessibilityManager:this._accessibilityManager,enablePermissions:this.#Or===g,onAppend:e=>{this.l10n.pause(),this.#Ur(e,"textLayer"),this.l10n.resume()},abortSignal:this.#os})),!this.annotationLayer&&this.#Tr!==ae.DISABLE){const{annotationStorage:e,annotationEditorUIManager:t,downloadManager:n,enableComment:s,enableScripting:a,fieldObjectsPromise:r,hasJSActionsPromise:o,linkService:l}=this.#Ir;this._annotationCanvasMap||=new Map,this.annotationLayer=new ms({pdfPage:i,annotationStorage:e,imageResourcesPath:this.imageResourcesPath,renderForms:this.#Tr===ae.ENABLE_FORMS,linkService:l,downloadManager:n,enableComment:s,enableScripting:a,hasJSActionsPromise:o,fieldObjectsPromise:r,annotationCanvasMap:this._annotationCanvasMap,accessibilityManager:this._accessibilityManager,annotationEditorUIManager:t,commentManager:this.#Ra,onAppend:e=>{this.#Ur(e,"annotationLayer")}})}const{width:a,height:r}=n;this.#Br=n;const{canvas:o,prevCanvas:l}=this._createCanvas(e=>{s.prepend(e)});o.setAttribute("role","presentation"),this.outputScale||this.#qr();const{outputScale:d}=this;this.#Mr=this.#Ar;const h=E(d.sx),u=E(d.sy),p=o.width=x(F(a*d.sx),h[0]),m=o.height=x(F(r*d.sy),u[0]),f=x(F(a),h[1]),b=x(F(r),u[1]);d.sx=p/f,d.sy=m/b,this.#Dr!==h[1]&&(e.style.setProperty("--scale-round-x",`${h[1]}px`),this.#Dr=h[1]),this.#Nr!==u[1]&&(e.style.setProperty("--scale-round-y",`${u[1]}px`),this.#Nr=u[1]);const v=this.enableOptimizedPartialRendering&&this.#Mr&&!this.recordedBBoxes,w=-1!==this.imagesRightClickMinSize&&!this.imageCoordinates,y=d.scaled?[d.sx,0,0,d.sy,0,0]:null,C=this._drawCanvas(this._getRenderingContext(o,y,v,w),()=>{l?.remove(),this._resetCanvas()},e=>{this.#jr.regularAnnotations=!e.separateAnnots,this.dispatchPageRendered(!1,!1)}).then(async()=>{if(this.renderingState!==rs.FINISHED)return;this.structTreeLayer||=new _s(i,n.rawDims);const e=this.#Yr();this.annotationLayer&&(await this.#Hr(),this.#_r&&this.annotationLayer&&this.textLayer&&await this.#Zr(e)),this.drawLayer||=new Cs({pageIndex:this.id,textLayer:this.enableSelectionRendering?this.textLayer?.div:null,filterFactory:this.pdfPage?.filterFactory,pageColors:this.pageColors}),await this.#Wr(),this.drawLayer.setParent(s);const{annotationEditorUIManager:a}=this.#Ir;a&&(this.annotationLayer||this.#Tr===ae.DISABLE)&&(this.annotationEditorLayer||=new ps({uiManager:a,pageIndex:this.id-1,l10n:t,structTreeLayer:this.structTreeLayer,accessibilityManager:this._accessibilityManager,annotationLayer:this.annotationLayer?.annotationLayer,textLayer:this.textLayer,drawLayer:this.drawLayer.getDrawLayer(),onAppend:e=>{this.#Ur(e,"annotationEditorLayer")}}),this.#$r())});if(i.isPureXfa){if(!this.xfaLayer){const{annotationStorage:e,linkService:t}=this.#Ir;this.xfaLayer=new Xn({pdfPage:i,annotationStorage:e,linkService:t})}this.#Xr()}return e.setAttribute("data-loaded",!0),this.dispatchPageRender(),C}setPageLabel(e){this.pageLabel="string"==typeof e?e:null,this.div.setAttribute("data-l10n-args",JSON.stringify({page:this.pageLabel??this.id})),null!==this.pageLabel?this.div.setAttribute("data-page-label",this.pageLabel):this.div.removeAttribute("data-page-label")}get thumbnailCanvas(){const{directDrawing:e,initialOptionalContent:t,regularAnnotations:i}=this.#jr;return e&&t&&i?this.canvas:null}}const Ds=1e4,Ns=5e3,Os=250;function Rs(e){return Object.values(ie).includes(e)&&e!==ie.DISABLE}class js{#Qr=new Set;#Jr=0;constructor(e){this.#Jr=e}push(e){const t=this.#Qr;t.has(e)&&t.delete(e),t.add(e),t.size>this.#Jr&&this.#eo()}resize(e,t=null){this.#Jr=e;const i=this.#Qr;if(t){const e=i.size;let n=1;for(const s of i)if(t.has(s.id)&&(i.delete(s),i.add(s)),++n>e)break}for(;i.size>this.#Jr;)this.#eo()}has(e){return this.#Qr.has(e)}[Symbol.iterator](){return this.#Qr.keys()}#eo(){const e=this.#Qr.keys().next().value;e?.destroy(),this.#Qr.delete(e)}}class Vs{#to=null;#io=null;#no=null;#so=ie.NONE;#ao=null;#Tr=ae.ENABLE_FORMS;#Ra=null;#ro=null;#oo=null;#lo=!1;#wr=!1;#do=!1;#ho=!1;#_r=!0;#os=null;#$i=null;#co=0;#de=null;#uo=!0;#go=null;#po=null;#mo=null;#fo=!1;#bo=null;#vo=0;#Ke=new ResizeObserver(this.#Hi.bind(this));#wo=null;#yo=null;#Co=null;#Po=!0;#Or=u;#So=null;#Eo=null;#xo=null;#Is=null;constructor(e){const i="6.0.227";if(nt!==i)throw new Error(`The API version "${nt}" does not match the Viewer version "${i}".`);if(this.container=e.container,this.viewer=e.viewer||e.container.firstElementChild,this.#So=e.viewerAlert||null,"DIV"!==this.container?.tagName||"DIV"!==this.viewer?.tagName)throw new Error("Invalid `container` and/or `viewer` option.");if(this.container.offsetParent&&"absolute"!==getComputedStyle(this.container).position)throw new Error("The `container` must be absolutely positioned.");this.#Ke.observe(this.container),this.eventBus=e.eventBus,this.linkService=e.linkService||new ot,this.downloadManager=e.downloadManager||null,this.findController=e.findController||null,this.#io=e.altTextManager||null,this.#Ra=e.commentManager||null,this.#Co=e.signatureManager||null,this.#oo=e.editorUndoBar||null,this.findController&&(this.findController.onIsPageVisible=e=>this._getVisiblePages().ids.has(e)),this._scriptingManager=e.scriptingManager||null,this.#Or=e.textLayerMode??u,this.#Tr=e.annotationMode??ae.ENABLE_FORMS,this.#so=e.annotationEditorMode??ie.NONE,this.#no=e.annotationEditorHighlightColors||null,this.#lo=!0===e.enableHighlightFloatingButton,this.#do=!0===e.enableUpdatedAddImage,this.#ho=!0===e.enableNewAltTextWhenAddingImage,this.imageResourcesPath=e.imageResourcesPath||"",this.enablePrintAutoRotate=e.enablePrintAutoRotate||!1,this.removePageBorders=e.removePageBorders||!1,this.maxCanvasPixels=e.maxCanvasPixels,this.maxCanvasDim=e.maxCanvasDim,this.capCanvasAreaFactor=e.capCanvasAreaFactor,this.enableDetailCanvas=e.enableDetailCanvas??!0,this.enableOptimizedPartialRendering=e.enableOptimizedPartialRendering??!1,this.enableSelectionRendering=!1!==e.enableSelectionRendering,this.imagesRightClickMinSize=e.imagesRightClickMinSize??-1,this.l10n=e.l10n,this.l10n||=new Mi,this.#wr=e.enablePermissions||!1,this.pageColors=e.pageColors||null,this.#de=e.mlManager||null,this.#Po=!1!==e.supportsPinchToZoom,this.#_r=!1!==e.enableAutoLinking,this.#co=e.minDurationToUpdateCanvas??500,this.defaultRenderingQueue=!e.renderingQueue,this.defaultRenderingQueue?(this.renderingQueue=new ls,this.renderingQueue.setViewer(this)):this.renderingQueue=e.renderingQueue;const{abortSignal:n}=e;this.#os=n||null,n?.addEventListener("abort",()=>{this.#Ke.disconnect(),this.#Ke=null},{once:!0}),this.scroll=w(this.container,this._scrollUpdate.bind(this),n),this.presentationModeState=t,this._resetView(),this.removePageBorders&&this.viewer.classList.add("removePageBorders"),this.#To(),this.eventBus.on("thumbnailrendered",({pageNumber:e,pdfPage:t})=>{const i=this._pages[e-1];this.#to.has(i)||t?.cleanup()},Q),e.l10n||this.l10n.translate(this.container)}get printingAllowed(){return this.#uo}get pagesCount(){return this._pages.length}getPageView(e){return this._pages[e]}getCachedPageViews(){return new Set(this.#to)}get pageViewsReady(){return this._pages.every(e=>e?.pdfPage)}clearSelection(){const e=document.getSelection();if(e&&!e.isCollapsed)for(let t=0,i=e.rangeCount;t<i;t++)if(e.getRangeAt(t).intersectsNode(this.viewer))return e.removeAllRanges?.(),void e.empty?.()}get renderForms(){return this.#Tr===ae.ENABLE_FORMS}get enableScripting(){return!!this._scriptingManager}get currentPageNumber(){return this._currentPageNumber}set currentPageNumber(e){if(!Number.isInteger(e))throw new Error("Invalid page number.");this.pdfDocument&&(this._currentPageNumber!==e&&this.clearSelection(),this._setCurrentPageNumber(e,!0)||console.error(`currentPageNumber: "${e}" is not a valid page.`))}_setCurrentPageNumber(e,t=!1){if(this._currentPageNumber===e)return t&&this.#Lo(),!0;if(!(0<e&&e<=this.pagesCount))return!1;const i=this._currentPageNumber;return this._currentPageNumber=e,this.eventBus.dispatch("pagechanging",{source:this,pageNumber:e,pageLabel:this._pageLabels?.[e-1]??null,previous:i}),t&&this.#Lo(),!0}get currentPageLabel(){return this._pageLabels?.[this._currentPageNumber-1]??null}set currentPageLabel(e){if(!this.pdfDocument)return;let t=0|e;if(this._pageLabels){const i=this._pageLabels.indexOf(e);i>=0&&(t=i+1)}this._currentPageNumber!==t&&this.clearSelection(),this._setCurrentPageNumber(t,!0)||console.error(`currentPageLabel: "${e}" is not a valid page.`)}get currentScale(){return 0!==this._currentScale?this._currentScale:1}set currentScale(e){if(isNaN(e))throw new Error("Invalid numeric scale.");this.pdfDocument&&this.#_o(e,{noScroll:!1})}get currentScaleValue(){return this._currentScaleValue}set currentScaleValue(e){this.pdfDocument&&this.#_o(e,{noScroll:!1})}get pagesRotation(){return this._pagesRotation}set pagesRotation(e){if(!_(e))throw new Error("Invalid pages rotation angle.");if(!this.pdfDocument)return;if((e%=360)<0&&(e+=360),this._pagesRotation===e)return;this.clearSelection(),this._pagesRotation=e;const t=this._currentPageNumber;this.refresh(!0,{rotation:e}),this._currentScaleValue&&this.#_o(this._currentScaleValue,{noScroll:!0}),this.eventBus.dispatch("rotationchanging",{source:this,pagesRotation:e,pageNumber:t}),this.defaultRenderingQueue&&this.update()}get firstPagePromise(){return this.pdfDocument?this._firstPageCapability.promise:null}get onePageRendered(){return this.pdfDocument?this._onePageRenderedCapability.promise:null}get pagesPromise(){return this.pdfDocument?this._pagesCapability.promise:null}get _layerProperties(){const e=this;return Ge(this,"_layerProperties",{get annotationEditorUIManager(){return e.#ao},get annotationStorage(){return e.pdfDocument?.annotationStorage},get downloadManager(){return e.downloadManager},get enableComment(){return!!e.#Ra},get enableScripting(){return!!e._scriptingManager},get fieldObjectsPromise(){return e.pdfDocument?.getFieldObjects()},get findController(){return e.findController},get hasJSActionsPromise(){return e.pdfDocument?.hasJSActions()},get linkService(){return e.linkService}})}#Mo(e){const t={annotationEditorMode:this.#so,annotationMode:this.#Tr,textLayerMode:this.#Or};return e?(this.#uo=e.includes(Ue.PRINT_HIGH_QUALITY)||e.includes(Ue.PRINT),this.eventBus.dispatch("printingallowed",{source:this,isAllowed:this.#uo}),e.includes(Ue.COPY)||this.#Or!==u||(t.textLayerMode=g),e.includes(Ue.MODIFY_CONTENTS)||(t.annotationEditorMode=ie.DISABLE),e.includes(Ue.MODIFY_ANNOTATIONS)||e.includes(Ue.FILL_INTERACTIVE_FORMS)||this.#Tr!==ae.ENABLE_FORMS||(t.annotationMode=ae.ENABLE),t):(this.#uo=!0,this.eventBus.dispatch("printingallowed",{source:this,isAllowed:this.#uo}),t)}async#Io(e){if("hidden"===document.visibilityState||!this.container.offsetParent||0===this._getVisiblePages().views.length)return;const t=Promise.withResolvers(),i=new AbortController;document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&t.resolve()},{signal:AbortSignal.any([e,i.signal])}),await Promise.race([this._onePageRenderedCapability.promise,t.promise]),i.abort()}async getAllText(e=null){const t=[],i=[];for(let n=1,s=this.pdfDocument.numPages;n<=s;++n){if(e?.aborted)return null;i.length=0;const s=await this.pdfDocument.getPage(n),{items:a}=await s.getTextContent();for(const e of a)e.str&&i.push(e.str),e.hasEOL&&i.push("\n");t.push(P(i.join("")))}return t.join("\n")}#Ao(e,t){const i=document.getSelection(),{focusNode:n,anchorNode:s}=i;if(s&&n&&i.containsNode(this.#bo)){if(this.#fo||e===g)return void Ke(t);this.#fo=!0;const{classList:i}=this.viewer;i.add("copyAll");const n=new AbortController,s=new AbortController;window.addEventListener("keydown",e=>{"Escape"===e.key&&s.abort()},{signal:n.signal}),this.getAllText(s.signal).then(async e=>{null!==e&&await navigator.clipboard.writeText(e)}).catch(e=>{console.warn(`Something goes wrong when extracting the text: ${e.message}`)}).finally(()=>{this.#fo=!1,n.abort(),i.remove("copyAll")}),Ke(t)}}setDocument(e){if(this.pdfDocument&&(this.eventBus.dispatch("pagesdestroy",{source:this}),this._cancelRendering(),this._resetView(),this.findController?.setDocument(null),this._scriptingManager?.setDocument(null),this.#ao?.destroy(),this.#ao=null,this.#so=ie.NONE,this.#uo=!0),this.pdfDocument=e,!e)return;const t=e.numPages,i=e.getPage(1),n=e.getOptionalContentConfig({intent:"display"}),s=this.#wr?e.getPermissions():Promise.resolve(),{eventBus:a,pageColors:r,viewer:o}=this;this.#$i=new AbortController;const{signal:l}=this.#$i,d={signal:l,...Q};if(t>Ds){console.warn("Forcing PAGE-scrolling for performance reasons, given the length of the document.");const e=this._scrollMode=p.PAGE;a.dispatch("scrollmodechanged",{source:this,mode:e})}this._pagesCapability.promise.then(()=>{a.dispatch("pagesloaded",{source:this,pagesCount:t})},()=>{});a.on("pagerender",e=>{const t=this._pages[e.pageNumber-1];t&&this.#to.push(t)},d);const h=e=>{e.cssTransform||e.isDetailView||(this._onePageRenderedCapability.resolve({timestamp:e.timestamp}),a.off("pagerendered",h))};a.on("pagerendered",h,d),Promise.all([i,s]).then(([i,s])=>{if(e!==this.pdfDocument)return;this._firstPageCapability.resolve(i),this._optionalContentConfigPromise=n;const{annotationEditorMode:d,annotationMode:h,textLayerMode:u}=this.#Mo(s);if(u!==c){const e=this.#bo=document.createElement("div");e.id="hiddenCopyElement",e.style.cssText="position:absolute;top:0;left:0;width:0;height:0;display:none",o.before(e)}if(d!==ie.DISABLE){const t=d;e.isPureXfa?console.warn("Warning: XFA-editing is not implemented."):Rs(t)?(this.#ao=new ne(this.container,o,this.#So,this.#io,this.#Ra,this.#Co,a,e,r,this.#no,this.#lo,this.#do,this.#ho,this.#de,this.#oo,this.#Po),a.dispatch("annotationeditoruimanager",{source:this,uiManager:this.#ao}),t!==ie.NONE&&(this.#Bo(t),this.#ao.updateMode(t))):console.error(`Invalid AnnotationEditor mode: ${t}`)}const g=this._scrollMode===p.PAGE?null:o,f=this.currentScale,b=i.getViewport({scale:f*ze.PDF_TO_CSS_UNITS});o.style.setProperty("--scale-factor",b.scale),r?.background&&o.style.setProperty("--page-bg-color",r.background),"CanvasText"!==r?.foreground&&"Canvas"!==r?.background||(o.style.setProperty("--hcm-highlight-filter",e.filterFactory.addHighlightHCMFilter("highlight","CanvasText","Canvas","HighlightText","Highlight")),o.style.setProperty("--hcm-highlight-selected-filter",e.filterFactory.addHighlightHCMFilter("highlight_selected","CanvasText","Canvas","HighlightText","ButtonText")));for(let e=1;e<=t;++e){const t=new ks({container:g,eventBus:a,id:e,scale:f,defaultViewport:b.clone(),optionalContentConfigPromise:n,renderingQueue:this.renderingQueue,textLayerMode:u,annotationMode:h,imageResourcesPath:this.imageResourcesPath,maxCanvasPixels:this.maxCanvasPixels,maxCanvasDim:this.maxCanvasDim,capCanvasAreaFactor:this.capCanvasAreaFactor,enableDetailCanvas:this.enableDetailCanvas,enableOptimizedPartialRendering:this.enableOptimizedPartialRendering,enableSelectionRendering:this.enableSelectionRendering,imagesRightClickMinSize:this.imagesRightClickMinSize,pageColors:r,l10n:this.l10n,layerProperties:this._layerProperties,enableAutoLinking:this.#_r,minDurationToUpdateCanvas:this.#co,commentManager:this.#Ra,abortSignal:this.#os});this._pages.push(t)}this._pages[0]?.setPdfPage(i),this._scrollMode===p.PAGE?this.#ko():this._spreadMode!==m.NONE&&this._updateSpreadMode(),a.on("annotationeditorlayerrendered",e=>{this.#ao&&a.dispatch("annotationeditormodechanged",{source:this,mode:this.#so})},{once:!0,signal:l,...Q}),this.#Io(l).then(async()=>{if(e!==this.pdfDocument)return;if(this.findController?.setDocument(e),this._scriptingManager?.setDocument(e),this.#bo&&document.addEventListener("copy",this.#Ao.bind(this,u),{signal:l}),e.loadingParams.disableAutoFetch||t>Ns)return void this._pagesCapability.resolve();let i=t-1;if(i<=0)this._pagesCapability.resolve();else for(let n=2;n<=t;++n){const t=e.getPage(n).then(e=>{const t=this._pages[n-1];t.pdfPage||t.setPdfPage(e),0===--i&&this._pagesCapability.resolve()},e=>{console.error(`Unable to get page ${n} to initialize viewer`,e),0===--i&&this._pagesCapability.resolve()});n%Os===0&&await t}}),a.dispatch("pagesinit",{source:this}),e.getMetadata().then(({info:t})=>{e===this.pdfDocument&&t.Language&&(o.lang=t.Language)}),this.defaultRenderingQueue&&this.update()}).catch(e=>{console.error("Unable to initialize viewer",e),this._pagesCapability.reject(e)})}onPagesEdited({pagesMapper:e,type:t,hasBeenCut:i,pageNumbers:n}){if("copy"===t){this.#Eo=new Map;for(const e of n)this.#Eo.set(e,this._pages[e-1]);return}if("cancelCopy"===t)return void(this.#Eo=null);if(("cut"===t||"delete"===t)&&(this.#xo=this._pages,this.#Is=n),"cancelDelete"===t){if(this.#Is=null,!this.#xo)return;const e=this._scrollMode===p.PAGE?null:this.viewer;if(e){this.#ao?.startUpdatePages();const t=document.createDocumentFragment();for(let e=0,i=this.#xo.length;e<i;e++){const i=this.#xo[e];i.updatePageNumber(e+1),t.append(i.div)}e.replaceChildren(t),this.#ao?.endUpdatePages()}return this._pages=this.#xo,void(this.#xo=null)}if("cleanSavedData"===t){if(this.#Is){if(this.#xo){for(const e of this.#Is)this.#xo[e-1].deleteMe();this.#xo=null}this.#Is=null}return}this._currentPageNumber=0;const s=this._pages,a=this._pages=[];this.#ao?.startUpdatePages();for(let t=1,n=e.pagesNumber;t<=n;t++){const n=e.getPrevPageNumber(t);if(n<0){let e=this.#Eo.get(-n);i?e.updatePageNumber(t):(this.#ao?.clonePage(-n-1,t-1),e=e.clone(t)),a.push(e);continue}const r=s[n-1];a.push(r),r.updatePageNumber(t)}this.#ao?.endUpdatePages(),"paste"===t&&(this.#Eo=null);const r=this._scrollMode===p.PAGE?null:this.viewer;if(r){const e=document.createDocumentFragment();for(const{div:t}of a)e.append(t);r.replaceChildren(e)}setTimeout(()=>{this.forceRendering()})}setPageLabels(e){if(this.pdfDocument){e?Array.isArray(e)&&this.pdfDocument.numPages===e.length?this._pageLabels=e:(this._pageLabels=null,console.error("setPageLabels: Invalid page labels.")):this._pageLabels=null;for(let e=0,t=this._pages.length;e<t;e++)this._pages[e].setPageLabel(this._pageLabels?.[e]??null)}}_resetView(){this._pages=[],this._currentPageNumber=1,this._currentScale=0,this._currentScaleValue=null,this._pageLabels=null,this.#to=new js(10),this._location=null,this._pagesRotation=0,this._optionalContentConfigPromise=null,this._firstPageCapability=Promise.withResolvers(),this._onePageRenderedCapability=Promise.withResolvers(),this._pagesCapability=Promise.withResolvers(),this._scrollMode=p.VERTICAL,this._previousScrollMode=p.UNKNOWN,this._spreadMode=m.NONE,this.#wo={previousPageNumber:1,scrollDown:!0,pages:[]},this.#$i?.abort(),this.#$i=null,this.viewer.textContent="",this._updateScrollMode(),this.viewer.removeAttribute("lang"),this.#bo?.remove(),this.#bo=null,this.#Do(),this.#No()}#ko(){if(this._scrollMode!==p.PAGE)throw new Error("#ensurePageViewVisible: Invalid scrollMode value.");const e=this._currentPageNumber,t=this.#wo,i=this.viewer;if(i.textContent="",t.pages.length=0,this._spreadMode!==m.NONE||this.isInPresentationMode){const n=new Set,s=this._spreadMode-1;-1===s?n.add(e-1):e%2!==s?(n.add(e-1),n.add(e)):(n.add(e-2),n.add(e-1));const a=document.createElement("div");if(a.className="spread",this.isInPresentationMode){const e=document.createElement("div");e.className="dummyPage",a.append(e)}for(const e of n){const i=this._pages[e];i&&(a.append(i.div),t.pages.push(i))}i.append(a)}else{const n=this._pages[e-1];i.append(n.div),t.pages.push(n)}t.scrollDown=e>=t.previousPageNumber,t.previousPageNumber=e}_scrollUpdate(){0!==this.pagesCount&&(this.#go&&clearTimeout(this.#go),this.#go=setTimeout(()=>{this.#go=null,this.update()},100),this.update())}#Oo(e,t=null){const{div:i,id:n}=e;if(this._currentPageNumber!==n&&this._setCurrentPageNumber(n),this._scrollMode===p.PAGE&&(this.#ko(),this.update()),!t&&!this.isInPresentationMode){const e=i.offsetLeft+i.clientLeft,n=e+i.clientWidth,{scrollLeft:s,clientWidth:a}=this.container;(this._scrollMode===p.HORIZONTAL||e<s||n>s+a)&&(t={left:0,top:0})}!function(e,t){let i=e.offsetParent;if(!i)return void console.error("offsetParent is not set -- cannot scroll");let n=e.offsetTop+e.clientTop,s=e.offsetLeft+e.clientLeft;for(;i.clientHeight===i.scrollHeight&&i.clientWidth===i.scrollWidth;)if(n+=i.offsetTop,s+=i.offsetLeft,i=i.offsetParent,!i)return;t&&(void 0!==t.top&&(n+=t.top),void 0!==t.left&&(s+=t.left,i.scrollLeft=s)),i.scrollTop=n}(i,t),!this._currentScaleValue&&this._location&&(this._location=null)}#Ro(e){return e===this._currentScale||Math.abs(e-this._currentScale)<1e-15}#jo(e,t,{noScroll:i=!1,preset:n=!1,drawingDelay:s=-1,origin:a=null}){if(this.clearSelection(),this._currentScaleValue=t.toString(),this.#Ro(e))return void(n&&this.eventBus.dispatch("scalechanging",{source:this,scale:e,presetValue:t}));this.viewer.style.setProperty("--scale-factor",e*ze.PDF_TO_CSS_UNITS);const r=s>=0&&s<1e3;this.refresh(!0,{scale:e,drawingDelay:r?s:-1}),r&&(this.#yo=setTimeout(()=>{this.#yo=null,this.refresh()},s));const o=this._currentScale;if(this._currentScale=e,!i){let t,i=this._currentPageNumber;if(!this._location||this.isInPresentationMode||this.isChangingPresentationMode||(i=this._location.pageNumber,t=[null,{name:"XYZ"},this._location.left,this._location.top,null]),this.scrollPageIntoView({pageNumber:i,destArray:t,allowNegativeOffset:!0}),Array.isArray(a)){const t=e/o-1,[i,n]=this.containerTopLeft;this.container.scrollLeft+=(a[0]-n)*t,this.container.scrollTop+=(a[1]-i)*t}}this.eventBus.dispatch("scalechanging",{source:this,scale:e,presetValue:n?t:void 0}),this.defaultRenderingQueue&&this.update()}get#Vo(){return this._spreadMode!==m.NONE&&this._scrollMode!==p.HORIZONTAL?2:1}#_o(e,t){let i=parseFloat(e);if(i>0)t.preset=!1,this.#jo(i,e,t);else{const n=this._pages[this._currentPageNumber-1];if(!n)return;let s=40,a=5;this.isInPresentationMode?(s=a=4,this._spreadMode!==m.NONE&&(s*=2)):this.removePageBorders?s=a=0:this._scrollMode===p.HORIZONTAL&&([s,a]=[a,s]);const r=(this.container.clientWidth-s)/n.width*n.scale/this.#Vo,o=(this.container.clientHeight-a)/n.height*n.scale;switch(e){case"page-actual":i=1;break;case"page-width":i=r;break;case"page-height":i=o;break;case"page-fit":i=Math.min(r,o);break;case"auto":const t=A(n)?r:Math.min(o,r);i=Math.min(1.25,t);break;default:return void console.error(`#setScale: "${e}" is an unknown zoom value.`)}t.preset=!0,this.#jo(i,e,t)}}#Lo(){const e=this._pages[this._currentPageNumber-1];this.isInPresentationMode&&this.#_o(this._currentScaleValue,{noScroll:!0}),this.#Oo(e)}pageLabelToPageNumber(e){if(!this._pageLabels)return null;const t=this._pageLabels.indexOf(e);return t<0?null:t+1}scrollPageIntoView({pageNumber:t,destArray:i=null,allowNegativeOffset:n=!1,ignoreDestinationZoom:s=!1,center:a=null}){if(!this.pdfDocument)return;const r=Number.isInteger(t)&&this._pages[t-1];if(!r)return void console.error(`scrollPageIntoView: "${t}" is not a valid pageNumber parameter.`);if(this.isInPresentationMode||!i)return void this._setCurrentPageNumber(t,!0);let o,l,d=0,h=0,c=0,u=0;const g=r.rotation%180!=0,p=(g?r.height:r.width)/r.scale/ze.PDF_TO_CSS_UNITS,m=(g?r.width:r.height)/r.scale/ze.PDF_TO_CSS_UNITS;let f=0;switch(i[1].name){case"XYZ":d=i[2],h=i[3],f=i[4],d=null!==d?d:0,h=null!==h?h:m;break;case"Fit":case"FitB":f="page-fit";break;case"FitH":case"FitBH":h=i[2],f="page-width",null===h&&this._location?(d=this._location.left,h=this._location.top):("number"!=typeof h||h<0)&&(h=m);break;case"FitV":case"FitBV":d=i[2],c=p,u=m,f="page-height";break;case"FitR":d=i[2],h=i[3],c=i[4]-d,u=i[5]-h;let e=40,t=5;this.removePageBorders&&(e=t=0),o=(this.container.clientWidth-e)/c/ze.PDF_TO_CSS_UNITS,l=(this.container.clientHeight-t)/u/ze.PDF_TO_CSS_UNITS,f=Math.min(Math.abs(o),Math.abs(l));break;default:return void console.error(`scrollPageIntoView: "${i[1].name}" is not a valid destination type.`)}if(s||(f&&f!==this._currentScale?this.currentScaleValue=f:0===this._currentScale&&(this.currentScaleValue=e)),"page-fit"===f&&!i[4])return void this.#Oo(r);const b=[r.viewport.convertToViewportPoint(d,h),r.viewport.convertToViewportPoint(d+c,h+u)];let v=Math.min(b[0][0],b[1][0]),w=Math.min(b[0][1],b[1][1]);a?("both"!==a&&"vertical"!==a||(w-=(this.container.clientHeight-Math.abs(b[1][1]-b[0][1]))/2),"both"!==a&&"horizontal"!==a||(v-=(this.container.clientWidth-Math.abs(b[1][0]-b[0][0]))/2)):n||(v=Math.max(v,0),w=Math.max(w,0)),this.#Oo(r,{left:v,top:w})}_updateLocation(e){const t=this._currentScale,i=this._currentScaleValue,n=parseFloat(i)===t?Math.round(1e4*t)/100:i,s=e.id,a=this._pages[s-1],r=this.container,o=a.getPagePoint(r.scrollLeft-e.x,r.scrollTop-e.y),l=Math.round(o[0]),d=Math.round(o[1]);let h=`#page=${s}`;this.isInPresentationMode||(h+=`&zoom=${n},${l},${d}`),this._location={pageNumber:s,scale:n,top:d,left:l,rotation:this._pagesRotation,pdfOpenParams:h}}update(){const e=this._getVisiblePages(),t=e.views,i=t.length;if(0===i)return;const n=Math.max(10,2*i+1);this.#to.resize(n,e.ids);for(const{view:e,visibleArea:i}of t)e.updateVisibleArea(i);for(const t of this.#to)e.ids.has(t.id)||t.updateVisibleArea(null);this.renderingQueue.renderHighestPriority(e);const s=this._spreadMode===m.NONE&&(this._scrollMode===p.PAGE||this._scrollMode===p.VERTICAL),a=this._currentPageNumber;let r=!1;for(const e of t){if(e.percent<100)break;if(e.id===a&&s){r=!0;break}}this._setCurrentPageNumber(r?this._currentPageNumber:t[0].id),this._updateLocation(e.first),this.eventBus.dispatch("updateviewarea",{source:this,location:this._location})}#Fo(){const e=this._getVisiblePages(),t=[],{ids:i,views:n}=e;for(const e of n){const{view:n}=e;n.hasEditableAnnotations()?t.push(e):i.delete(n.id)}return 0===t.length?null:(this.renderingQueue.renderHighestPriority({first:t[0],last:t.at(-1),views:t,ids:i}),i)}containsElement(e){return this.container.contains(e)}focus(){this.container.focus()}get _isContainerRtl(){return"rtl"===getComputedStyle(this.container).direction}get isInPresentationMode(){return this.presentationModeState===s}get isChangingPresentationMode(){return this.presentationModeState===n}get isHorizontalScrollbarEnabled(){return!this.isInPresentationMode&&this.container.scrollWidth>this.container.clientWidth}get isVerticalScrollbarEnabled(){return!this.isInPresentationMode&&this.container.scrollHeight>this.container.clientHeight}_getVisiblePages(){const e=this._scrollMode===p.PAGE?this.#wo.pages:this._pages,t=this._scrollMode===p.HORIZONTAL,i=t&&this._isContainerRtl;return T({scrollEl:this.container,views:e,sortByVisibility:!0,horizontal:t,rtl:i})}cleanup(){for(const e of this._pages)e.renderingState!==rs.FINISHED&&e.reset()}_cancelRendering(){for(const e of this._pages)e.cancelRendering()}async#ma(e){if(e.pdfPage)return e.pdfPage;try{const t=await this.pdfDocument.getPage(e.id);return e.pdfPage||e.setPdfPage(t),t}catch(e){return console.error("Unable to get page for page view",e),null}}#fa(e){if(1===e.first?.id)return!0;if(e.last?.id===this.pagesCount)return!1;switch(this._scrollMode){case p.PAGE:return this.#wo.scrollDown;case p.HORIZONTAL:return this.scroll.right}return this.scroll.down}forceRendering(e){const t=e||this._getVisiblePages(),i=this.#fa(t),n=this._spreadMode!==m.NONE&&this._scrollMode!==p.HORIZONTAL,s=null!==this.#yo||null!==this.#go&&t.views.some(e=>e.detailView?.renderingCancelled),a=this.renderingQueue.getHighestPriority(t,this._pages,i,n,s);return!!a&&(this.#ma(a).then(()=>{this.renderingQueue.renderView(a)}),!0)}get hasEqualPageSizes(){const e=this._pages[0];for(let t=1,i=this._pages.length;t<i;++t){const i=this._pages[t];if(i.width!==e.width||i.height!==e.height)return!1}return!0}getPagesOverview(){let e;return this._pages.map(t=>{const i=t.pdfPage.getViewport({scale:1}),n=A(i);if(void 0===e)e=n;else if(this.enablePrintAutoRotate&&n!==e)return{width:i.height,height:i.width,rotation:(i.rotation-90)%360};return{width:i.width,height:i.height,rotation:i.rotation}})}get optionalContentConfigPromise(){return this.pdfDocument?this._optionalContentConfigPromise?this._optionalContentConfigPromise:(console.error("optionalContentConfigPromise: Not initialized yet."),this.pdfDocument.getOptionalContentConfig({intent:"display"})):Promise.resolve(null)}set optionalContentConfigPromise(e){if(!(e instanceof Promise))throw new Error(`Invalid optionalContentConfigPromise: ${e}`);this.pdfDocument&&this._optionalContentConfigPromise&&(this._optionalContentConfigPromise=e,this.refresh(!1,{optionalContentConfigPromise:e}),this.eventBus.dispatch("optionalcontentconfigchanged",{source:this,promise:e}))}get scrollMode(){return this._scrollMode}set scrollMode(e){if(this._scrollMode!==e){if(!M(e))throw new Error(`Invalid scroll mode: ${e}`);this.pagesCount>Ds||(this._previousScrollMode=this._scrollMode,this.clearSelection(),this._scrollMode=e,this.eventBus.dispatch("scrollmodechanged",{source:this,mode:e}),this._updateScrollMode(this._currentPageNumber))}}_updateScrollMode(e=null){const t=this._scrollMode,i=this.viewer;i.classList.toggle("scrollHorizontal",t===p.HORIZONTAL),i.classList.toggle("scrollWrapped",t===p.WRAPPED),this.pdfDocument&&e&&(t===p.PAGE?this.#ko():this._previousScrollMode===p.PAGE&&this._updateSpreadMode(),this._currentScaleValue&&isNaN(this._currentScaleValue)&&this.#_o(this._currentScaleValue,{noScroll:!0}),this._setCurrentPageNumber(e,!0),this.update())}get spreadMode(){return this._spreadMode}set spreadMode(e){if(this._spreadMode!==e){if(!I(e))throw new Error(`Invalid spread mode: ${e}`);this.clearSelection(),this._spreadMode=e,this.eventBus.dispatch("spreadmodechanged",{source:this,mode:e}),this._updateSpreadMode(this._currentPageNumber)}}_updateSpreadMode(e=null){if(!this.pdfDocument)return;const t=this.viewer,i=this._pages;if(this._scrollMode===p.PAGE)this.#ko();else if(t.textContent="",this._spreadMode===m.NONE)for(const e of this._pages)t.append(e.div);else{const e=this._spreadMode-1;let n=null;for(let s=0,a=i.length;s<a;++s)null===n?(n=document.createElement("div"),n.className="spread",t.append(n)):s%2===e&&(n=n.cloneNode(!1),t.append(n)),n.append(i[s].div)}e&&(this._currentScaleValue&&isNaN(this._currentScaleValue)&&this.#_o(this._currentScaleValue,{noScroll:!0}),this._setCurrentPageNumber(e,!0),this.update())}#Uo(e,t=!1){switch(this._scrollMode){case p.WRAPPED:{const{views:i}=this._getVisiblePages(),n=new Map;for(const{id:e,y:t,percent:s,widthPercent:a}of i)0===s||a<100||n.getOrInsertComputed(t,Me).push(e);for(const i of n.values()){const n=i.indexOf(e);if(-1===n)continue;const s=i.length;if(1===s)break;if(t)for(let t=n-1,s=0;t>=s;t--){const n=i[t],s=i[t+1]-1;if(n<s)return e-s}else for(let t=n+1,a=s;t<a;t++){const n=i[t],s=i[t-1]+1;if(n>s)return s-e}if(t){const t=i[0];if(t<e)return e-t+1}else{const t=i[s-1];if(t>e)return t-e+1}break}break}case p.HORIZONTAL:break;case p.PAGE:case p.VERTICAL:{if(this._spreadMode===m.NONE)break;const i=this._spreadMode-1;if(t&&e%2!==i)break;if(!t&&e%2===i)break;const{views:n}=this._getVisiblePages(),s=t?e-1:e+1;for(const{id:e,percent:t,widthPercent:i}of n)if(e===s){if(t>0&&100===i)return 2;break}break}}return 1}nextPage(){const e=this._currentPageNumber,t=this.pagesCount;if(e>=t)return!1;const i=this.#Uo(e,!1)||1;return this.currentPageNumber=Math.min(e+i,t),!0}previousPage(){const e=this._currentPageNumber;if(e<=1)return!1;const t=this.#Uo(e,!0)||1;return this.currentPageNumber=Math.max(e-t,1),!0}updateScale({drawingDelay:e,scaleFactor:t=null,steps:i=null,origin:n}){if(null===i&&null===t)throw new Error("Invalid updateScale options: either `steps` or `scaleFactor` must be provided.");if(!this.pdfDocument)return;let s=this._currentScale;if(t>0&&1!==t)s=Math.round(s*t*100)/100;else if(i){const e=i>0?1.1:1/1.1,t=i>0?Math.ceil:Math.floor;i=Math.abs(i);do{s=t(10*(s*e).toFixed(2))/10}while(--i>0)}s=Be(s,.1,25),this.#_o(s,{noScroll:!1,drawingDelay:e,origin:n})}increaseScale(e={}){this.updateScale({...e,steps:e.steps??1})}decreaseScale(e={}){this.updateScale({...e,steps:-(e.steps??1)})}#To(e=this.container.clientHeight){e!==this.#vo&&(this.#vo=e,k.setProperty("--viewer-container-height",`${e}px`))}#Hi(e){for(const t of e)if(t.target===this.container){this.#To(Math.floor(t.borderBoxSize[0].blockSize)),this.#ro=null;break}}get containerTopLeft(){return this.#ro||=[this.container.offsetTop,this.container.offsetLeft]}#Do(){null!==this.#yo&&(clearTimeout(this.#yo),this.#yo=null),null!==this.#go&&(clearTimeout(this.#go),this.#go=null)}#No(){this.#po?.abort(),this.#po=null,null!==this.#mo&&(clearTimeout(this.#mo),this.#mo=null)}#Bo(e){switch(e){case ie.STAMP:this.#de?.loadModel("altText");break;case ie.SIGNATURE:this.#Co?.loadSignatures()}}get annotationEditorMode(){return this.#ao?this.#so:ie.DISABLE}set annotationEditorMode({mode:e,editId:t=null,isFromKeyboard:i=!1,mustEnterInEditMode:n=!1,editComment:s=!1}){if(!this.#ao)throw new Error("The AnnotationEditor is not enabled.");if(this.#so===e)return;if(!Rs(e))throw new Error(`Invalid AnnotationEditor mode: ${e}`);if(!this.pdfDocument)return;this.#Bo(e);const{eventBus:a,pdfDocument:r}=this,o=async()=>{this.#No(),this.#so=e,await this.#ao.updateMode(e,t,!0,i,n,s),e===this.#so&&r===this.pdfDocument&&a.dispatch("annotationeditormodechanged",{source:this,mode:e})};if(e===ie.NONE||this.#so===ie.NONE){const t=e!==ie.NONE;t||this.pdfDocument.annotationStorage.resetModifiedIds(),this.cleanup();for(const e of this._pages)e.toggleEditingMode(t);const i=this.#Fo();if(t&&i){this.#No(),this.#po=new AbortController;const e=AbortSignal.any([this.#$i.signal,this.#po.signal]);return void a.on("pagerendered",({pageNumber:e})=>{i.delete(e),0===i.size&&(this.#mo=setTimeout(o,0))},{signal:e,...Q})}}o()}refresh(e=!1,t=Object.create(null)){if(this.pdfDocument){for(const e of this._pages)e.update(t);this.#Do(),e||this.update()}}}class Fs{#a;constructor(e,t){this.#a=e;const i=[{element:e.presentationModeButton,eventName:"presentationmode",close:!0},{element:e.printButton,eventName:"print",close:!0},{element:e.downloadButton,eventName:"download",close:!0},{element:e.viewBookmarkButton,eventName:null,close:!0},{element:e.firstPageButton,eventName:"firstpage",close:!0},{element:e.lastPageButton,eventName:"lastpage",close:!0},{element:e.pageRotateCwButton,eventName:"rotatecw",close:!1},{element:e.pageRotateCcwButton,eventName:"rotateccw",close:!1},{element:e.cursorSelectToolButton,eventName:"switchcursortool",eventDetails:{tool:f},close:!0},{element:e.cursorHandToolButton,eventName:"switchcursortool",eventDetails:{tool:b},close:!0},{element:e.scrollPageButton,eventName:"switchscrollmode",eventDetails:{mode:p.PAGE},close:!0},{element:e.scrollVerticalButton,eventName:"switchscrollmode",eventDetails:{mode:p.VERTICAL},close:!0},{element:e.scrollHorizontalButton,eventName:"switchscrollmode",eventDetails:{mode:p.HORIZONTAL},close:!0},{element:e.scrollWrappedButton,eventName:"switchscrollmode",eventDetails:{mode:p.WRAPPED},close:!0},{element:e.spreadNoneButton,eventName:"switchspreadmode",eventDetails:{mode:m.NONE},close:!0},{element:e.spreadOddButton,eventName:"switchspreadmode",eventDetails:{mode:m.ODD},close:!0},{element:e.spreadEvenButton,eventName:"switchspreadmode",eventDetails:{mode:m.EVEN},close:!0},{element:e.imageAltTextSettingsButton,eventName:"imagealttextsettings",close:!0},{element:e.documentPropertiesButton,eventName:"documentproperties",close:!0}];i.push({element:e.openFileButton,eventName:"openfile",close:!0}),this.eventBus=t,this.opened=!1,this.#Ie(i),this.reset()}get isOpen(){return this.opened}setPageNumber(e){this.pageNumber=e,this.#xe()}setPagesCount(e){this.pagesCount=e,this.#xe()}reset(){this.pageNumber=0,this.pagesCount=0,this.#xe(),this.eventBus.dispatch("switchcursortool",{source:this,reset:!0}),this.#zo({mode:p.VERTICAL}),this.#Ho({mode:m.NONE})}#xe(){const{firstPageButton:e,lastPageButton:t,pageRotateCwButton:i,pageRotateCcwButton:n}=this.#a;e.disabled=this.pageNumber<=1,t.disabled=this.pageNumber>=this.pagesCount,i.disabled=0===this.pagesCount,n.disabled=0===this.pagesCount}#Ie(e){const{eventBus:t}=this,{toggleButton:i}=this.#a;i.addEventListener("click",this.toggle.bind(this));for(const{element:i,eventName:n,close:s,eventDetails:a}of e)i.addEventListener("click",e=>{null!==n&&t.dispatch(n,{source:this,...a}),s&&this.close(),t.dispatch("reporttelemetry",{source:this,details:{type:"buttons",data:{id:i.id}}})});t.on("cursortoolchanged",this.#$o.bind(this),Q),t.on("scrollmodechanged",this.#zo.bind(this),Q),t.on("spreadmodechanged",this.#Ho.bind(this),Q)}#$o({tool:e,disabled:t}){const{cursorSelectToolButton:i,cursorHandToolButton:n}=this.#a;R(i,e===f),R(n,e===b),i.disabled=t,n.disabled=t}#zo({mode:e}){const{scrollPageButton:t,scrollVerticalButton:i,scrollHorizontalButton:n,scrollWrappedButton:s,spreadNoneButton:a,spreadOddButton:r,spreadEvenButton:o}=this.#a;R(t,e===p.PAGE),R(i,e===p.VERTICAL),R(n,e===p.HORIZONTAL),R(s,e===p.WRAPPED);const l=this.pagesCount>Ds;t.disabled=l,i.disabled=l,n.disabled=l,s.disabled=l;const d=e===p.HORIZONTAL;a.disabled=d,r.disabled=d,o.disabled=d}#Ho({mode:e}){const{spreadNoneButton:t,spreadOddButton:i,spreadEvenButton:n}=this.#a;R(t,e===m.NONE),R(i,e===m.ODD),R(n,e===m.EVEN)}open(){if(this.opened)return;this.opened=!0;const{toggleButton:e,toolbar:t}=this.#a;V(e,!0,t)}close(){if(!this.opened)return;this.opened=!1;const{toggleButton:e,toolbar:t}=this.#a;V(e,!1,t)}toggle(){this.opened?this.close():this.open()}}class Us{#Wo;#Xo=null;#Go;#Yo;#L;#Ko;#I;#Zo=null;#qo;#Qo=null;#Jo="";#el=null;#tl;#il;#nl;#sl;#al;#rl=null;#ol=null;#ll;#dl;#hl;#cl;#ul;#gl;#pl;#ml;#fl=null;#bl;#vl=null;#wl=null;#yl=!1;#y;#Cl=!1;#u;#$;#Pl;#Sl;#G=null;static#El=null;constructor({dialog:e,panels:t,typeButton:i,typeInput:n,drawButton:s,drawPlaceholder:a,drawSVG:r,drawThickness:o,imageButton:l,imageSVG:d,imagePlaceholder:h,imagePicker:c,imagePickerLink:u,description:g,clearButton:p,cancelButton:m,addButton:f,errorCloseButton:b,errorBar:v,errorTitle:w,errorDescription:y,saveCheckbox:C,saveContainer:P},S,E,x,T,L,_){this.#Wo=f,this.#Go=p,this.#Yo=g.lastElementChild,this.#Ko=g.firstElementChild,this.#I=e,this.#tl=r,this.#qo=a,this.#il=o,this.#nl=v,this.#al=w,this.#sl=y,this.#cl=d,this.#hl=h,this.#ll=c,this.#dl=u,this.#$=x,this.#ul=C,this.#gl=P,this.#ml=E,this.#bl=n,this.#u=T,this.#Sl=L,this.#y=_,this.#Pl=new zs(S,x),Us.#El||=Object.freeze({signature:"pdfjs-editor-add-signature-description-default-when-drawing",errorUploadTitle:"pdfjs-editor-add-signature-image-upload-error-title",errorUploadDescription:"pdfjs-editor-add-signature-image-upload-error-description",errorNoDataTitle:"pdfjs-editor-add-signature-image-no-data-error-title",errorNoDataDescription:"pdfjs-editor-add-signature-image-no-data-error-description"}),e.addEventListener("close",this.#K.bind(this)),e.addEventListener("contextmenu",e=>{const{target:t}=e;t!==this.#bl&&t!==this.#Ko&&e.preventDefault()}),e.addEventListener("drop",e=>{Ke(e)}),m.addEventListener("click",this.#x.bind(this)),f.addEventListener("click",this.#xl.bind(this)),p.addEventListener("click",()=>{this.#pe({type:"signature",action:"pdfjs.signature.clear",data:{type:this.#vl}}),this.#Tl(null)},{passive:!0}),this.#Ko.addEventListener("input",()=>{this.#Yo.disabled=""===this.#Ko.value},{passive:!0}),this.#Yo.addEventListener("click",()=>{this.#Ko.value="",this.#Yo.disabled=!0},{passive:!0}),b.addEventListener("click",()=>{v.hidden=!0},{passive:!0}),this.#Ll(i,s,l,t),c.accept=Ze.join(","),_.on("storedsignatureschanged",this.#_l.bind(this),Q),x.register(e)}#Ll(e,t,i,n){const s=this.#pl=new Map([["type",e],["draw",t],["image",i]]),a=e=>{for(const[t,i]of s)i===e.target?(i.setAttribute("aria-selected",!0),i.setAttribute("tabindex",0),n.setAttribute("data-selected",t),this.#Tl(t)):(i.setAttribute("aria-selected",!1),i.setAttribute("tabindex",-1))},r=Array.from(s.values());for(let e=0,t=r.length;e<t;e++){const t=r[e];t.addEventListener("click",a,{passive:!0}),t.addEventListener("keydown",({key:t})=>{"ArrowLeft"!==t&&"ArrowRight"!==t||r[e+("ArrowLeft"===t?-1:1)]?.focus()},{passive:!0})}}#Ml(){this.#yl=!1,this.#Ko.value="",this.#vl&&(this.#Xo.get(this.#vl).value="")}#Il(e){switch(e){case"type":this.#bl.value="";break;case"draw":this.#Zo=null,this.#el=null,this.#Jo="",this.#Qo?.remove(),this.#Qo=null,this.#qo.hidden=!1,this.#il.value=1;break;case"image":this.#hl.hidden=!1,this.#ol?.remove(),this.#ol=null}}#Tl(e){if(e&&this.#vl===e)return;this.#vl&&(this.#Xo.get(this.#vl).value=this.#Ko.value),e&&(this.#vl=e),this.#nl.hidden=!0;const t=!e;switch(t?this.#Ml():this.#Ko.value=this.#Xo.get(this.#vl).value,this.#Yo.disabled=""===this.#Ko.value,this.#wl?.abort(),this.#wl=new AbortController,this.#vl){case"type":this.#Al(t);break;case"draw":this.#Bl(t);break;case"image":this.#kl(t)}}#Dl(e){e&&this.#Cl||(this.#ul.disabled=!e),this.#Go.disabled=this.#Wo.disabled=this.#Ko.disabled=!e}#Al(e){e&&this.#Il("type"),this.#Dl(this.#bl.value);const{signal:t}=this.#wl,i={passive:!0,signal:t};this.#bl.addEventListener("input",()=>{const{value:e}=this.#bl;this.#yl||(this.#Xo.get("type").default=this.#Ko.value=e,this.#Yo.disabled=""===e),this.#Dl(e)},i),this.#Ko.addEventListener("input",()=>{this.#yl=this.#bl.value!==this.#Ko.value},i)}#Bl(e){e&&this.#Il("draw"),this.#Dl(this.#Qo);const{signal:t}=this.#wl,i={signal:t};let n=NaN;const s=e=>{const{pointerId:a}=e;if(!isNaN(n)&&n!==a)return;n=a,e.preventDefault(),this.#tl.setPointerCapture(a);const{width:r,height:o}=this.#tl.getBoundingClientRect();let{offsetX:l,offsetY:d}=e;if(l=Math.round(l),d=Math.round(d),e.target===this.#qo&&(this.#qo.hidden=!0),!this.#Zo){this.#Zo={width:r,height:o,thickness:parseInt(this.#il.value,10),curves:[]},this.#Dl(!0);const e=new ue,t=this.#Qo=e.createElement("path");t.setAttribute("stroke-width",this.#il.value),this.#tl.append(t),this.#tl.addEventListener("pointerdown",s,i),this.#qo.removeEventListener("pointerdown",s),""===this.#Ko.value&&this.#u.get(Us.#El.signature).then(e=>{this.#Xo.get("draw").default=e,this.#Ko.value||=e,this.#Yo.disabled=""===this.#Ko.value})}this.#el=[l,d],this.#Zo.curves.push({points:this.#el}),this.#Jo+=`M ${l} ${d}`,this.#Qo.setAttribute("d",this.#Jo);const h=new AbortController,c={signal:AbortSignal.any([t,h.signal])};this.#tl.addEventListener("contextmenu",ke,c),this.#tl.addEventListener("pointermove",e=>{e.preventDefault();let{offsetX:t,offsetY:i}=e;t=Math.round(t),i=Math.round(i);const n=this.#el;if(!(t<0||i<0||t>r||i>o||t===n.at(-2)&&i===n.at(-1))){if(n.length>=4){const[e,s,a,r]=n.slice(-4);this.#Jo+=`C${(e+5*a)/6} ${(s+5*r)/6} ${(5*a+t)/6} ${(5*r+i)/6} ${(a+t)/2} ${(r+i)/2}`}else this.#Jo+=`L${t} ${i}`;n.push(t,i),this.#Qo.setAttribute("d",this.#Jo)}},c),this.#tl.addEventListener("pointerup",e=>{const{pointerId:t}=e;(isNaN(n)||n===t)&&(n=NaN,e.preventDefault(),this.#tl.releasePointerCapture(t),h.abort(),2===this.#el.length&&(this.#Jo+=`L${this.#el[0]} ${this.#el[1]}`,this.#Qo.setAttribute("d",this.#Jo)))},c)};this.#Zo?this.#tl.addEventListener("pointerdown",s,i):this.#qo.addEventListener("pointerdown",s,i),this.#il.addEventListener("input",()=>{const{value:e}=this.#il;this.#il.setAttribute("data-l10n-args",JSON.stringify({thickness:e})),this.#Zo&&(this.#Qo.setAttribute("stroke-width",e),this.#Zo.thickness=e)},i)}#Nl(e){this.#al.setAttribute("data-l10n-id",Us.#El[`error${e}Title`]),this.#sl.setAttribute("data-l10n-id",Us.#El[`error${e}Description`]),this.#nl.hidden=!1}#kl(e){e&&this.#Il("image"),this.#Dl(this.#ol);const{signal:t}=this.#wl,i={signal:t},n={passive:!0,signal:t};this.#dl.addEventListener("keydown",e=>{const{key:t}=e;"Enter"!==t&&" "!==t||(Ke(e),this.#ll.click())},i),this.#ll.addEventListener("click",()=>{this.#I.classList.toggle("waiting",!0)},n),this.#ll.addEventListener("change",async()=>{const e=this.#ll.files?.[0];if(!e||!Ze.includes(e.type))return this.#Nl("Upload"),void this.#I.classList.toggle("waiting",!1);await this.#Ol(e)},n),this.#ll.addEventListener("cancel",()=>{this.#I.classList.toggle("waiting",!1)},n),this.#hl.addEventListener("dragover",e=>{const{dataTransfer:t}=e;for(const{type:i}of t.items)if(Ze.includes(i))return t.dropEffect="copy"===t.effectAllowed?"copy":"move",void Ke(e);t.dropEffect="none"},i),this.#hl.addEventListener("drop",e=>{const{dataTransfer:{files:t}}=e;if(t?.length){for(const e of t)if(Ze.includes(e.type)){this.#Ol(e);break}Ke(e),this.#I.classList.toggle("waiting",!0)}},i)}async#Ol(e){let t;try{t=await this.#G.imageManager.getFromFile(e)}catch(e){console.error("SignatureManager.#extractSignature.",e)}if(!t)return this.#Nl("Upload"),void this.#I.classList.toggle("waiting",!1);const i=this.#rl=this.#L.getFromImage(t.bitmap);if(!i)return this.#Nl("NoData"),void this.#I.classList.toggle("waiting",!1);const{outline:n}=i;this.#hl.hidden=!0,this.#Dl(!0);const s=new ue,a=this.#ol=s.createElement("path");this.#cl.setAttribute("viewBox",n.viewBox),this.#cl.setAttribute("preserveAspectRatio","xMidYMid meet"),this.#cl.append(a),a.setAttribute("d",n.toSVGPath()),this.#Xo.get("image").default=e.name,""===this.#Ko.value&&(this.#Ko.value=e.name||"",this.#Yo.disabled=""===this.#Ko.value),this.#I.classList.toggle("waiting",!1)}#Rl(){return this.#L.getFromText(this.#bl.value,window.getComputedStyle(this.#bl))}#jl(){const{width:e,height:t}=this.#tl.getBoundingClientRect();return this.#L.getDrawnSignature(this.#Zo,e,t)}#pe(e){this.#y.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:e}})}#Vl(e,t,i){const{curves:n,areContours:s,thickness:a,width:r,height:o}=e,l=Math.max(r,o),d=Ye.processDrawnLines({lines:{curves:n,thickness:a,width:r,height:o},pageWidth:l,pageHeight:l,rotation:0,innerMargin:0,mustSmooth:!1,areContours:s});if(!d)return;const{outline:h}=d,c=new ue,u=document.createElement("div"),g=document.createElement("button");g.addEventListener("click",()=>{this.#y.dispatch("switchannotationeditorparams",{source:this,type:te.CREATE,value:{signatureData:{lines:{curves:n,thickness:a,width:r,height:o},mustSmooth:!1,areContours:s,description:i,uuid:t,heightInPage:40}}})}),u.append(g),u.classList.add("toolbarAddSignatureButtonContainer");const p=c.create(1,1,!0);g.append(p);const m=document.createElement("span");m.ariaHidden=!0,g.append(m),g.classList.add("toolbarAddSignatureButton"),g.type="button",m.textContent=i,g.setAttribute("data-l10n-id","pdfjs-editor-add-saved-signature-button"),g.setAttribute("data-l10n-args",JSON.stringify({description:i})),g.tabIndex=0;const f=c.createElement("path");p.append(f),p.setAttribute("viewBox",h.viewBox),p.setAttribute("preserveAspectRatio","xMidYMid meet"),s&&f.classList.add("contours"),f.setAttribute("d",h.toSVGPath());const b=document.createElement("button");u.append(b),b.classList.add("toolbarButton","deleteButton"),b.setAttribute("data-l10n-id","pdfjs-editor-delete-signature-button1"),b.type="button",b.tabIndex=0,b.addEventListener("click",async()=>{await this.#Sl.delete(t)&&(u.remove(),this.#pe({type:"signature",action:"pdfjs.signature.delete_saved",data:{savedCount:await this.#Sl.size()}}))});const v=document.createElement("span");b.append(v),v.setAttribute("data-l10n-id","pdfjs-editor-delete-signature-button-label1"),this.#ml.before(u)}async#_l(){const e=this.#ml.parentElement;for(;e.firstElementChild!==this.#ml;)e.firstElementChild.remove();this.#fl=null,await this.loadSignatures(!0)}getSignature(e){return this.open(e)}async loadSignatures(e=!1){if(!this.#ml||!e&&this.#ml.previousElementSibling||!this.#Sl)return;if(!this.#fl&&(this.#fl=this.#Sl.getAll().then(async e=>[e,await Promise.all(Array.from(e.values(),({signatureData:e})=>Ye.decompressSignature(e)))]),!e))return;const[t,i]=await this.#fl;this.#fl=null;let n=0;for(const[e,{description:s}]of t){const t=i[n++];t&&(t.curves=t.outlines.map(e=>({points:e})),delete t.outlines,this.#Vl(t,e,s))}}async renderEditButton(e){const t=document.createElement("button");t.classList.add("altText","editDescription"),t.tabIndex=0,e.description&&(t.title=e.description);const i=document.createElement("span");return t.append(i),i.setAttribute("data-l10n-id","pdfjs-editor-add-signature-edit-button-label"),t.addEventListener("click",()=>{this.#Pl.open(e)},{passive:!0}),t}async open({uiManager:e,editor:t}){this.#Xo||=new Map(this.#pl.keys().map(e=>[e,{value:"",default:""}])),this.#G=e,this.#L=t,this.#G.removeEditListeners();const i=this.#Cl=await this.#Sl.isFull();this.#gl.classList.toggle("fullStorage",i),this.#ul.checked=!i,await this.#$.open(this.#I);const n=this.#pl.get("type");n.focus(),n.click()}#x(){this.#re()}#re(){this.#$.closeIfActive(this.#I)}#K(){null===this.#L._drawId&&this.#L.remove(),this.#G?.addEditListeners(),this.#wl?.abort(),this.#wl=null,this.#G=null,this.#L=null,this.#Ml();for(const[e]of this.#pl)this.#Il(e);this.#Dl(!1),this.#vl=null,this.#Xo=null}async#xl(){let e;const t=this.#vl;switch(t){case"type":e=this.#Rl();break;case"draw":e=this.#jl();break;case"image":e=this.#rl}let i=null;const n=this.#Ko.value;if(this.#ul.checked){const{newCurves:t,areContours:s,thickness:a,width:r,height:o}=e,l=await Ye.compressSignature({outlines:t,areContours:s,thickness:a,width:r,height:o});i=await this.#Sl.create({description:n,signatureData:l}),i?this.#Vl({curves:t.map(e=>({points:e})),areContours:s,thickness:a,width:r,height:o},i,n):console.warn("SignatureManager.add: cannot save the signature.")}const s=this.#Xo.get(t);this.#pe({type:"signature",action:"pdfjs.signature.created",data:{type:t,saved:!!i,savedCount:await this.#Sl.size(),descriptionChanged:n!==s.default}}),this.#L.addSignature(e,40,this.#Ko.value,i),this.#re()}destroy(){this.#G=null,this.#re()}}class zs{#L;#Fl;#Ko;#I;#$;#Ul;#G;constructor({dialog:e,description:t,cancelButton:i,updateButton:n,editSignatureView:s},a){const r=this.#Ko=t.firstElementChild;this.#Ul=s,this.#I=e,this.#$=a,e.addEventListener("close",this.#K.bind(this)),e.addEventListener("contextmenu",e=>{e.target!==this.#Ko&&e.preventDefault()}),i.addEventListener("click",this.#x.bind(this)),n.addEventListener("click",this.#zl.bind(this));const o=t.lastElementChild;o.addEventListener("click",()=>{r.value="",o.disabled=!0,n.disabled=""===this.#Fl}),r.addEventListener("input",()=>{const{value:e}=r;o.disabled=""===e,n.disabled=e===this.#Fl,s.setAttribute("aria-label",e)},{passive:!0}),a.register(e)}async open(e){this.#G=e._uiManager,this.#L=e,this.#Fl=this.#Ko.value=e.description,this.#Ko.dispatchEvent(new Event("input")),this.#G.removeEditListeners();const{areContours:t,outline:i}=e.getSignaturePreview(),n=(new ue).createElement("path");this.#Ul.append(n),this.#Ul.setAttribute("viewBox",i.viewBox),n.setAttribute("d",i.toSVGPath()),t&&n.classList.add("contours"),await this.#$.open(this.#I)}async#zl(){this.#L._reportTelemetry({action:"pdfjs.signature.edit_description",data:{hasBeenChanged:!0}}),this.#L.description=this.#Ko.value,this.#re()}#x(){this.#L._reportTelemetry({action:"pdfjs.signature.edit_description",data:{hasBeenChanged:!1}}),this.#re()}#re(){this.#$.closeIfActive(this.#I)}#K(){this.#G?.addEditListeners(),this.#G=null,this.#L=null,this.#Ul.firstElementChild.remove()}}class Hs{#Hl=null;#a;constructor(e,t,i=0){this.#a=e,this.eventBus=t;const n=[{element:e.previous,eventName:"previouspage"},{element:e.next,eventName:"nextpage"},{element:e.zoomIn,eventName:"zoomin"},{element:e.zoomOut,eventName:"zoomout"},{element:e.print,eventName:"print"},{element:e.download,eventName:"download"},{element:e.editorCommentButton,eventName:"switchannotationeditormode",eventDetails:{get mode(){const{classList:t}=e.editorCommentButton;return t.contains("toggled")?ie.NONE:ie.POPUP}}},{element:e.editorFreeTextButton,eventName:"switchannotationeditormode",eventDetails:{get mode(){const{classList:t}=e.editorFreeTextButton;return t.contains("toggled")?ie.NONE:ie.FREETEXT}}},{element:e.editorHighlightButton,eventName:"switchannotationeditormode",eventDetails:{get mode(){const{classList:t}=e.editorHighlightButton;return t.contains("toggled")?ie.NONE:ie.HIGHLIGHT}}},{element:e.editorInkButton,eventName:"switchannotationeditormode",eventDetails:{get mode(){const{classList:t}=e.editorInkButton;return t.contains("toggled")?ie.NONE:ie.INK}}},{element:e.editorStampButton,eventName:"switchannotationeditormode",eventDetails:{get mode(){const{classList:t}=e.editorStampButton;return t.contains("toggled")?ie.NONE:ie.STAMP}},telemetry:{type:"editing",data:{action:"pdfjs.image.icon_click"}}},{element:e.editorSignatureButton,eventName:"switchannotationeditormode",eventDetails:{get mode(){const{classList:t}=e.editorSignatureButton;return t.contains("toggled")?ie.NONE:ie.SIGNATURE}}}];this.#Ie(n),this.#$l({value:i}),this.reset()}#$l({value:e}){let t="normal";switch(e){case 1:t="compact";break;case 2:t="touch"}document.documentElement.setAttribute("data-toolbar-density",t)}setPageNumber(e,t){this.pageNumber=e,this.pageLabel=t,this.#xe(!1)}setPagesCount(e,t){this.pagesCount=e,this.hasPageLabels=t,this.#xe(!0)}setPageScale(e,t){this.pageScaleValue=(e||t).toString(),this.pageScale=t,this.#xe(!1)}reset(){this.#Hl=null,this.pageNumber=0,this.pageLabel=null,this.hasPageLabels=!1,this.pagesCount=0,this.pageScaleValue=e,this.pageScale=1,this.#xe(!0),this.updateLoadingIndicatorState(),this.#Wl({mode:ie.DISABLE})}#Ie(e){const{eventBus:t}=this,{editorHighlightColorPicker:i,editorHighlightButton:n,pageNumber:s,scaleSelect:a}=this.#a,r=this;for(const{element:i,eventName:n,eventDetails:s,telemetry:a}of e)i.addEventListener("click",e=>{null!==n&&t.dispatch(n,{source:this,...s,isFromKeyboard:0===e.detail}),a&&t.dispatch("reporttelemetry",{source:this,details:a})});s.addEventListener("click",function(){this.select()}),s.addEventListener("change",function(){t.dispatch("pagenumberchanged",{source:r,value:this.value})}),t.on("pagesedited",({pagesMapper:e})=>{const t=e.pagesNumber;t!==this.pagesCount&&this.setPagesCount(t,this.hasPageLabels)},Q),a.addEventListener("change",function(){"custom"!==this.value&&t.dispatch("scalechanged",{source:r,value:this.value})}),a.addEventListener("click",function({target:e}){this.value===r.pageScaleValue&&"OPTION"===e.tagName.toUpperCase()&&this.blur()}),a.oncontextmenu=ke,t.on("annotationeditormodechanged",this.#Wl.bind(this),Q),t.on("showannotationeditorui",({mode:e})=>{if(e===ie.HIGHLIGHT)n.click()},Q),t.on("toolbardensity",this.#$l.bind(this),Q),i&&(t.on("annotationeditoruimanager",({uiManager:e})=>{const t=this.#Hl=new de({uiManager:e});e.setMainHighlightColorPicker(t),i.append(t.renderMainDropdown())},Q),t.on("mainhighlightcolorpickerupdatecolor",({value:e})=>{this.#Hl?.updateColor(e)},Q))}#Wl({mode:e}){const{editorCommentButton:t,editorCommentParamsToolbar:i,editorFreeTextButton:n,editorFreeTextParamsToolbar:s,editorHighlightButton:a,editorHighlightParamsToolbar:r,editorInkButton:o,editorInkParamsToolbar:l,editorStampButton:d,editorStampParamsToolbar:h,editorSignatureButton:c,editorSignatureParamsToolbar:u}=this.#a;V(t,e===ie.POPUP,i),V(n,e===ie.FREETEXT,s),V(a,e===ie.HIGHLIGHT,r),V(o,e===ie.INK,l),V(d,e===ie.STAMP,h),V(c,e===ie.SIGNATURE,u),t.disabled=n.disabled=a.disabled=o.disabled=d.disabled=c.disabled=e===ie.DISABLE}#xe(e=!1){const{pageNumber:t,pagesCount:i,pageScaleValue:n,pageScale:s}=this,a=this.#a;e&&(this.hasPageLabels?(a.pageNumber.type="text",a.numPages.setAttribute("data-l10n-id","pdfjs-page-of-pages")):(a.pageNumber.type="number",a.numPages.setAttribute("data-l10n-id","pdfjs-of-pages"),a.numPages.setAttribute("data-l10n-args",JSON.stringify({pagesCount:i}))),a.pageNumber.max=i),this.hasPageLabels?(a.pageNumber.value=this.pageLabel,a.numPages.setAttribute("data-l10n-args",JSON.stringify({pageNumber:t,pagesCount:i}))):a.pageNumber.value=t,a.previous.disabled=t<=1,a.next.disabled=t>=i,a.zoomOut.disabled=s<=.1,a.zoomIn.disabled=s>=25;let r=!1;for(const e of a.scaleSelect.options)e.value===n?(e.selected=!0,r=!0):e.selected=!1;r||(a.customScaleOption.selected=!0,a.customScaleOption.setAttribute("data-l10n-args",JSON.stringify({scale:Math.round(1e4*s)/100})))}updateLoadingIndicatorState(e=!1){const{pageNumber:t}=this.#a;t.classList.toggle("loading",e)}}class $s{constructor(e,t=20){this.fingerprint=e,this.cacheSize=t,this._initializedPromise=this._readFromStorage().then(e=>{const t=JSON.parse(e||"{}");let i=-1;if(Array.isArray(t.files)){for(;t.files.length>=this.cacheSize;)t.files.shift();for(let e=0,n=t.files.length;e<n;e++){if(t.files[e].fingerprint===this.fingerprint){i=e;break}}}else t.files=[];-1===i&&(i=t.files.push({fingerprint:this.fingerprint})-1),this.file=t.files[i],this.database=t})}async _writeToStorage(){const e=JSON.stringify(this.database);localStorage.setItem("pdfjs.history",e)}async _readFromStorage(){return localStorage.getItem("pdfjs.history")}async set(e,t){return await this._initializedPromise,this.file[e]=t,this._writeToStorage()}async setMultiple(e){await this._initializedPromise;for(const t in e)this.file[t]=e[t];return this._writeToStorage()}async get(e,t){await this._initializedPromise;const i=this.file[e];return void 0!==i?i:t}async getMultiple(e){await this._initializedPromise;const t=Object.create(null);for(const i in e){const n=this.file[i];t[i]=void 0!==n?n:e[i]}return t}}const Ws="viewsManagerResizing",Xs="pdfSidebarNotification";class Gs extends Fi{static#El=null;#Xl=!window.matchMedia("(prefers-reduced-motion: reduce)").matches;constructor({elements:{outerContainer:e,sidebarContainer:t,toggleButton:i,resizer:n,thumbnailButton:s,outlineButton:a,attachmentsButton:r,layersButton:l,thumbnailsView:d,outlinesView:h,attachmentsView:c,layersView:u,viewsManagerAddFile:{button:g},viewsManagerCurrentOutlineButton:p,viewsManagerSelectorButton:m,viewsManagerSelectorOptions:f,viewsManagerHeaderLabel:b,viewsManagerStatus:v},eventBus:w,l10n:y,enableMerge:C=!1,enableSplitMerge:P=!1,globalAbortSignal:S}){super({sidebar:t,resizer:n,toggleButton:i},"ltr"===y.getDirection(),!1,S),this.isOpen=!1,this.active=o,this.isInitialViewSet=!1,this.isInitialEventDispatched=!1,this.onToggled=null,this.onUpdateThumbnails=null,this.outerContainer=e,this.sidebarContainer=t,this.toggleButton=i,this.resizer=n,this.thumbnailButton=s,this.outlineButton=a,this.attachmentsButton=r,this.layersButton=l,this.thumbnailsView=d,this.outlinesView=h,this.attachmentsView=c,this.layersView=u,this.viewsManagerAddFileButton=g,this.viewsManagerCurrentOutlineButton=p,this.viewsManagerHeaderLabel=b,this.viewsManagerStatus=v,this.eventBus=w,P||(v.hidden=!0),this._enableSplitMerge=P,this._enableMerge=C,C||(g.hidden=!0),this.menu=new hs(f,m,[s,a,r,l]),Gs.#El||=Object.freeze({pagesTitle:"pdfjs-views-manager-pages-title",outlinesTitle:"pdfjs-views-manager-outlines-title1",attachmentsTitle:"pdfjs-views-manager-attachments-title",layersTitle:"pdfjs-views-manager-layers-title1",notificationButton:"pdfjs-toggle-views-manager-notification-button",toggleButton:"pdfjs-toggle-views-manager-button1"}),this.#hi()}reset(){this.isInitialViewSet=!1,this.isInitialEventDispatched=!1,this.#Gl(!0),this.switchView(o),this.outlineButton.disabled=this.attachmentsButton.disabled=this.layersButton.disabled=!1,this.viewsManagerCurrentOutlineButton.disabled=!0}get visibleView(){return this.isOpen?this.active:r}setInitialView(e=r){this.isInitialViewSet||(this.isInitialViewSet=!0,e!==r&&e!==a?(this.switchView(e,!0),this.isInitialEventDispatched||this.#Yl()):this.#Yl())}switchView(e,t=!1){const i=e!==this.active;let n=!1,s=null;switch(e){case r:return void(this.isOpen&&this.close());case o:s="pagesTitle",this.isOpen&&i&&(n=!0);break;case l:if(s="outlinesTitle",this.outlineButton.disabled)return;break;case d:if(s="attachmentsTitle",this.attachmentsButton.disabled)return;break;case h:if(s="layersTitle",this.layersButton.disabled)return;break;default:return void console.error(`PDFSidebar.switchView: "${e}" is not a valid view.`)}this.viewsManagerStatus.hidden=!this._enableSplitMerge||e!==o,this.viewsManagerAddFileButton.hidden=!this._enableMerge||e!==o,this.viewsManagerCurrentOutlineButton.hidden=e!==l,this.viewsManagerHeaderLabel.setAttribute("data-l10n-id",Gs.#El[s]||""),this.active=e,j(this.thumbnailButton,e===o,this.thumbnailsView),j(this.outlineButton,e===l,this.outlinesView),j(this.attachmentsButton,e===d,this.attachmentsView),j(this.layersButton,e===h,this.layersView),!t||this.isOpen?(n&&(this.onUpdateThumbnails(),this.onToggled()),i&&this.#Yl()):this.open()}open(){this.isOpen||(this.isOpen=!0,this.onResizing(this.width),this._sidebar.hidden=!1,V(this.toggleButton,!0),this.switchView(this.active),this.#Xl?queueMicrotask(()=>{this.outerContainer.classList.add("viewsManagerMoving","viewsManagerOpen")}):(this.outerContainer.classList.add("viewsManagerOpen"),this.eventBus.dispatch("resize",{source:this})),this.active===o&&this.onUpdateThumbnails(),this.onToggled(),this.#Yl(),this.#Gl())}close(e=null){this.isOpen&&(this.isOpen=!1,this._sidebar.hidden=!0,V(this.toggleButton,!1),this.outerContainer.classList.add("viewsManagerMoving"),this.outerContainer.classList.remove("viewsManagerOpen"),this.onToggled(),this.#Yl(),e?.detail>0&&this.toggleButton.blur())}toggle(e=null){super.toggle(),this.isOpen?this.close(e):this.open()}#Yl(){this.isInitialViewSet&&(this.isInitialEventDispatched||=!0),this.eventBus.dispatch("sidebarviewchanged",{source:this,view:this.visibleView})}#Kl(){this.toggleButton.setAttribute("data-l10n-id",Gs.#El.notificationButton),this.isOpen||this.toggleButton.classList.add(Xs)}#Gl(e=!1){(this.isOpen||e)&&this.toggleButton.classList.remove(Xs),e&&this.toggleButton.setAttribute("data-l10n-id",Gs.#El.toggleButton)}#hi(){const{eventBus:e,outerContainer:t}=this;this.#Xl&&this.sidebarContainer.addEventListener("transitionend",i=>{i.target===this.sidebarContainer&&(t.classList.remove("viewsManagerMoving"),e.dispatch("resize",{source:this}))}),this.viewsManagerHeaderLabel.addEventListener("dblclick",t=>{this.active!==l?this.active===h&&e.dispatch("resetlayers",{source:this}):e.dispatch("toggleoutlinetree",{source:this})}),this.thumbnailButton.addEventListener("click",()=>{this.switchView(o)}),this.outlineButton.addEventListener("click",()=>{this.switchView(l)}),this.attachmentsButton.addEventListener("click",()=>{this.switchView(d)}),this.layersButton.addEventListener("click",()=>{this.switchView(h)}),this.viewsManagerCurrentOutlineButton.addEventListener("click",()=>{e.dispatch("currentoutlineitem",{source:this})});const n=(e,t,i)=>{t.disabled=!e,e?this.#Kl():this.active===i&&this.switchView(o)};e.on("outlineloaded",e=>{n(e.outlineCount,this.outlineButton,l),e.currentOutlineItemPromise.then(e=>{this.isInitialViewSet&&(this.viewsManagerCurrentOutlineButton.disabled=!e)})},Q),e.on("attachmentsloaded",e=>{n(e.attachmentsCount,this.attachmentsButton,d)},Q),e.on("layersloaded",e=>{n(e.layersCount,this.layersButton,h)},Q),e.on("presentationmodechanged",e=>{e.state===i&&this.visibleView===o&&this.onUpdateThumbnails()},Q)}onStartResizing(){this.outerContainer.classList.add(Ws)}onStopResizing(){this.eventBus.dispatch("resize",{source:this}),this.outerContainer.classList.remove(Ws)}onResizing(e){k.setProperty("--viewsManager-width",`${e}px`)}}const Ys=-1,Ks=1,Zs={initialBookmark:document.location.hash.substring(1),_initializedCapability:{...Promise.withResolvers(),settled:!1},appConfig:null,pdfDocument:null,pdfLoadingTask:null,printService:null,pdfViewer:null,pdfThumbnailViewer:null,pdfRenderingQueue:null,pdfPresentationMode:null,pdfDocumentProperties:null,pdfLinkService:null,pdfTextExtractor:null,pdfHistory:null,viewsManager:null,pdfOutlineViewer:null,pdfAttachmentViewer:null,pdfLayerViewer:null,pdfCursorTools:null,pdfScriptingManager:null,store:null,downloadManager:null,overlayManager:null,preferences:new class extends gt{async _writeToStorage(e){localStorage.setItem("pdfjs.preferences",JSON.stringify(e))}async _readFromStorage(e){return{prefs:JSON.parse(localStorage.getItem("pdfjs.preferences"))}}},toolbar:null,secondaryToolbar:null,eventBus:null,l10n:null,annotationEditorParams:null,imageAltTextSettings:null,isInitialViewSet:!1,isViewerEmbedded:window.parent!==window,url:"",baseUrl:"",mlManager:null,_downloadUrl:"",_eventBusAC:null,_windowAC:null,_globalAbortController:new AbortController,documentInfo:null,metadata:null,_contentDispositionFilename:null,_contentLength:null,_saveInProgress:!1,_wheelUnusedTicks:0,_wheelUnusedFactor:1,_touchManager:null,_touchUnusedTicks:0,_touchUnusedFactor:1,_PDFBug:null,_hasAnnotationEditors:!1,_title:document.title,_printAnnotationStoragePromise:null,_isCtrlKeyDown:!1,_caretBrowsing:null,_isScrolling:!1,editorUndoBar:null,_printPermissionPromise:null,async initialize(e){this.appConfig=e;try{await this.preferences.initializedPromise}catch(e){console.error("initialize:",e)}let t;switch(Z.get("pdfBugEnabled")&&await this._parseHashParams(),Z.get("viewerCssTheme")){case 1:t="light";break;case 2:t="dark"}t&&k.setProperty("color-scheme",t),this.l10n=await this.externalServices.createL10n(),document.getElementsByTagName("html")[0].dir=this.l10n.getDirection(),this.l10n.translate(e.appContainer||document.documentElement),this.isViewerEmbedded&&Z.get("externalLinkTarget")===at.NONE&&Z.set("externalLinkTarget",at.TOP),await this._initializeViewerComponents(),this.bindEvents(),this.bindWindowEvents(),this._initializedCapability.settled=!0,this._initializedCapability.resolve()},async _parseHashParams(){const e=document.location.hash.substring(1);if(!e)return;const{mainContainer:t,viewerContainer:i}=this.appConfig,n=y(e),s=async()=>{if(this._PDFBug)return;const{PDFBug:e}=await import(Z.get("debuggerSrc"));this._PDFBug=e};if("true"===n.get("disableworker"))try{Se.workerSrc||=Z.get("workerSrc"),await import(Fe.workerSrc),Z.set("workerPort",null)}catch(e){console.error("_parseHashParams:",e)}if(n.has("textlayer"))switch(n.get("textlayer")){case"off":Z.set("textLayerMode",c);break;case"visible":case"shadow":case"hover":i.classList.add(`textLayer-${n.get("textlayer")}`);try{await s(),this._PDFBug.loadCSS()}catch(e){console.error("_parseHashParams:",e)}}if(n.has("pdfbug")){const e=n.get("pdfbug").split(",");try{await s(),this._PDFBug.init(t,e)}catch(e){console.error("_parseHashParams:",e)}const i={pdfBug:!0,fontExtraProperties:!0};globalThis.StepperManager?.enabled&&(i.minDurationToUpdateCanvas=0),Z.setAll(i)}n.has("locale")&&Z.set("localeProperties",{lang:n.get("locale")});const a={disableAutoFetch:e=>"true"===e,disableFontFace:e=>"true"===e,disableHistory:e=>"true"===e,disableRange:e=>"true"===e,disableStream:e=>"true"===e,verbosity:e=>0|e};for(const e in a){const t=a[e],i=e.toLowerCase();n.has(i)&&Z.set(e,t(n.get(i)))}},async _initializeViewerComponents(){const{appConfig:e,externalServices:t,l10n:i,mlManager:n}=this,s=this._globalAbortController.signal,a=new ct;this.eventBus=Z.eventBus=a,n?.setEventBus(a,s);const r=this.overlayManager=new Yi,o=this.pdfRenderingQueue=new ls;o.onIdle=this._cleanup.bind(this);const l=this.pdfLinkService=new rt({eventBus:a,externalLinkTarget:Z.get("externalLinkTarget"),externalLinkRel:Z.get("externalLinkRel"),ignoreDestinationZoom:Z.get("ignoreDestinationZoom")}),d=this.downloadManager=new Xi,h=this.findController=new On({linkService:l,eventBus:a,updateMatchesCountOnProgress:!0}),c=this.pdfScriptingManager=new ds({eventBus:a,externalServices:t,docProperties:this._scriptingDocProperties.bind(this)}),u=e.mainContainer,g=e.viewerContainer,p=Z.get("annotationEditorMode"),m=Z.get("forcePageColors")||window.matchMedia("(forced-colors: active)").matches,f=m?{background:Z.get("pageColorsBackground"),foreground:Z.get("pageColorsForeground")}:null,b=Z.get("enableMerge"),v=Z.get("enableSplitMerge");let w;w=Z.get("enableUpdatedAddImage")?e.newAltTextDialog?new Di(e.newAltTextDialog,r,a):null:e.altTextDialog?new Oi(e.altTextDialog,u,r,a):null,e.editorUndoBar&&(this.editorUndoBar=new Gi(e.editorUndoBar,a));const y=Z.get("enableSignatureEditor")&&e.addSignatureDialog?new Us(e.addSignatureDialog,e.editSignatureDialog,e.annotationEditorParams?.editorSignatureAddSignature||null,r,i,t.createSignatureStorage(a,s),a):null,C=Z.get("enableComment")&&e.editCommentDialog?new Ui(e.editCommentDialog,{learnMoreUrl:Z.get("commentLearnMoreUrl"),sidebar:e.annotationEditorParams?.editorCommentsSidebar||null,sidebarResizer:e.annotationEditorParams?.editorCommentsSidebarResizer||null,commentsList:e.annotationEditorParams?.editorCommentsSidebarList||null,commentCount:e.annotationEditorParams?.editorCommentsSidebarCount||null,sidebarTitle:e.annotationEditorParams?.editorCommentsSidebarTitle||null,closeButton:e.annotationEditorParams?.editorCommentsSidebarCloseButton||null,commentToolbarButton:e.toolbar?.editorCommentButton||null},a,l,r,"ltr"===i.getDirection(),m,s):null,P=Z.get("maxCanvasPixels"),S=Z.get("maxCanvasDim"),E=Z.get("capCanvasAreaFactor"),x=this.pdfViewer=new Vs({container:u,viewer:g,viewerAlert:e.viewerAlert,eventBus:a,renderingQueue:o,linkService:l,downloadManager:d,altTextManager:w,commentManager:C,signatureManager:y,editorUndoBar:this.editorUndoBar,findController:h,scriptingManager:Z.get("enableScripting")&&c,l10n:i,textLayerMode:Z.get("textLayerMode"),annotationMode:Z.get("annotationMode"),annotationEditorMode:p,annotationEditorHighlightColors:Z.get("highlightEditorColors"),enableHighlightFloatingButton:Z.get("enableHighlightFloatingButton"),enableUpdatedAddImage:Z.get("enableUpdatedAddImage"),enableNewAltTextWhenAddingImage:Z.get("enableNewAltTextWhenAddingImage"),imageResourcesPath:Z.get("imageResourcesPath"),enablePrintAutoRotate:Z.get("enablePrintAutoRotate"),maxCanvasPixels:P,maxCanvasDim:S,capCanvasAreaFactor:E,enableDetailCanvas:Z.get("enableDetailCanvas"),enablePermissions:Z.get("enablePermissions"),enableOptimizedPartialRendering:Z.get("enableOptimizedPartialRendering"),enableSelectionRendering:Z.get("enableSelectionRendering"),imagesRightClickMinSize:Z.get("imagesRightClickMinSize"),pageColors:f,mlManager:n,abortSignal:s,supportsPinchToZoom:this.supportsPinchToZoom,enableAutoLinking:Z.get("enableAutoLinking"),minDurationToUpdateCanvas:Z.get("minDurationToUpdateCanvas")});if(o.setViewer(x),l.setViewer(x),c.setViewer(x),e.viewsManager?.thumbnailsView){const{viewsManager:t}=e;this.pdfThumbnailViewer=new gs({container:t.thumbnailsView,eventBus:a,renderingQueue:o,linkService:l,maxCanvasPixels:P,maxCanvasDim:S,pageColors:f,abortSignal:s,enableSplitMerge:v,enableMerge:b,enableNewBadge:Z.get("enableNewBadge"),statusBar:t.viewsManagerStatusBar,undoBar:t.viewsManagerUndoBar,manageMenu:t.manageMenu,waitingBar:t.viewsManagerWaitingBar,addFileComponent:t.viewsManagerAddFile}),o.setThumbnailViewer(this.pdfThumbnailViewer)}if(this.isViewerEmbedded||Z.get("disableHistory")||(this.pdfHistory=new Vn({linkService:l,eventBus:a}),l.setHistory(this.pdfHistory)),!this.supportsIntegratedFind&&e.findBar&&(this.findBar=new Rn(e.findBar,e.principalContainer,a)),e.annotationEditorParams)if(p!==ie.DISABLE){const t=e.toolbar?.editorSignatureButton;t&&Z.get("enableSignatureEditor")&&(t.parentElement.hidden=!1);const i=e.toolbar?.editorCommentButton;i&&Z.get("enableComment")&&(i.parentElement.hidden=!1),this.annotationEditorParams=new Ri(e.annotationEditorParams,a)}else for(const e of["editorModeButtons","editorModeSeparator"])document.getElementById(e)?.classList.add("hidden");n&&e.secondaryToolbar?.imageAltTextSettingsButton&&(this.imageAltTextSettings=new Ni(e.altTextSettingsDialog,r,a,n)),e.documentProperties&&(this.pdfDocumentProperties=new on(e.documentProperties,r,a,i,()=>this._docFilename,()=>this._docTitle)),e.secondaryToolbar?.cursorHandToolButton&&(this.pdfCursorTools=new tn({container:u,eventBus:a,cursorToolOnLoad:Z.get("cursorToolOnLoad")})),e.toolbar&&(this.toolbar=new Hs(e.toolbar,a,Z.get("toolbarDensity"))),e.secondaryToolbar&&(Z.get("enableAltText")&&(e.secondaryToolbar.imageAltTextSettingsButton?.classList.remove("hidden"),e.secondaryToolbar.imageAltTextSettingsSeparator?.classList.remove("hidden")),this.secondaryToolbar=new Fs(e.secondaryToolbar,a)),this.supportsFullscreen&&e.secondaryToolbar?.presentationModeButton&&(this.pdfPresentationMode=new Wn({container:u,pdfViewer:x,eventBus:a})),e.passwordOverlay&&(this.passwordPrompt=new Ki(e.passwordOverlay,r,this.isViewerEmbedded)),e.viewsManager?.outlinesView&&(this.pdfOutlineViewer=new Un({container:e.viewsManager.outlinesView,eventBus:a,l10n:i,linkService:l,downloadManager:d})),e.viewsManager?.attachmentsView&&(this.pdfAttachmentViewer=new Qi({container:e.viewsManager.attachmentsView,eventBus:a,l10n:i,downloadManager:d})),e.viewsManager?.layersView&&(this.pdfLayerViewer=new Fn({container:e.viewsManager.layersView,eventBus:a,l10n:i})),e.viewsManager&&(this.viewsManager=new Gs({elements:e.viewsManager,eventBus:a,l10n:i,enableMerge:b,enableSplitMerge:v,globalAbortSignal:s}),this.viewsManager.onToggled=this.forceRendering.bind(this),this.viewsManager.onUpdateThumbnails=()=>{for(const e of x.getCachedPageViews())e.renderingState===rs.FINISHED&&this.pdfThumbnailViewer.getThumbnail(e.id-1)?.setImage(e);this.pdfThumbnailViewer.scrollThumbnailIntoView(x.currentPageNumber)})},async run(e){await this.initialize(e);const{appConfig:t,eventBus:i}=this;let n;n=y(document.location.search.substring(1)).get("file")??Z.get("defaultUrl");try{n=new URL(n).href}catch{n=encodeURIComponent(n).replaceAll("%2F","/")}qs(n);const s=this._openFileInput=document.createElement("input");s.id="fileInput",s.hidden=!0,s.type="file",s.value=null,document.body.append(s),s.addEventListener("change",function(e){const{files:t}=e.target;t&&0!==t.length&&i.dispatch("fileinputchange",{source:this,fileInput:e.target})}),t.mainContainer.addEventListener("dragover",function(e){for(const t of e.dataTransfer.items)if("application/pdf"===t.type)return e.dataTransfer.dropEffect="copy"===e.dataTransfer.effectAllowed?"copy":"move",void Ke(e)}),t.mainContainer.addEventListener("drop",function(e){"application/pdf"===e.dataTransfer.files?.[0].type&&(Ke(e),i.dispatch("fileinputchange",{source:this,fileInput:e.dataTransfer}))}),Z.get("supportsDocumentFonts")||(Z.set("disableFontFace",!0),this.l10n.get("pdfjs-web-fonts-disabled").then(e=>{console.warn(e)}));const a=e=>{t.toolbar?.print?.classList.toggle("hidden",!e),t.secondaryToolbar?.printButton.classList.toggle("hidden",!e)};this.supportsPrinting?i.on("printingallowed",({isAllowed:e})=>a(e)):a(!1),this.supportsFullscreen||t.secondaryToolbar?.presentationModeButton.classList.add("hidden"),this.supportsIntegratedFind&&t.findBar?.toggleButton?.classList.add("hidden"),n?this.open({url:n}):this._hideViewBookmark()},get externalServices(){return Ge(this,"externalServices",new ki)},get initialized(){return this._initializedCapability.settled},get initializedPromise(){return this._initializedCapability.promise},updateZoom(e,t,i){this.pdfViewer.isInPresentationMode||this.pdfViewer.updateScale({drawingDelay:Z.get("defaultZoomDelay"),steps:e,scaleFactor:t,origin:i})},zoomIn(){this.updateZoom(1)},zoomOut(){this.updateZoom(-1)},zoomReset(){this.pdfViewer.isInPresentationMode||(this.pdfViewer.currentScaleValue=e)},touchPinchCallback(e,t,i){if(this.supportsPinchToZoom){const n=this._accumulateFactor(this.pdfViewer.currentScale,i/t,"_touchUnusedFactor");this.updateZoom(null,n,e)}else{const n=30,s=this._accumulateTicks((i-t)/n,"_touchUnusedTicks");this.updateZoom(s,null,e)}},touchPinchEndCallback(){this._touchUnusedTicks=0,this._touchUnusedFactor=1},get pagesCount(){return this.pdfDocument?this.pdfDocument.numPages:0},get page(){return this.pdfViewer.currentPageNumber},set page(e){this.pdfViewer.currentPageNumber=e},get supportsPrinting(){return Ge(this,"supportsPrinting",Z.get("supportsPrinting")&&as.supportsPrinting)},get supportsFullscreen(){return Ge(this,"supportsFullscreen",document.fullscreenEnabled)},get supportsPinchToZoom(){return Ge(this,"supportsPinchToZoom",Z.get("supportsPinchToZoom"))},get supportsIntegratedFind(){return Ge(this,"supportsIntegratedFind",Z.get("supportsIntegratedFind"))},get loadingBar(){const e=document.getElementById("loadingBar"),t=e?new D(e):null;return Ge(this,"loadingBar",t)},get supportsMouseWheelZoomCtrlKey(){return Ge(this,"supportsMouseWheelZoomCtrlKey",Z.get("supportsMouseWheelZoomCtrlKey"))},get supportsMouseWheelZoomMetaKey(){return Ge(this,"supportsMouseWheelZoomMetaKey",Z.get("supportsMouseWheelZoomMetaKey"))},get supportsCaretBrowsingMode(){return Z.get("supportsCaretBrowsingMode")},moveCaret(e,t){this._caretBrowsing||=new Vi(this._globalAbortController.signal,this.appConfig.mainContainer,this.appConfig.viewerContainer,this.appConfig.toolbar?.container),this._caretBrowsing.moveCaret(e,t)},setTitleUsingUrl(e="",t=null){this.url=e,this.baseUrl=et(e,"",!0),t&&(this._downloadUrl=t===e?this.baseUrl:et(t,"",!0)),Te(e)&&this._hideViewBookmark();let i=we(e,"");if(!i)try{i=decodeURIComponent(ve(e))}catch{}this.setTitle(i||e)},setTitle(e=this._title){if(this._title=e,this.isViewerEmbedded)return;const t=this._hasChanges()&&!this.pdfRenderingQueue.printing;document.title=`${t?"* ":""}${e}`},get _docFilename(){return this._contentDispositionFilename||we(this.url)},get _docTitle(){const{documentInfo:e,metadata:t}=this,i=t?.get("dc:title");return i&&"Untitled"!==i&&!/[\uFFF0-\uFFFF]/.test(i)?i:e.Title},_hideViewBookmark(){const{secondaryToolbar:e}=this.appConfig;e?.viewBookmarkButton.classList.add("hidden"),e?.presentationModeButton.classList.contains("hidden")&&document.getElementById("viewBookmarkSeparator")?.classList.add("hidden")},async close(){if(this._unblockDocumentLoadEvent(),this._hideViewBookmark(),!this.pdfLoadingTask)return;if(this._hasChanges()&&this._annotationStorageModified)try{await this.downloadOrSave()}catch{}const e=[];e.push(this.pdfLoadingTask.destroy()),this.pdfLoadingTask=null,this.pdfDocument&&(this.pdfDocument=null,this.pdfThumbnailViewer?.setDocument(null),this.pdfViewer.setDocument(null),this.pdfLinkService.setDocument(null),this.pdfDocumentProperties?.setDocument(null)),this.pdfLinkService.externalLinkEnabled=!0,this.store=null,this.isInitialViewSet=!1,this.url="",this.baseUrl="",this._downloadUrl="",this.documentInfo=null,this.metadata=null,this._contentDispositionFilename=null,this._contentLength=null,this._saveInProgress=!1,this._hasAnnotationEditors=!1,e.push(this.pdfScriptingManager.destroyPromise,this.passwordPrompt.close()),this.setTitle(),this.viewsManager?.reset(),this.pdfOutlineViewer?.reset(),this.pdfAttachmentViewer?.reset(),this.pdfLayerViewer?.reset(),this.pdfHistory?.reset(),this.findBar?.reset(),this.toolbar?.reset(),this.secondaryToolbar?.reset(),this._PDFBug?.cleanup(),await Promise.all(e)},async open(e){this.pdfLoadingTask&&await this.close();const t=Z.getAll(W);Object.assign(Se,t),e.data&&Le(e.filename)?this._contentDispositionFilename=e.filename:e.url&&this.setTitleUsingUrl(e.originalUrl||e.url,e.url);const i=Z.getAll($),n=be({...i,...e});return this.pdfLoadingTask=n,n.onPassword=(e,t)=>{this.isViewerEmbedded&&this._unblockDocumentLoadEvent(),this.pdfLinkService.externalLinkEnabled=!1,this.passwordPrompt.setUpdateCallback(e,t),this.passwordPrompt.open()},n.onProgress=e=>this.progress(e.percent),n.promise.then(e=>{this.load(e)},e=>{if(n!==this.pdfLoadingTask)return;this.loadingBar&&(this.loadingBar.percent||=0);let t="pdfjs-loading-error";return e instanceof xe?t="pdfjs-invalid-file-error":e instanceof We&&(t=e.missing?"pdfjs-missing-file-error":"pdfjs-unexpected-response-error"),this._documentError(t,{message:e.message}).then(()=>{throw e})})},async download(){let e;try{e=await(this.pdfDocument?this.pdfDocument.getData():this.pdfLoadingTask.getData())}catch{}this.downloadManager.download(e,this._downloadUrl,this._docFilename)},async save(){if(this._saveInProgress)return;this._saveInProgress=!0,await this.pdfScriptingManager.dispatchWillSave();try{const e=await this.pdfDocument.saveDocument();this.downloadManager.download(e,this._downloadUrl,this._docFilename)}catch(e){console.error("Error when saving the document:",e),await this.download()}finally{await this.pdfScriptingManager.dispatchDidSave(),this._saveInProgress=!1}const e=this.pdfDocument?.annotationStorage.editorStats;e&&this.externalServices.reportTelemetry({type:"editing",data:{type:"save",stats:e}})},async downloadOrSave(){const{classList:e}=this.appConfig.appContainer;e.add("wait"),this.pdfThumbnailViewer?.hasStructuralChanges()?(this.externalServices.reportTelemetry({type:"pageOrganization",data:{action:"save"}}),await this.onSavePages({data:this.pdfThumbnailViewer.getStructuralChanges()})):await(this.pdfDocument?.annotationStorage.size>0?this.save():this.download()),delete this._mergedDocumentNeedsSaving,this.setTitle(),e.remove("wait")},async _documentError(e,t=null){this._unblockDocumentLoadEvent();const i=await this._otherError(e||"pdfjs-loading-error",t);this.eventBus.dispatch("documenterror",{source:this,message:i,reason:t?.message??null})},async _otherError(e,t=null){const i=await this.l10n.get(e),n=[`PDF.js v${nt||"?"} (build: ${le||"?"})`];return t&&(n.push(`Message: ${t.message}`),t.stack?n.push(`Stack: ${t.stack}`):(t.filename&&n.push(`File: ${t.filename}`),t.lineNumber&&n.push(`Line: ${t.lineNumber}`))),console.error(`${i}\n\n${n.join("\n")}`),i},progress(e){!this.loadingBar||e<=this.loadingBar.percent||(this.loadingBar.percent=e,(this.pdfDocument?.loadingParams.disableAutoFetch??Z.get("disableAutoFetch"))&&this.loadingBar.setDisableAutoFetch())},load(t){this.pdfDocument=t,this._printPermissionPromise=new Promise(e=>{this.eventBus.on("printingallowed",({isAllowed:t})=>{e(t)},{once:!0})}),t.getDownloadInfo().then(({length:e})=>{this._contentLength=e,this.loadingBar?.hide(),u.then(()=>{this.eventBus.dispatch("documentloaded",{source:this})})});const i=t.getPageLayout().catch(()=>{}),n=t.getPageMode().catch(()=>{}),s=t.getOpenAction().catch(()=>{});this.toolbar?.setPagesCount(t.numPages,!1),this.secondaryToolbar?.setPagesCount(t.numPages),this.pdfLinkService.setDocument(t),this.pdfDocumentProperties?.setDocument(t);const c=this.pdfViewer;c.setDocument(t);const{firstPagePromise:u,onePageRendered:g,pagesPromise:f}=c;this.pdfThumbnailViewer?.setDocument(t);const b=(this.store=new $s(t.fingerprints[0])).getMultiple({page:null,zoom:e,scrollLeft:"0",scrollTop:"0",rotation:null,sidebarView:a,scrollMode:p.UNKNOWN,spreadMode:m.UNKNOWN}).catch(()=>{});u.then(e=>{this.loadingBar?.setWidth(this.appConfig.viewerContainer),this._initializeAnnotationStorageCallbacks(t),Promise.all([B,b,i,n,s]).then(async([e,i,n,s,u])=>{const g=Z.get("viewOnLoad");this._initializePdfHistory({fingerprint:t.fingerprints[0],viewOnLoad:g,initialDest:u?.dest});const b=this.initialBookmark,v=Z.get("defaultZoomValue");let w=v?`zoom=${v}`:null,y=null,C=Z.get("sidebarViewOnLoad"),P=Z.get("scrollModeOnLoad"),S=Z.get("spreadModeOnLoad");if(i?.page&&g!==Ks&&(w=`page=${i.page}&zoom=${v||i.zoom},${i.scrollLeft},${i.scrollTop}`,y=parseInt(i.rotation,10),C===a&&(C=0|i.sidebarView),P===p.UNKNOWN&&(P=0|i.scrollMode),S===m.UNKNOWN&&(S=0|i.spreadMode)),s&&C===a&&(C=function(e){switch(e){case"UseNone":return r;case"UseThumbs":return o;case"UseOutlines":return l;case"UseAttachments":return d;case"UseOC":return h}return r}(s)),n&&P===p.UNKNOWN&&S===m.UNKNOWN){S=O(n).spreadMode}this.setInitialView(w,{rotation:y,sidebarView:C,scrollMode:P,spreadMode:S}),this.eventBus.dispatch("documentinit",{source:this}),await Promise.race([f,new Promise(e=>{setTimeout(e,1e4)})]),(b||w)&&(c.hasEqualPageSizes||(this.initialBookmark=b,c.currentScaleValue=c.currentScaleValue,this.setInitialView(w)))}).catch(()=>{this.setInitialView()}).then(function(){c.update()})}),f.then(()=>{this._unblockDocumentLoadEvent(),this._initializeAutoPrint(t,s)},e=>{this._documentError("pdfjs-loading-error",{message:e.message})}),g.then(e=>{this.externalServices.reportTelemetry({type:"pageInfo",timestamp:e.timestamp}),this.pdfOutlineViewer&&t.getOutline().then(e=>{t===this.pdfDocument&&this.pdfOutlineViewer.render({outline:e,pdfDocument:t})}),this.pdfAttachmentViewer&&t.getAttachments().then(e=>{t===this.pdfDocument&&this.pdfAttachmentViewer.render({attachments:e})}),this.pdfLayerViewer&&c.optionalContentConfigPromise.then(e=>{t===this.pdfDocument&&this.pdfLayerViewer.render({optionalContentConfig:e,pdfDocument:t})})}),this._initializePageLabels(t),this._initializeMetadata(t)},async _scriptingDocProperties(e){return(this.documentInfo||(await new Promise(e=>{this.eventBus.on("metadataloaded",e,{once:!0,...Q})}),e===this.pdfDocument))&&(this._contentLength||(await new Promise(e=>{this.eventBus.on("documentloaded",e,{once:!0,...Q})}),e===this.pdfDocument))?{...this.documentInfo,baseURL:this.baseUrl,filesize:this._contentLength,filename:this._docFilename,metadata:this.metadata?.getRaw(),authors:this.metadata?.get("dc:creator"),numPages:this.pagesCount,URL:this.url}:null},async _initializeAutoPrint(e,t){const[i,n]=await Promise.all([t,this.pdfViewer.enableScripting?null:e.getJSActions()]);if(e!==this.pdfDocument)return;let s="Print"===i?.action;if(n){console.warn("Warning: JavaScript support is not enabled");for(const e in n){if(s)break;switch(e){case"WillClose":case"WillSave":case"DidSave":case"WillPrint":case"DidPrint":continue}s=n[e].some(e=>v.test(e))}}s&&this.triggerPrinting()},async _initializeMetadata(e){const{info:t,metadata:i,contentDispositionFilename:n,contentLength:s,hasStructTree:a}=await e.getMetadata();if(e!==this.pdfDocument)return;this.externalServices.reportTelemetry({type:"taggedPDF",data:a}),this.documentInfo=t,this.metadata=i,this._contentDispositionFilename??=n,this._contentLength??=s,console.log(`PDF ${e.fingerprints[0]} [${t.PDFFormatVersion} ${(i?.get("pdf:producer")||t.Producer||"-").trim()} / ${(i?.get("xmp:creatortool")||t.Creator||"-").trim()}] (PDF.js: ${nt||"?"} [${le||"?"}])`);const r=this._docTitle;r?this.setTitle(`${r} - ${this._contentDispositionFilename||this._title}`):this._contentDispositionFilename&&this.setTitle(this._contentDispositionFilename),!t.IsXFAPresent||t.IsAcroFormPresent||e.isPureXfa?!t.IsAcroFormPresent&&!t.IsXFAPresent||this.pdfViewer.renderForms||console.warn("Warning: Interactive form support is not enabled"):e.loadingParams.enableXfa?console.warn("Warning: XFA Foreground documents are not supported"):console.warn("Warning: XFA support is not enabled"),t.IsSignaturesPresent&&console.warn("Warning: Digital signatures validation is not supported"),this.eventBus.dispatch("metadataloaded",{source:this})},async _initializePageLabels(e){const t=await e.getPageLabels();if(e!==this.pdfDocument)return;if(!t||Z.get("disablePageLabels"))return;const i=t.length;let n=0,s=0;for(let e=0;e<i;e++){const i=t[e];if(i===(e+1).toString())n++;else{if(""!==i)break;s++}}if(n>=i||s>=i)return;const{pdfViewer:a,pdfThumbnailViewer:r,toolbar:o}=this;a.setPageLabels(t),r?.setPageLabels(t),o?.setPagesCount(i,!0),o?.setPageNumber(a.currentPageNumber,a.currentPageLabel)},_initializePdfHistory({fingerprint:e,viewOnLoad:t,initialDest:i=null}){this.pdfHistory&&(this.pdfHistory.initialize({fingerprint:e,resetHistory:t===Ks||!!this._mergedDocumentNeedsSaving,updateUrl:Z.get("historyUpdateUrl")}),this.pdfHistory.initialBookmark&&(this.initialBookmark=this.pdfHistory.initialBookmark,this.initialRotation=this.pdfHistory.initialRotation),i&&!this.initialBookmark&&t===Ys&&(this.initialBookmark=JSON.stringify(i),this.pdfHistory.push({explicitDest:i,pageNumber:null})))},_hasChanges(){return this.pdfDocument?.annotationStorage.size>0||this.pdfThumbnailViewer?.hasStructuralChanges()||!0===this._mergedDocumentNeedsSaving},_initializeAnnotationStorageCallbacks(e){if(e!==this.pdfDocument)return;const{annotationStorage:t}=e;t.onSetModified=()=>{this._annotationStorageModified=!0},t.onResetModified=()=>{delete this._annotationStorageModified},t.onAnnotationEditor=e=>{this._hasAnnotationEditors=!!e,this.setTitle()}},setInitialView(t,{rotation:i,sidebarView:n,scrollMode:s,spreadMode:a}={}){const r=e=>{_(e)&&(this.pdfViewer.pagesRotation=e)};this.isInitialViewSet=!0,this.viewsManager?.setInitialView(n),((e,t)=>{M(e)&&(this.pdfViewer.scrollMode=e),I(t)&&(this.pdfViewer.spreadMode=t)})(s,a),this.initialBookmark?(r(this.initialRotation),delete this.initialRotation,this.pdfLinkService.setHash(this.initialBookmark),this.initialBookmark=null):t&&(r(i),this.pdfLinkService.setHash(t)),this.toolbar?.setPageNumber(this.pdfViewer.currentPageNumber,this.pdfViewer.currentPageLabel),this.secondaryToolbar?.setPageNumber(this.pdfViewer.currentPageNumber),this.pdfViewer.currentScaleValue||(this.pdfViewer.currentScaleValue=e)},_cleanup(){this.pdfDocument&&(this.pdfViewer.cleanup(),this.pdfThumbnailViewer?.cleanup(),this.pdfDocument.cleanup(Z.get("fontExtraProperties")))},forceRendering(){this.pdfRenderingQueue.printing=!!this.printService,this.pdfRenderingQueue.isThumbnailViewEnabled=this.viewsManager?.visibleView===o,this.pdfRenderingQueue.renderHighestPriority()},beforePrint(){this._printAnnotationStoragePromise=this.pdfScriptingManager.dispatchWillPrint().catch(()=>{}).then(()=>this.pdfDocument?.annotationStorage.print),this.printService||(this.supportsPrinting&&this.pdfViewer.printingAllowed?this.pdfViewer.pageViewsReady?(this.printService=as.createPrintService({pdfDocument:this.pdfDocument,pagesOverview:this.pdfViewer.getPagesOverview(),printContainer:this.appConfig.printContainer,printResolution:Z.get("printResolution"),printAnnotationStoragePromise:this._printAnnotationStoragePromise}),this.forceRendering(),this.setTitle(),this.printService.layout(),this._hasAnnotationEditors&&this.externalServices.reportTelemetry({type:"editing",data:{type:"print",stats:this.pdfDocument?.annotationStorage.editorStats}})):this.l10n.get("pdfjs-printing-not-ready").then(e=>{window.alert(e)}):this._otherError("pdfjs-printing-not-supported"))},afterPrint(){this._printAnnotationStoragePromise&&(this._printAnnotationStoragePromise.then(()=>{this.pdfScriptingManager.dispatchDidPrint()}),this._printAnnotationStoragePromise=null),this.printService&&(this.printService.destroy(),this.printService=null,this.pdfDocument?.annotationStorage.resetModified()),this.forceRendering(),this.setTitle()},rotatePages(e){this.pdfViewer.pagesRotation+=e},requestPresentationMode(){this.pdfPresentationMode?.request()},async triggerPrinting(){this.supportsPrinting&&await this._printPermissionPromise&&window.print()},bindEvents(){if(this._eventBusAC)return;const e={signal:(this._eventBusAC=new AbortController).signal,...Q},{eventBus:t,externalServices:i,pdfDocumentProperties:n,pdfViewer:s,preferences:a}=this;t.on("resize",oa.bind(this),e),t.on("hashchange",la.bind(this),e),t.on("beforeprint",this.beforePrint.bind(this),e),t.on("afterprint",this.afterPrint.bind(this),e),t.on("pagerender",ea.bind(this),e),t.on("pagerendered",ta.bind(this),e),t.on("updateviewarea",aa.bind(this),e),t.on("pagechanging",fa.bind(this),e),t.on("scalechanging",pa.bind(this),e),t.on("rotationchanging",ma.bind(this),e),t.on("sidebarviewchanged",sa.bind(this),e),t.on("pagemode",ia.bind(this),e),t.on("namedaction",na.bind(this),e),t.on("presentationmodechanged",e=>s.presentationModeState=e.state,e),t.on("presentationmode",this.requestPresentationMode.bind(this),e),t.on("switchannotationeditormode",e=>s.annotationEditorMode=e,e),t.on("print",this.triggerPrinting.bind(this),e),t.on("download",this.downloadOrSave.bind(this),e),t.on("firstpage",()=>this.page=1,e),t.on("lastpage",()=>this.page=this.pagesCount,e),t.on("nextpage",()=>s.nextPage(),e),t.on("previouspage",()=>s.previousPage(),e),t.on("zoomin",this.zoomIn.bind(this),e),t.on("zoomout",this.zoomOut.bind(this),e),t.on("zoomreset",this.zoomReset.bind(this),e),t.on("pagenumberchanged",da.bind(this),e),t.on("scalechanged",e=>s.currentScaleValue=e.value,e),t.on("rotatecw",this.rotatePages.bind(this,90),e),t.on("rotateccw",this.rotatePages.bind(this,-90),e),t.on("optionalcontentconfig",e=>s.optionalContentConfigPromise=e.promise,e),t.on("switchscrollmode",e=>s.scrollMode=e.mode,e),t.on("scrollmodechanged",ra.bind(this,"scrollMode"),e),t.on("switchspreadmode",e=>s.spreadMode=e.mode,e),t.on("spreadmodechanged",ra.bind(this,"spreadMode"),e),t.on("imagealttextsettings",ha.bind(this),e),t.on("documentproperties",()=>n?.open(),e),t.on("findfromurlhash",ca.bind(this),e),t.on("updatefindmatchescount",ua.bind(this),e),t.on("updatefindcontrolstate",ga.bind(this),e),t.on("fileinputchange",Qs.bind(this),e),t.on("openfile",Js.bind(this),e),t.on("pagesedited",this.onPagesEdited.bind(this),e),t.on("saveextractedpages",this.onSavePages.bind(this),e),t.on("saveandload",this.onSaveAndLoad.bind(this),e)},bindWindowEvents(){if(this._windowAC)return;this._windowAC=new AbortController;const{eventBus:e,appConfig:{mainContainer:t},pdfViewer:i,_windowAC:{signal:n}}=this;if(this._touchManager=new Je({container:window,isPinchingDisabled:()=>i.isInPresentationMode,isPinchingStopped:()=>this.overlayManager?.active,onPinching:this.touchPinchCallback.bind(this),onPinchEnd:this.touchPinchEndCallback.bind(this),signal:n}),function e(t=null){t&&i.refresh(),window.matchMedia(`(resolution: ${Oe.pixelRatio}dppx)`).addEventListener("change",e,{once:!0,signal:n})}(),window.addEventListener("wheel",ba.bind(this),{passive:!1,signal:n}),window.addEventListener("click",Ca.bind(this),{signal:n}),window.addEventListener("keydown",Sa.bind(this),{signal:n}),window.addEventListener("keyup",Pa.bind(this),{signal:n}),window.addEventListener("resize",()=>e.dispatch("resize",{source:window}),{signal:n}),window.addEventListener("hashchange",()=>{e.dispatch("hashchange",{source:window,hash:document.location.hash.substring(1)})},{signal:n}),window.addEventListener("beforeprint",()=>e.dispatch("beforeprint",{source:window}),{signal:n}),window.addEventListener("afterprint",()=>e.dispatch("afterprint",{source:window}),{signal:n}),window.addEventListener("updatefromsandbox",t=>{e.dispatch("updatefromsandbox",{source:window,detail:t.detail})},{signal:n}),window.addEventListener("beforeunload",ya.bind(this),{signal:n}),!("onscrollend"in document.documentElement))return;let s,a;({scrollTop:this._lastScrollTop,scrollLeft:this._lastScrollLeft}=t);const r=()=>{({scrollTop:this._lastScrollTop,scrollLeft:this._lastScrollLeft}=t),clearTimeout(s),this._isScrolling&&(a.abort(),a=null,this._isScrolling=!1)};t.addEventListener("scroll",()=>{if(!this._isCtrlKeyDown&&(this._lastScrollTop!==t.scrollTop||this._lastScrollLeft!==t.scrollLeft)){if(!this._isScrolling){a=new AbortController;const e=AbortSignal.any([a.signal,n]);t.addEventListener("scrollend",r,{signal:e}),t.addEventListener("blur",r,{signal:e}),this._isScrolling=!0}clearTimeout(s),s=setTimeout(r,100)}},{passive:!0,signal:n})},unbindEvents(){this._eventBusAC?.abort(),this._eventBusAC=null},unbindWindowEvents(){this._windowAC?.abort(),this._windowAC=null,this._touchManager=null},async testingClose(){this.unbindEvents(),this.unbindWindowEvents(),this._globalAbortController?.abort(),this._globalAbortController=null,this.findBar?.close(),await Promise.all([this.l10n?.destroy(),this.close()])},onPagesEdited(e){this.pdfViewer.onPagesEdited(e)},async onSavePages({data:e}){if(!this.pdfDocument)return;const t=await this.pdfDocument.extractPages(e);t?this.downloadManager.download(t,this._downloadUrl,this._docFilename):console.error("Something wrong happened when saving the edited PDF.\nPlease file a bug.")},async onSaveAndLoad({data:e}){if(!this.pdfDocument)return;const t=await this.pdfDocument.extractPages(e);t?(this._mergedDocumentNeedsSaving=!0,this.open({data:t,filename:this._docFilename})):console.error("Something wrong happened when saving the edited PDF.\nPlease file a bug.")},_accumulateTicks(e,t){(this[t]>0&&e<0||this[t]<0&&e>0)&&(this[t]=0),this[t]+=e;const i=Math.trunc(this[t]);return this[t]-=i,i},_accumulateFactor(e,t,i){if(1===t)return 1;(this[i]>1&&t<1||this[i]<1&&t>1)&&(this[i]=1);const n=Math.floor(e*t*this[i]*100)/(100*e);return this[i]=t/n,n},_unblockDocumentLoadEvent(){document.blockUnblockOnload?.(!1),this._unblockDocumentLoadEvent=()=>{}},get scriptingReady(){return this.pdfScriptingManager.ready}};as.initGlobals(Zs);{const e=new Set(["null","http://mozilla.github.io","https://mozilla.github.io"]);var qs=function(t){if(!t)return;const i=URL.parse(window.location)?.origin||"null";if(e.has(i))return;const n=URL.parse(t,window.location)?.origin;if(n===i)return;const s=new Error("file origin does not match viewer's");throw Zs._documentError("pdfjs-loading-error",{message:s.message}),s},Qs=function(e){if(this.pdfViewer?.isInPresentationMode)return;const t=e.fileInput.files[0];this.open({url:URL.createObjectURL(t),originalUrl:encodeURIComponent(t.name)})},Js=function(e){this._openFileInput?.click()}}function ea({pageNumber:e}){e===this.page&&this.toolbar?.updateLoadingIndicatorState(!0)}function ta({pageNumber:e,isDetailView:t,error:i}){if(e===this.page&&this.toolbar?.updateLoadingIndicatorState(!1),!t&&this.viewsManager?.visibleView===o){const t=this.pdfViewer.getPageView(e-1),i=this.pdfThumbnailViewer?.getThumbnail(e-1);t&&i?.setImage(t)}i&&this._otherError("pdfjs-rendering-error",i)}function ia({mode:e}){let t;switch(e){case"thumbs":t=o;break;case"bookmarks":case"outline":t=l;break;case"attachments":t=d;break;case"layers":t=h;break;case"none":t=r;break;default:return void console.error('Invalid "pagemode" hash parameter: '+e)}this.viewsManager?.switchView(t,!0)}function na(e){switch(e.action){case"GoToPage":this.appConfig.toolbar?.pageNumber.select();break;case"Find":this.supportsIntegratedFind||this.findBar?.toggle();break;case"Print":this.triggerPrinting();break;case"SaveAs":this.downloadOrSave()}}function sa({view:e}){this.pdfRenderingQueue.isThumbnailViewEnabled=e===o,this.isInitialViewSet&&this.store?.set("sidebarView",e).catch(()=>{})}function aa({location:e}){this.isInitialViewSet&&this.store?.setMultiple({page:e.pageNumber,zoom:e.scale,scrollLeft:e.left,scrollTop:e.top,rotation:e.rotation}).catch(()=>{}),this.appConfig.secondaryToolbar&&(this.appConfig.secondaryToolbar.viewBookmarkButton.href=this.pdfLinkService.getAnchorUrl(e.pdfOpenParams))}function ra(e,t){this.isInitialViewSet&&!this.pdfViewer.isInPresentationMode&&this.store?.set(e,t.mode).catch(()=>{})}function oa(){const{pdfDocument:e,pdfViewer:t,pdfRenderingQueue:i}=this;if(i.printing&&window.matchMedia("print").matches)return;if(!e)return;const n=t.currentScaleValue;"auto"!==n&&"page-fit"!==n&&"page-width"!==n||(t.currentScaleValue=n),t.update()}function la(e){const t=e.hash;t&&(this.isInitialViewSet?this.pdfHistory?.popStateInProgress||this.pdfLinkService.setHash(t):this.initialBookmark=t)}function da(e){const{pdfViewer:t}=this;""!==e.value&&this.pdfLinkService.goToPage(e.value),e.value!==t.currentPageNumber.toString()&&e.value!==t.currentPageLabel&&this.toolbar?.setPageNumber(t.currentPageNumber,t.currentPageLabel)}function ha(){this.imageAltTextSettings?.open({enableGuessAltText:Z.get("enableGuessAltText"),enableNewAltTextWhenAddingImage:Z.get("enableNewAltTextWhenAddingImage")})}function ca(e){this.eventBus.dispatch("find",{source:e.source,type:"",query:e.query,caseSensitive:!1,entireWord:!1,highlightAll:!0,findPrevious:!1,matchDiacritics:!0})}function ua({matchesCount:e}){this.supportsIntegratedFind?this.externalServices.updateFindMatchesCount(e):this.findBar?.updateResultsCount(e)}function ga({state:e,previous:t,entireWord:i,matchesCount:n,rawQuery:s}){this.supportsIntegratedFind?this.externalServices.updateFindControlState({result:e,findPrevious:t,entireWord:i,matchesCount:n,rawQuery:s}):this.findBar?.updateUIState(e,t,n)}function pa(e){this.toolbar?.setPageScale(e.presetValue,e.scale),this.pdfViewer.update()}function ma(e){this.pdfThumbnailViewer&&(this.pdfThumbnailViewer.pagesRotation=e.pagesRotation),this.forceRendering(),this.pdfViewer.currentPageNumber=e.pageNumber}function fa({pageNumber:e,pageLabel:t}){this.toolbar?.setPageNumber(e,t),this.secondaryToolbar?.setPageNumber(e),this.viewsManager?.visibleView===o&&this.pdfThumbnailViewer?.scrollThumbnailIntoView(e);const i=this.pdfViewer.getPageView(e-1);this.toolbar?.updateLoadingIndicatorState(i?.renderingState===rs.RUNNING)}function ba(e){const{pdfViewer:t,supportsMouseWheelZoomCtrlKey:i,supportsMouseWheelZoomMetaKey:n,supportsPinchToZoom:s}=this;if(t.isInPresentationMode)return;const a=e.deltaMode;let r=Math.exp(-e.deltaY/100);const o=e.ctrlKey&&!this._isCtrlKeyDown&&a===WheelEvent.DOM_DELTA_PIXEL&&0===e.deltaX&&(Math.abs(r-1)<.05||!1)&&0===e.deltaZ,l=[e.clientX,e.clientY];if(o||e.ctrlKey&&i||e.metaKey&&n){if(e.preventDefault(),this._isScrolling||"hidden"===document.visibilityState||this.overlayManager.active)return;if(o&&s)r=this._accumulateFactor(t.currentScale,r,"_wheelUnusedFactor"),this.updateZoom(null,r,l);else{const t=L(e);let i=0;if(a===WheelEvent.DOM_DELTA_LINE||a===WheelEvent.DOM_DELTA_PAGE)i=Math.abs(t)>=1?Math.sign(t):this._accumulateTicks(t,"_wheelUnusedTicks");else{const e=30;i=this._accumulateTicks(t/e,"_wheelUnusedTicks")}this.updateZoom(i,null,l)}}}function va({target:e}){if(!this.secondaryToolbar?.isOpen)return;const{toolbar:t,secondaryToolbar:i}=this.appConfig;(this.pdfViewer.containsElement(e)||t?.container.contains(e)&&!i?.toolbar.contains(e)&&!i?.toggleButton.contains(e))&&this.secondaryToolbar.close()}function wa(e){this.editorUndoBar?.isOpen&&this.appConfig.secondaryToolbar?.toolbar.contains(e.target)&&this.editorUndoBar.hide()}function ya(e){return!this._hasChanges()||(e.preventDefault(),e.returnValue="",!1)}function Ca(e){va.call(this,e),wa.call(this,e)}function Pa(e){"Control"===e.key&&(this._isCtrlKeyDown=!1)}function Sa(e){if(this._isCtrlKeyDown="Control"===e.key,this.editorUndoBar?.isOpen&&9!==e.keyCode&&16!==e.keyCode&&(13!==e.keyCode&&32!==e.keyCode||N()!==this.appConfig.editorUndoBar.undoButton)&&this.editorUndoBar.hide(),this.overlayManager.active)return;const{eventBus:t,pdfViewer:i}=this,n=i.isInPresentationMode;let s=!1,a=!1;const r=(e.ctrlKey?1:0)|(e.altKey?2:0)|(e.shiftKey?4:0)|(e.metaKey?8:0);if(1===r||8===r||5===r||12===r)switch(e.keyCode){case 70:this.supportsIntegratedFind||e.shiftKey||(this.findBar?.open(),s=!0);break;case 71:if(!this.supportsIntegratedFind){const{state:e}=this.findController;if(e){const i={source:window,type:"again",findPrevious:5===r||12===r};t.dispatch("find",{...e,...i})}s=!0}break;case 61:case 107:case 187:case 171:this.zoomIn(),s=!0;break;case 173:case 109:case 189:this.zoomOut(),s=!0;break;case 48:case 96:n||(setTimeout(()=>{this.zoomReset()}),s=!1);break;case 38:(n||this.page>1)&&(this.page=1,s=!0,a=!0);break;case 40:(n||this.page<this.pagesCount)&&(this.page=this.pagesCount,s=!0,a=!0)}if(1===r||8===r)switch(e.keyCode){case 83:t.dispatch("download",{source:window}),s=!0;break;case 79:t.dispatch("openfile",{source:window}),s=!0}if(3===r||10===r)switch(e.keyCode){case 80:this.requestPresentationMode(),s=!0,this.externalServices.reportTelemetry({type:"buttons",data:{id:"presentationModeKeyboard"}});break;case 71:this.appConfig.toolbar&&(this.appConfig.toolbar.pageNumber.select(),s=!0)}if(s)return a&&!n&&i.focus(),void e.preventDefault();const o=N(),l=o?.tagName.toUpperCase();if(!("INPUT"===l||"TEXTAREA"===l||"SELECT"===l||"BUTTON"===l&&32===e.keyCode||o?.isContentEditable)||27===e.keyCode){if(0===r){let t=0,r=!1;switch(e.keyCode){case 38:if(this.supportsCaretBrowsingMode){this.moveCaret(!0,!1),s=!0;break}case 33:i.isVerticalScrollbarEnabled&&(r=!0),t=-1;break;case 8:n||(r=!0),t=-1;break;case 37:if(this.supportsCaretBrowsingMode)return;i.isHorizontalScrollbarEnabled&&(r=!0);case 75:case 80:t=-1;break;case 27:this.secondaryToolbar?.isOpen&&(this.secondaryToolbar.close(),s=!0),!this.supportsIntegratedFind&&this.findBar?.opened&&(this.findBar.close(),s=!0);break;case 40:if(this.supportsCaretBrowsingMode){this.moveCaret(!1,!1),s=!0;break}case 34:i.isVerticalScrollbarEnabled&&(r=!0),t=1;break;case 32:n||(r=!0),t=1;break;case 39:if(this.supportsCaretBrowsingMode)return;i.isHorizontalScrollbarEnabled&&(r=!0);case 74:case 78:t=1;break;case 36:(n||this.page>1)&&(this.page=1,s=!0,a=!0);break;case 35:(n||this.page<this.pagesCount)&&(this.page=this.pagesCount,s=!0,a=!0);break;case 83:this.pdfCursorTools?.switchTool(f);break;case 72:this.pdfCursorTools?.switchTool(b);break;case 82:this.rotatePages(90);break;case 115:this.viewsManager?.toggle()}0===t||r&&"page-fit"!==i.currentScaleValue||(t>0?i.nextPage():i.previousPage(),s=!0)}if(4===r)switch(e.keyCode){case 32:if(!n&&"page-fit"!==i.currentScaleValue)break;i.previousPage(),s=!0;break;case 38:this.moveCaret(!0,!0),s=!0;break;case 40:this.moveCaret(!1,!0),s=!0;break;case 82:this.rotatePages(-90)}s||n||(e.keyCode>=33&&e.keyCode<=40||32===e.keyCode&&"BUTTON"!==l)&&(a=!0),a&&!i.containsElement(o)&&i.focus(),s&&e.preventDefault()}}const Ea={LinkTarget:at,RenderingStates:rs,ScrollMode:p,SpreadMode:m};function xa(){const e={appContainer:document.body,principalContainer:document.getElementById("mainContainer"),mainContainer:document.getElementById("viewerContainer"),viewerContainer:document.getElementById("viewer"),viewerAlert:document.getElementById("viewer-alert"),toolbar:{container:document.getElementById("toolbarContainer"),numPages:document.getElementById("numPages"),pageNumber:document.getElementById("pageNumber"),scaleSelect:document.getElementById("scaleSelect"),customScaleOption:document.getElementById("customScaleOption"),previous:document.getElementById("previous"),next:document.getElementById("next"),zoomIn:document.getElementById("zoomInButton"),zoomOut:document.getElementById("zoomOutButton"),print:document.getElementById("printButton"),editorCommentButton:document.getElementById("editorCommentButton"),editorCommentParamsToolbar:document.getElementById("editorCommentParamsToolbar"),editorFreeTextButton:document.getElementById("editorFreeTextButton"),editorFreeTextParamsToolbar:document.getElementById("editorFreeTextParamsToolbar"),editorHighlightButton:document.getElementById("editorHighlightButton"),editorHighlightParamsToolbar:document.getElementById("editorHighlightParamsToolbar"),editorHighlightColorPicker:document.getElementById("editorHighlightColorPicker"),editorInkButton:document.getElementById("editorInkButton"),editorInkParamsToolbar:document.getElementById("editorInkParamsToolbar"),editorStampButton:document.getElementById("editorStampButton"),editorStampParamsToolbar:document.getElementById("editorStampParamsToolbar"),editorSignatureButton:document.getElementById("editorSignatureButton"),editorSignatureParamsToolbar:document.getElementById("editorSignatureParamsToolbar"),download:document.getElementById("downloadButton")},secondaryToolbar:{toolbar:document.getElementById("secondaryToolbar"),toggleButton:document.getElementById("secondaryToolbarToggleButton"),presentationModeButton:document.getElementById("presentationMode"),openFileButton:document.getElementById("secondaryOpenFile"),printButton:document.getElementById("secondaryPrint"),downloadButton:document.getElementById("secondaryDownload"),viewBookmarkButton:document.getElementById("viewBookmark"),firstPageButton:document.getElementById("firstPage"),lastPageButton:document.getElementById("lastPage"),pageRotateCwButton:document.getElementById("pageRotateCw"),pageRotateCcwButton:document.getElementById("pageRotateCcw"),cursorSelectToolButton:document.getElementById("cursorSelectTool"),cursorHandToolButton:document.getElementById("cursorHandTool"),scrollPageButton:document.getElementById("scrollPage"),scrollVerticalButton:document.getElementById("scrollVertical"),scrollHorizontalButton:document.getElementById("scrollHorizontal"),scrollWrappedButton:document.getElementById("scrollWrapped"),spreadNoneButton:document.getElementById("spreadNone"),spreadOddButton:document.getElementById("spreadOdd"),spreadEvenButton:document.getElementById("spreadEven"),imageAltTextSettingsButton:document.getElementById("imageAltTextSettings"),imageAltTextSettingsSeparator:document.getElementById("imageAltTextSettingsSeparator"),documentPropertiesButton:document.getElementById("documentProperties")},viewsManager:{outerContainer:document.getElementById("outerContainer"),toggleButton:document.getElementById("viewsManagerToggleButton"),sidebarContainer:document.getElementById("viewsManager"),resizer:document.getElementById("viewsManagerResizer"),thumbnailButton:document.getElementById("thumbnailsViewMenu"),outlineButton:document.getElementById("outlinesViewMenu"),attachmentsButton:document.getElementById("attachmentsViewMenu"),layersButton:document.getElementById("layersViewMenu"),viewsManagerSelectorButton:document.getElementById("viewsManagerSelectorButton"),viewsManagerSelectorOptions:document.getElementById("viewsManagerSelectorOptions"),thumbnailsView:document.getElementById("thumbnailsView"),outlinesView:document.getElementById("outlinesView"),attachmentsView:document.getElementById("attachmentsView"),layersView:document.getElementById("layersView"),viewsManagerAddFile:{button:document.getElementById("viewsManagerAddFileButton"),picker:document.getElementById("viewsManagerAddFilePicker")},viewsManagerCurrentOutlineButton:document.getElementById("viewsManagerCurrentOutlineButton"),viewsManagerHeaderLabel:document.getElementById("viewsManagerHeaderLabel"),viewsManagerStatus:document.getElementById("viewsManagerStatus"),viewsManagerStatusBar:{viewsManagerStatusAction:document.getElementById("viewsManagerStatusAction"),viewsManagerStatusActionDeselectButton:document.getElementById("viewsManagerStatusActionDeselectButton"),viewsManagerStatusActionLabel:document.getElementById("viewsManagerStatusActionLabel")},viewsManagerUndoBar:{viewsManagerStatusUndo:document.getElementById("viewsManagerStatusUndo"),viewsManagerStatusUndoLabel:document.getElementById("viewsManagerStatusUndoLabel"),viewsManagerStatusUndoButton:document.getElementById("viewsManagerStatusUndoButton"),viewsManagerStatusUndoCloseButton:document.getElementById("viewsManagerStatusUndoCloseButton")},viewsManagerWaitingBar:{container:document.getElementById("viewsManagerStatusWaiting"),closeButton:document.getElementById("viewsManagerStatusWaitingCloseButton"),label:document.getElementById("viewsManagerStatusWaitingLabel")},manageMenu:{button:document.getElementById("viewsManagerStatusActionButton"),menu:document.getElementById("viewsManagerStatusActionOptions"),copy:document.getElementById("viewsManagerStatusActionCopy"),cut:document.getElementById("viewsManagerStatusActionCut"),delete:document.getElementById("viewsManagerStatusActionDelete"),exportSelected:document.getElementById("viewsManagerStatusActionExport")}},findBar:{bar:document.getElementById("findbar"),toggleButton:document.getElementById("viewFindButton"),findField:document.getElementById("findInput"),highlightAllCheckbox:document.getElementById("findHighlightAll"),caseSensitiveCheckbox:document.getElementById("findMatchCase"),matchDiacriticsCheckbox:document.getElementById("findMatchDiacritics"),entireWordCheckbox:document.getElementById("findEntireWord"),findMsg:document.getElementById("findMsg"),findResultsCount:document.getElementById("findResultsCount"),findPreviousButton:document.getElementById("findPreviousButton"),findNextButton:document.getElementById("findNextButton")},passwordOverlay:{dialog:document.getElementById("passwordDialog"),label:document.getElementById("passwordText"),input:document.getElementById("password"),submitButton:document.getElementById("passwordSubmit"),cancelButton:document.getElementById("passwordCancel")},documentProperties:{dialog:document.getElementById("documentPropertiesDialog"),closeButton:document.getElementById("documentPropertiesClose"),fields:{fileName:document.getElementById("fileNameField"),fileSize:document.getElementById("fileSizeField"),title:document.getElementById("titleField"),author:document.getElementById("authorField"),subject:document.getElementById("subjectField"),keywords:document.getElementById("keywordsField"),creationDate:document.getElementById("creationDateField"),modificationDate:document.getElementById("modificationDateField"),creator:document.getElementById("creatorField"),producer:document.getElementById("producerField"),version:document.getElementById("versionField"),pageCount:document.getElementById("pageCountField"),pageSize:document.getElementById("pageSizeField"),linearized:document.getElementById("linearizedField")}},altTextDialog:{dialog:document.getElementById("altTextDialog"),optionDescription:document.getElementById("descriptionButton"),optionDecorative:document.getElementById("decorativeButton"),textarea:document.getElementById("descriptionTextarea"),cancelButton:document.getElementById("altTextCancel"),saveButton:document.getElementById("altTextSave")},newAltTextDialog:{dialog:document.getElementById("newAltTextDialog"),title:document.getElementById("newAltTextTitle"),descriptionContainer:document.getElementById("newAltTextDescriptionContainer"),textarea:document.getElementById("newAltTextDescriptionTextarea"),disclaimer:document.getElementById("newAltTextDisclaimer"),learnMore:document.getElementById("newAltTextLearnMore"),imagePreview:document.getElementById("newAltTextImagePreview"),createAutomatically:document.getElementById("newAltTextCreateAutomatically"),createAutomaticallyButton:document.getElementById("newAltTextCreateAutomaticallyButton"),downloadModel:document.getElementById("newAltTextDownloadModel"),downloadModelDescription:document.getElementById("newAltTextDownloadModelDescription"),error:document.getElementById("newAltTextError"),errorCloseButton:document.getElementById("newAltTextCloseButton"),cancelButton:document.getElementById("newAltTextCancel"),notNowButton:document.getElementById("newAltTextNotNow"),saveButton:document.getElementById("newAltTextSave")},altTextSettingsDialog:{dialog:document.getElementById("altTextSettingsDialog"),createModelButton:document.getElementById("createModelButton"),learnMore:document.getElementById("altTextSettingsLearnMore"),showAltTextDialogButton:document.getElementById("showAltTextDialogButton"),altTextSettingsCloseButton:document.getElementById("altTextSettingsCloseButton"),closeButton:document.getElementById("altTextSettingsCloseButton")},addSignatureDialog:{dialog:document.getElementById("addSignatureDialog"),panels:document.getElementById("addSignatureActionContainer"),typeButton:document.getElementById("addSignatureTypeButton"),typeInput:document.getElementById("addSignatureTypeInput"),drawButton:document.getElementById("addSignatureDrawButton"),drawSVG:document.getElementById("addSignatureDraw"),drawPlaceholder:document.getElementById("addSignatureDrawPlaceholder"),drawThickness:document.getElementById("addSignatureDrawThickness"),imageButton:document.getElementById("addSignatureImageButton"),imageSVG:document.getElementById("addSignatureImage"),imagePlaceholder:document.getElementById("addSignatureImagePlaceholder"),imagePicker:document.getElementById("addSignatureFilePicker"),imagePickerLink:document.getElementById("addSignatureImageBrowse"),description:document.getElementById("addSignatureDescription"),clearButton:document.getElementById("clearSignatureButton"),saveContainer:document.getElementById("addSignatureSaveContainer"),saveCheckbox:document.getElementById("addSignatureSaveCheckbox"),errorBar:document.getElementById("addSignatureError"),errorTitle:document.getElementById("addSignatureErrorTitle"),errorDescription:document.getElementById("addSignatureErrorDescription"),errorCloseButton:document.getElementById("addSignatureErrorCloseButton"),cancelButton:document.getElementById("addSignatureCancelButton"),addButton:document.getElementById("addSignatureAddButton")},editSignatureDialog:{dialog:document.getElementById("editSignatureDescriptionDialog"),description:document.getElementById("editSignatureDescription"),editSignatureView:document.getElementById("editSignatureView"),cancelButton:document.getElementById("editSignatureCancelButton"),updateButton:document.getElementById("editSignatureUpdateButton")},annotationEditorParams:{editorCommentsSidebar:document.getElementById("editorCommentsSidebar"),editorCommentsSidebarCount:document.getElementById("editorCommentsSidebarCount"),editorCommentsSidebarTitle:document.getElementById("editorCommentsSidebarTitle"),editorCommentsSidebarCloseButton:document.getElementById("editorCommentsSidebarCloseButton"),editorCommentsSidebarList:document.getElementById("editorCommentsSidebarList"),editorCommentsSidebarResizer:document.getElementById("editorCommentsSidebarResizer"),editorFreeTextFontSize:document.getElementById("editorFreeTextFontSize"),editorFreeTextColor:document.getElementById("editorFreeTextColor"),editorInkColor:document.getElementById("editorInkColor"),editorInkThickness:document.getElementById("editorInkThickness"),editorInkOpacity:document.getElementById("editorInkOpacity"),editorStampAddImage:document.getElementById("editorStampAddImage"),editorSignatureAddSignature:document.getElementById("editorSignatureAddSignature"),editorFreeHighlightThickness:document.getElementById("editorFreeHighlightThickness"),editorHighlightShowAll:document.getElementById("editorHighlightShowAll")},printContainer:document.getElementById("printContainer"),editorUndoBar:{container:document.getElementById("editorUndoBar"),message:document.getElementById("editorUndoBarMessage"),undoButton:document.getElementById("editorUndoBarUndoButton"),closeButton:document.getElementById("editorUndoBarCloseButton")},editCommentDialog:{dialog:document.getElementById("commentManagerDialog"),toolbar:document.getElementById("commentManagerToolbar"),title:document.getElementById("commentManagerTitle"),textInput:document.getElementById("commentManagerTextInput"),cancelButton:document.getElementById("commentManagerCancelButton"),saveButton:document.getElementById("commentManagerSaveButton")}},t=new CustomEvent("webviewerloaded",{bubbles:!0,cancelable:!0,detail:{source:window}});try{parent.document.dispatchEvent(t)}catch(e){console.error("webviewerloaded:",e),document.dispatchEvent(t)}Zs.run(e)}window.PDFViewerApplication=Zs,window.PDFViewerApplicationConstants=Ea,window.PDFViewerApplicationOptions=Z,document.blockUnblockOnload?.(!0),"interactive"===document.readyState||"complete"===document.readyState?xa():document.addEventListener("DOMContentLoaded",xa,!0);export{Zs as PDFViewerApplication,Ea as PDFViewerApplicationConstants,Z as PDFViewerApplicationOptions};