/**
 * @licstart The following is the entire license notice for the
 * JavaScript code in this page
 *
 * Copyright 2023 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
 */var t={d:(e,s)=>{for(var i in s)t.o(s,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:s[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},e=globalThis.pdfjsLib={};t.d(e,{AbortException:()=>pt,AnnotationEditorLayer:()=>gn,AnnotationEditorParamsType:()=>m,AnnotationEditorType:()=>g,AnnotationEditorUIManager:()=>me,AnnotationLayer:()=>en,AnnotationMode:()=>p,CMapCompressionType:()=>X,ColorPicker:()=>dn,DOMSVGFactory:()=>$t,DrawLayer:()=>mn,FeatureTest:()=>bt,GlobalWorkerOptions:()=>rs,ImageKind:()=>x,InvalidPDFException:()=>lt,MissingPDFException:()=>dt,OPS:()=>K,Outliner:()=>an,PDFDataRangeTransport:()=>hi,PDFDateString:()=>ee,PDFWorker:()=>pi,PasswordResponses:()=>Y,PermissionFlag:()=>f,PixelsPerInch:()=>Ht,RenderingCancelledException:()=>Gt,TextLayer:()=>Ys,UnexpectedResponseException:()=>ct,Util:()=>At,VerbosityLevel:()=>q,XfaLayer:()=>Ei,build:()=>yi,createValidAbsoluteUrl:()=>nt,fetchData:()=>zt,getDocument:()=>ai,getFilenameFromUrl:()=>Xt,getPdfFilenameFromUrl:()=>Kt,getXfaPageViewport:()=>se,isDataScheme:()=>Wt,isPdfFile:()=>qt,noContextMenu:()=>Jt,normalizeUnicode:()=>_t,renderTextLayer:()=>Qs,setLayerDimensions:()=>re,shadow:()=>at,updateTextLayer:()=>Js,version:()=>Ai});const s=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),i=[1,0,0,1,0,0],n=[.001,0,0,.001,0,0],a=1.35,r=1,o=2,h=4,l=16,d=32,c=64,u=256,p={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},g={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},m={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35},f={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},b=0,v=1,A=2,y=3,w=3,_=4,x={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},E=1,C=2,S=3,T=4,M=5,k=6,P=7,I=8,R=9,D=10,L=11,F=12,O=13,N=14,B=15,H=16,z=17,j=20,U=1,$=2,V=3,G=4,W=5,q={ERRORS:0,WARNINGS:1,INFOS:5},X={NONE:0,BINARY:1},K={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91},Y={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let Q=q.WARNINGS;function J(t){Number.isInteger(t)&&(Q=t)}function Z(){return Q}function tt(t){Q>=q.INFOS&&console.log(`Info: ${t}`)}function et(t){Q>=q.WARNINGS&&console.log(`Warning: ${t}`)}function st(t){throw new Error(t)}function it(t,e){t||st(e)}function nt(t,e=null,s=null){if(!t)return null;try{if(s&&"string"==typeof t){if(s.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(s.tryConvertEncoding)try{t=decodeURIComponent(escape(t))}catch{}}const i=e?new URL(t,e):new URL(t);if(function(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(i))return i}catch{}return null}function at(t,e,s,i=!1){return Object.defineProperty(t,e,{value:s,enumerable:!i,configurable:!0,writable:!1}),s}const rt=function(){function t(e,s){this.constructor===t&&st("Cannot initialize BaseException."),this.message=e,this.name=s}return t.prototype=new Error,t.constructor=t,t}();class ot extends rt{constructor(t,e){super(t,"PasswordException"),this.code=e}}class ht extends rt{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class lt extends rt{constructor(t){super(t,"InvalidPDFException")}}class dt extends rt{constructor(t){super(t,"MissingPDFException")}}class ct extends rt{constructor(t,e){super(t,"UnexpectedResponseException"),this.status=e}}class ut extends rt{constructor(t){super(t,"FormatError")}}class pt extends rt{constructor(t){super(t,"AbortException")}}function gt(t){"object"==typeof t&&void 0!==t?.length||st("Invalid argument for bytesToString");const e=t.length,s=8192;if(e<s)return String.fromCharCode.apply(null,t);const i=[];for(let n=0;n<e;n+=s){const a=Math.min(n+s,e),r=t.subarray(n,a);i.push(String.fromCharCode.apply(null,r))}return i.join("")}function mt(t){"string"!=typeof t&&st("Invalid argument for stringToBytes");const e=t.length,s=new Uint8Array(e);for(let i=0;i<e;++i)s[i]=255&t.charCodeAt(i);return s}function ft(t){const e=Object.create(null);for(const[s,i]of t)e[s]=i;return e}class bt{static get isLittleEndian(){return at(this,"isLittleEndian",function(){const t=new Uint8Array(4);return t[0]=1,1===new Uint32Array(t.buffer,0,1)[0]}())}static get isEvalSupported(){return at(this,"isEvalSupported",function(){try{return new Function(""),!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return at(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get platform(){return"undefined"!=typeof navigator&&"string"==typeof navigator?.platform?at(this,"platform",{isMac:navigator.platform.includes("Mac")}):at(this,"platform",{isMac:!1})}static get isCSSRoundSupported(){return at(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const vt=Array.from(Array(256).keys(),t=>t.toString(16).padStart(2,"0"));class At{static makeHexColor(t,e,s){return`#${vt[t]}${vt[e]}${vt[s]}`}static scaleMinMax(t,e){let s;t[0]?(t[0]<0&&(s=e[0],e[0]=e[2],e[2]=s),e[0]*=t[0],e[2]*=t[0],t[3]<0&&(s=e[1],e[1]=e[3],e[3]=s),e[1]*=t[3],e[3]*=t[3]):(s=e[0],e[0]=e[1],e[1]=s,s=e[2],e[2]=e[3],e[3]=s,t[1]<0&&(s=e[1],e[1]=e[3],e[3]=s),e[1]*=t[1],e[3]*=t[1],t[2]<0&&(s=e[0],e[0]=e[2],e[2]=s),e[0]*=t[2],e[2]*=t[2]),e[0]+=t[4],e[1]+=t[5],e[2]+=t[4],e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){return[t[0]*e[0]+t[1]*e[2]+e[4],t[0]*e[1]+t[1]*e[3]+e[5]]}static applyInverseTransform(t,e){const s=e[0]*e[3]-e[1]*e[2];return[(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/s,(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/s]}static getAxialAlignedBoundingBox(t,e){const s=this.applyTransform(t,e),i=this.applyTransform(t.slice(2,4),e),n=this.applyTransform([t[0],t[3]],e),a=this.applyTransform([t[2],t[1]],e);return[Math.min(s[0],i[0],n[0],a[0]),Math.min(s[1],i[1],n[1],a[1]),Math.max(s[0],i[0],n[0],a[0]),Math.max(s[1],i[1],n[1],a[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]],s=t[0]*e[0]+t[1]*e[2],i=t[0]*e[1]+t[1]*e[3],n=t[2]*e[0]+t[3]*e[2],a=t[2]*e[1]+t[3]*e[3],r=(s+a)/2,o=Math.sqrt((s+a)**2-4*(s*a-n*i))/2,h=r+o||1,l=r-o||1;return[Math.sqrt(h),Math.sqrt(l)]}static normalizeRect(t){const e=t.slice(0);return t[0]>t[2]&&(e[0]=t[2],e[2]=t[0]),t[1]>t[3]&&(e[1]=t[3],e[3]=t[1]),e}static intersect(t,e){const s=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),i=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(s>i)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),a=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>a?null:[s,n,i,a]}static#t(t,e,s,i,n,a,r,o,h,l){if(h<=0||h>=1)return;const d=1-h,c=h*h,u=c*h,p=d*(d*(d*t+3*h*e)+3*c*s)+u*i,g=d*(d*(d*n+3*h*a)+3*c*r)+u*o;l[0]=Math.min(l[0],p),l[1]=Math.min(l[1],g),l[2]=Math.max(l[2],p),l[3]=Math.max(l[3],g)}static#e(t,e,s,i,n,a,r,o,h,l,d,c){if(Math.abs(h)<1e-12)return void(Math.abs(l)>=1e-12&&this.#t(t,e,s,i,n,a,r,o,-d/l,c));const u=l**2-4*d*h;if(u<0)return;const p=Math.sqrt(u),g=2*h;this.#t(t,e,s,i,n,a,r,o,(-l+p)/g,c),this.#t(t,e,s,i,n,a,r,o,(-l-p)/g,c)}static bezierBoundingBox(t,e,s,i,n,a,r,o,h){return h?(h[0]=Math.min(h[0],t,r),h[1]=Math.min(h[1],e,o),h[2]=Math.max(h[2],t,r),h[3]=Math.max(h[3],e,o)):h=[Math.min(t,r),Math.min(e,o),Math.max(t,r),Math.max(e,o)],this.#e(t,s,n,r,e,i,a,o,3*(3*(s-n)-t+r),6*(t-2*s+n),3*(s-t),h),this.#e(t,s,n,r,e,i,a,o,3*(3*(i-a)-e+o),6*(e-2*i+a),3*(i-e),h),h}}let yt=null,wt=null;function _t(t){return yt||(yt=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,wt=new Map([["ﬅ","ſt"]])),t.replaceAll(yt,(t,e,s)=>e?e.normalize("NFKC"):wt.get(s))}const xt="pdfjs_internal_id_",Et=0,Ct=1,St=2,Tt=3,Mt=4,kt=5,Pt=6,It=7,Rt=8;class Dt{constructor(){this.constructor===Dt&&st("Cannot initialize BaseFilterFactory.")}addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,s,i,n){return"none"}destroy(t=!1){}}class Lt{#s=!1;constructor({enableHWA:t=!1}={}){this.constructor===Lt&&st("Cannot initialize BaseCanvasFactory."),this.#s=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const s=this._createCanvas(t,e);return{canvas:s,context:s.getContext("2d",{willReadFrequently:!this.#s})}}reset(t,e,s){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||s<=0)throw new Error("Invalid canvas size");t.canvas.width=e,t.canvas.height=s}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0,t.canvas.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){st("Abstract method `_createCanvas` called.")}}class Ft{constructor({baseUrl:t=null,isCompressed:e=!0}){this.constructor===Ft&&st("Cannot initialize BaseCMapReaderFactory."),this.baseUrl=t,this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error('The CMap "baseUrl" parameter must be specified, ensure that the "cMapUrl" and "cMapPacked" API parameters are provided.');if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":""),s=this.isCompressed?X.BINARY:X.NONE;return this._fetchData(e,s).catch(t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)})}_fetchData(t,e){st("Abstract method `_fetchData` called.")}}class Ot{constructor({baseUrl:t=null}){this.constructor===Ot&&st("Cannot initialize BaseStandardFontDataFactory."),this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error('The standard font "baseUrl" parameter must be specified, ensure that the "standardFontDataUrl" API parameter is provided.');if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetchData(e).catch(t=>{throw new Error(`Unable to load font data at: ${e}`)})}_fetchData(t){st("Abstract method `_fetchData` called.")}}class Nt{constructor(){this.constructor===Nt&&st("Cannot initialize BaseSVGFactory.")}create(t,e,s=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const i=this._createSVG("svg:svg");return i.setAttribute("version","1.1"),s||(i.setAttribute("width",`${t}px`),i.setAttribute("height",`${e}px`)),i.setAttribute("preserveAspectRatio","none"),i.setAttribute("viewBox",`0 0 ${t} ${e}`),i}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){st("Abstract method `_createSVG` called.")}}const Bt="http://www.w3.org/2000/svg";class Ht{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function zt(t,e="text"){if(Qt(t,document.baseURI)){const s=await fetch(t);if(!s.ok)throw new Error(s.statusText);switch(e){case"arraybuffer":return s.arrayBuffer();case"blob":return s.blob();case"json":return s.json()}return s.text()}return new Promise((s,i)=>{const n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType=e,n.onreadystatechange=()=>{if(n.readyState===XMLHttpRequest.DONE)if(200!==n.status&&0!==n.status)i(new Error(n.statusText));else{switch(e){case"arraybuffer":case"blob":case"json":return void s(n.response)}s(n.responseText)}},n.send(null)})}class jt extends Ft{_fetchData(t,e){return zt(t,this.isCompressed?"arraybuffer":"text").then(t=>({cMapData:t instanceof ArrayBuffer?new Uint8Array(t):mt(t),compressionType:e}))}}class Ut extends Ot{_fetchData(t){return zt(t,"arraybuffer").then(t=>new Uint8Array(t))}}class $t extends Nt{_createSVG(t){return document.createElementNS(Bt,t)}}class Vt{constructor({viewBox:t,scale:e,rotation:s,offsetX:i=0,offsetY:n=0,dontFlip:a=!1}){this.viewBox=t,this.scale=e,this.rotation=s,this.offsetX=i,this.offsetY=n;const r=(t[2]+t[0])/2,o=(t[3]+t[1])/2;let h,l,d,c,u,p,g,m;switch((s%=360)<0&&(s+=360),s){case 180:h=-1,l=0,d=0,c=1;break;case 90:h=0,l=1,d=1,c=0;break;case 270:h=0,l=-1,d=-1,c=0;break;case 0:h=1,l=0,d=0,c=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}a&&(d=-d,c=-c),0===h?(u=Math.abs(o-t[1])*e+i,p=Math.abs(r-t[0])*e+n,g=(t[3]-t[1])*e,m=(t[2]-t[0])*e):(u=Math.abs(r-t[0])*e+i,p=Math.abs(o-t[1])*e+n,g=(t[2]-t[0])*e,m=(t[3]-t[1])*e),this.transform=[h*e,l*e,d*e,c*e,u-h*e*r-d*e*o,p-l*e*r-c*e*o],this.width=g,this.height=m}get rawDims(){const{viewBox:t}=this;return at(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:s=this.offsetX,offsetY:i=this.offsetY,dontFlip:n=!1}={}){return new Vt({viewBox:this.viewBox.slice(),scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}convertToViewportPoint(t,e){return At.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=At.applyTransform([t[0],t[1]],this.transform),s=At.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],s[0],s[1]]}convertToPdfPoint(t,e){return At.applyInverseTransform([t,e],this.transform)}}class Gt extends rt{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function Wt(t){const e=t.length;let s=0;for(;s<e&&""===t[s].trim();)s++;return"data:"===t.substring(s,s+5).toLowerCase()}function qt(t){return"string"==typeof t&&/\.pdf$/i.test(t)}function Xt(t){return[t]=t.split(/[#?]/,1),t.substring(t.lastIndexOf("/")+1)}function Kt(t,e="document.pdf"){if("string"!=typeof t)return e;if(Wt(t))return et('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),e;const s=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,i=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/.exec(t);let n=s.exec(i[1])||s.exec(i[2])||s.exec(i[3]);if(n&&(n=n[0],n.includes("%")))try{n=s.exec(decodeURIComponent(n))[0]}catch{}return n||e}class Yt{started=Object.create(null);times=[];time(t){t in this.started&&et(`Timer is already running for ${t}`),this.started[t]=Date.now()}timeEnd(t){t in this.started||et(`Timer has not been started for ${t}`),this.times.push({name:t,start:this.started[t],end:Date.now()}),delete this.started[t]}toString(){const t=[];let e=0;for(const{name:t}of this.times)e=Math.max(t.length,e);for(const{name:s,start:i,end:n}of this.times)t.push(`${s.padEnd(e)} ${n-i}ms\n`);return t.join("")}}function Qt(t,e){try{const{protocol:s}=e?new URL(t,e):new URL(t);return"http:"===s||"https:"===s}catch{return!1}}function Jt(t){t.preventDefault()}function Zt(t){console.log("Deprecated API usage: "+t)}let te;class ee{static toDateObject(t){if(!t||"string"!=typeof t)return null;te||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");const e=te.exec(t);if(!e)return null;const s=parseInt(e[1],10);let i=parseInt(e[2],10);i=i>=1&&i<=12?i-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let a=parseInt(e[4],10);a=a>=0&&a<=23?a:0;let r=parseInt(e[5],10);r=r>=0&&r<=59?r:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const h=e[7]||"Z";let l=parseInt(e[8],10);l=l>=0&&l<=23?l:0;let d=parseInt(e[9],10)||0;return d=d>=0&&d<=59?d:0,"-"===h?(a+=l,r+=d):"+"===h&&(a-=l,r-=d),new Date(Date.UTC(s,i,n,a,r,o))}}function se(t,{scale:e=1,rotation:s=0}){const{width:i,height:n}=t.attributes.style,a=[0,0,parseInt(i),parseInt(n)];return new Vt({viewBox:a,scale:e,rotation:s})}function ie(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(16711680&e)>>16,(65280&e)>>8,255&e]}return t.startsWith("rgb(")?t.slice(4,-1).split(",").map(t=>parseInt(t)):t.startsWith("rgba(")?t.slice(5,-1).split(",").map(t=>parseInt(t)).slice(0,3):(et(`Not a valid color format: "${t}"`),[0,0,0])}function ne(t){const{a:e,b:s,c:i,d:n,e:a,f:r}=t.getTransform();return[e,s,i,n,a,r]}function ae(t){const{a:e,b:s,c:i,d:n,e:a,f:r}=t.getTransform().invertSelf();return[e,s,i,n,a,r]}function re(t,e,s=!1,i=!0){if(e instanceof Vt){const{pageWidth:i,pageHeight:n}=e.rawDims,{style:a}=t,r=bt.isCSSRoundSupported,o=`var(--scale-factor) * ${i}px`,h=`var(--scale-factor) * ${n}px`,l=r?`round(${o}, 1px)`:`calc(${o})`,d=r?`round(${h}, 1px)`:`calc(${h})`;s&&e.rotation%180!=0?(a.width=d,a.height=l):(a.width=l,a.height=d)}i&&t.setAttribute("data-main-rotation",e.rotation)}class oe{#i=null;#n=null;#a;#r=null;constructor(t){this.#a=t}render(){const t=this.#i=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar");const e=this.#a._uiManager._signal;t.addEventListener("contextmenu",Jt,{signal:e}),t.addEventListener("pointerdown",oe.#o,{signal:e});const s=this.#r=document.createElement("div");s.className="buttons",t.append(s);const i=this.#a.toolbarPosition;if(i){const{style:e}=t,s="ltr"===this.#a._uiManager.direction?1-i[0]:i[0];e.insetInlineEnd=100*s+"%",e.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return this.#h(),t}static#o(t){t.stopPropagation()}#l(t){this.#a._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()}#d(t){this.#a._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()}#c(t){const e=this.#a._uiManager._signal;t.addEventListener("focusin",this.#l.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#d.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",Jt,{signal:e})}hide(){this.#i.classList.add("hidden"),this.#n?.hideDropdown()}show(){this.#i.classList.remove("hidden")}#h(){const t=document.createElement("button");t.className="delete",t.tabIndex=0,t.setAttribute("data-l10n-id",`pdfjs-editor-remove-${this.#a.editorType}-button`),this.#c(t),t.addEventListener("click",t=>{this.#a._uiManager.delete()},{signal:this.#a._uiManager._signal}),this.#r.append(t)}get#u(){const t=document.createElement("div");return t.className="divider",t}addAltTextButton(t){this.#c(t),this.#r.prepend(t,this.#u)}addColorPicker(t){this.#n=t;const e=t.renderButton();this.#c(e),this.#r.prepend(e,this.#u)}remove(){this.#i.remove(),this.#n?.destroy(),this.#n=null}}class he{#r=null;#i=null;#p;constructor(t){this.#p=t}#g(){const t=this.#i=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",Jt,{signal:this.#p._signal});const e=this.#r=document.createElement("div");return e.className="buttons",t.append(e),this.#m(),t}#f(t,e){let s=0,i=0;for(const n of t){const t=n.y+n.height;if(t<s)continue;const a=n.x+(e?n.width:0);t>s?(i=a,s=t):e?a>i&&(i=a):a<i&&(i=a)}return[e?1-i:i,s]}show(t,e,s){const[i,n]=this.#f(e,s),{style:a}=this.#i||=this.#g();t.append(this.#i),a.insetInlineEnd=100*i+"%",a.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){this.#i.remove()}#m(){const t=document.createElement("button");t.className="highlightButton",t.tabIndex=0,t.setAttribute("data-l10n-id","pdfjs-highlight-floating-button1");const e=document.createElement("span");t.append(e),e.className="visuallyHidden",e.setAttribute("data-l10n-id","pdfjs-highlight-floating-button-label");const s=this.#p._signal;t.addEventListener("contextmenu",Jt,{signal:s}),t.addEventListener("click",()=>{this.#p.highlightSelection("floating_button")},{signal:s}),this.#r.append(t)}}function le(t,e,s){for(const i of s)e.addEventListener(i,t[i].bind(t))}class de{#b=0;get id(){return"pdfjs_internal_editor_"+this.#b++}}class ce{#v=function(){if("undefined"!=typeof crypto&&"function"==typeof crypto?.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);if("undefined"!=typeof crypto&&"function"==typeof crypto?.getRandomValues)crypto.getRandomValues(t);else for(let e=0;e<32;e++)t[e]=Math.floor(255*Math.random());return gt(t)}();#b=0;#A=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;e.src='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>';return at(this,"_isSVGFittingCanvas",e.decode().then(()=>(t.drawImage(e,0,0,1,1,0,0,1,3),0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0])))}async#y(t,e){this.#A||=new Map;let s=this.#A.get(t);if(null===s)return null;if(s?.bitmap)return s.refCounter+=1,s;try{let t;if(s||={bitmap:null,id:`image_${this.#v}_${this.#b++}`,refCounter:0,isSvg:!1},"string"==typeof e?(s.url=e,t=await zt(e,"blob")):t=s.file=e,"image/svg+xml"===t.type){const e=ce._isSVGFittingCanvas,i=new FileReader,n=new Image,a=new Promise((t,a)=>{n.onload=()=>{s.bitmap=n,s.isSvg=!0,t()},i.onload=async()=>{const t=s.svgUrl=i.result;n.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t},n.onerror=i.onerror=a});i.readAsDataURL(t),await a}else s.bitmap=await createImageBitmap(t);s.refCounter=1}catch(t){console.error(t),s=null}return this.#A.set(t,s),s&&this.#A.set(s.id,s),s}async getFromFile(t){const{lastModified:e,name:s,size:i,type:n}=t;return this.#y(`${e}_${s}_${i}_${n}`,t)}async getFromUrl(t){return this.#y(t,t)}async getFromId(t){this.#A||=new Map;const e=this.#A.get(t);return e?e.bitmap?(e.refCounter+=1,e):e.file?this.getFromFile(e.file):this.getFromUrl(e.url):null}getSvgUrl(t){const e=this.#A.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#A||=new Map;const e=this.#A.get(t);e&&(e.refCounter-=1,0===e.refCounter&&(e.bitmap=null))}isValidId(t){return t.startsWith(`image_${this.#v}_`)}}class ue{#w=[];#_=!1;#x;#E=-1;constructor(t=128){this.#x=t}add({cmd:t,undo:e,post:s,mustExec:i,type:n=NaN,overwriteIfSameType:a=!1,keepUndo:r=!1}){if(i&&t(),this.#_)return;const o={cmd:t,undo:e,post:s,type:n};if(-1===this.#E)return this.#w.length>0&&(this.#w.length=0),this.#E=0,void this.#w.push(o);if(a&&this.#w[this.#E].type===n)return r&&(o.undo=this.#w[this.#E].undo),void(this.#w[this.#E]=o);const h=this.#E+1;h===this.#x?this.#w.splice(0,1):(this.#E=h,h<this.#w.length&&this.#w.splice(h)),this.#w.push(o)}undo(){if(-1===this.#E)return;this.#_=!0;const{undo:t,post:e}=this.#w[this.#E];t(),e?.(),this.#_=!1,this.#E-=1}redo(){if(this.#E<this.#w.length-1){this.#E+=1,this.#_=!0;const{cmd:t,post:e}=this.#w[this.#E];t(),e?.(),this.#_=!1}}hasSomethingToUndo(){return-1!==this.#E}hasSomethingToRedo(){return this.#E<this.#w.length-1}destroy(){this.#w=null}}class pe{constructor(t){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=bt.platform;for(const[s,i,n={}]of t)for(const t of s){const s=t.startsWith("mac+");e&&s?(this.callbacks.set(t.slice(4),{callback:i,options:n}),this.allKeys.add(t.split("+").at(-1))):e||s||(this.callbacks.set(t,{callback:i,options:n}),this.allKeys.add(t.split("+").at(-1)))}}#C(t){t.altKey&&this.buffer.push("alt"),t.ctrlKey&&this.buffer.push("ctrl"),t.metaKey&&this.buffer.push("meta"),t.shiftKey&&this.buffer.push("shift"),this.buffer.push(t.key);const e=this.buffer.join("+");return this.buffer.length=0,e}exec(t,e){if(!this.allKeys.has(e.key))return;const s=this.callbacks.get(this.#C(e));if(!s)return;const{callback:i,options:{bubbles:n=!1,args:a=[],checker:r=null}}=s;r&&!r(t,e)||(i.bind(t,...a,e)(),n||(e.stopPropagation(),e.preventDefault()))}}class ge{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return function(t){const e=document.createElement("span");e.style.visibility="hidden",document.body.append(e);for(const s of t.keys()){e.style.color=s;const i=window.getComputedStyle(e).color;t.set(s,ie(i))}e.remove()}(t),at(this,"_colors",t)}convert(t){const e=ie(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[t,s]of this._colors)if(s.every((t,s)=>t===e[s]))return ge._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?At.makeHexColor(...e):t}}class me{#S=new AbortController;#T=null;#M=new Map;#k=new Map;#P=null;#I=null;#R=null;#D=new ue;#L=0;#F=new Set;#O=null;#N=null;#B=new Set;#H=!1;#z=null;#j=null;#U=null;#$=!1;#V=null;#G=new de;#W=!1;#q=!1;#X=null;#K=null;#Y=null;#Q=g.NONE;#J=new Set;#Z=null;#tt=null;#et=null;#st=this.blur.bind(this);#it=this.focus.bind(this);#nt=this.copy.bind(this);#at=this.cut.bind(this);#rt=this.paste.bind(this);#ot=this.keydown.bind(this);#ht=this.keyup.bind(this);#lt=this.onEditingAction.bind(this);#dt=this.onPageChanging.bind(this);#ct=this.onScaleChanging.bind(this);#ut=this.onRotationChanging.bind(this);#pt={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#gt=[0,0];#mt=null;#ft=null;#bt=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=me.prototype,e=t=>t.#ft.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),s=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},i=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return at(this,"_keyboardManager",new pe([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:s}],[["ctrl+z","mac+meta+z"],t.undo,{checker:s}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:s}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:s}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#ft.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#ft.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}]]))}constructor(t,e,s,i,n,a,r,o,h){this._signal=this.#S.signal,this.#ft=t,this.#bt=e,this.#P=s,this._eventBus=i,this._eventBus._on("editingaction",this.#lt),this._eventBus._on("pagechanging",this.#dt),this._eventBus._on("scalechanging",this.#ct),this._eventBus._on("rotationchanging",this.#ut),this.#vt(),this.#At(),this.#yt(),this.#I=n.annotationStorage,this.#z=n.filterFactory,this.#tt=a,this.#U=r||null,this.#H=o,this.#Y=h||null,this.viewParameters={realScale:Ht.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}destroy(){this.#S?.abort(),this.#S=null,this._signal=null,this._eventBus._off("editingaction",this.#lt),this._eventBus._off("pagechanging",this.#dt),this._eventBus._off("scalechanging",this.#ct),this._eventBus._off("rotationchanging",this.#ut);for(const t of this.#k.values())t.destroy();this.#k.clear(),this.#M.clear(),this.#B.clear(),this.#T=null,this.#J.clear(),this.#D.destroy(),this.#P?.destroy(),this.#V?.hide(),this.#V=null,this.#j&&(clearTimeout(this.#j),this.#j=null),this.#mt&&(clearTimeout(this.#mt),this.#mt=null)}async mlGuess(t){return this.#Y?.guess(t)||null}get hasMLManager(){return!!this.#Y}get hcmFilter(){return at(this,"hcmFilter",this.#tt?this.#z.addHCMFilter(this.#tt.foreground,this.#tt.background):"none")}get direction(){return at(this,"direction",getComputedStyle(this.#ft).direction)}get highlightColors(){return at(this,"highlightColors",this.#U?new Map(this.#U.split(",").map(t=>t.split("=").map(t=>t.trim()))):null)}get highlightColorNames(){return at(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setMainHighlightColorPicker(t){this.#K=t}editAltText(t){this.#P?.editAltText(this,t)}onPageChanging({pageNumber:t}){this.#L=t-1}focusMainContainer(){this.#ft.focus()}findParent(t,e){for(const s of this.#k.values()){const{x:i,y:n,width:a,height:r}=s.div.getBoundingClientRect();if(t>=i&&t<=i+a&&e>=n&&e<=n+r)return s}return null}disableUserSelect(t=!1){this.#bt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#B.add(t)}removeShouldRescale(t){this.#B.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*Ht.PDF_TO_CSS_UNITS;for(const t of this.#B)t.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#wt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:a}=e,r=e.toString(),o=this.#wt(e).closest(".textLayer"),h=this.getSelectionBoxes(o);if(h){e.empty(),this.#Q===g.NONE&&(this._eventBus.dispatch("showannotationeditorui",{source:this,mode:g.HIGHLIGHT}),this.showAllEditors("highlight",!0,!0));for(const e of this.#k.values())if(e.hasTextLayer(o)){e.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:h,anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:a,text:r});break}}}#_t(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#wt(t).closest(".textLayer"),s=this.getSelectionBoxes(e);s&&(this.#V||=new he(this),this.#V.show(e,s,"ltr"===this.direction))}addToAnnotationStorage(t){t.isEmpty()||!this.#I||this.#I.has(t.id)||this.#I.setValue(t.id,t)}#xt(){const t=document.getSelection();if(!t||t.isCollapsed)return void(this.#Z&&(this.#V?.hide(),this.#Z=null,this.#Et({hasSelectedText:!1})));const{anchorNode:e}=t;if(e===this.#Z)return;if(this.#wt(t).closest(".textLayer")){if(this.#V?.hide(),this.#Z=e,this.#Et({hasSelectedText:!0}),(this.#Q===g.HIGHLIGHT||this.#Q===g.NONE)&&(this.#Q===g.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#$=this.isShiftKeyDown,!this.isShiftKeyDown)){const t=this._signal,e=t=>{"pointerup"===t.type&&0!==t.button||(window.removeEventListener("pointerup",e),window.removeEventListener("blur",e),"pointerup"===t.type&&this.#Ct("main_toolbar"))};window.addEventListener("pointerup",e,{signal:t}),window.addEventListener("blur",e,{signal:t})}}else this.#Z&&(this.#V?.hide(),this.#Z=null,this.#Et({hasSelectedText:!1}))}#Ct(t=""){this.#Q===g.HIGHLIGHT?this.highlightSelection(t):this.#H&&this.#_t()}#vt(){document.addEventListener("selectionchange",this.#xt.bind(this),{signal:this._signal})}#St(){const t=this._signal;window.addEventListener("focus",this.#it,{signal:t}),window.addEventListener("blur",this.#st,{signal:t})}#Tt(){window.removeEventListener("focus",this.#it),window.removeEventListener("blur",this.#st)}blur(){if(this.isShiftKeyDown=!1,this.#$&&(this.#$=!1,this.#Ct("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#J)if(e.div.contains(t)){this.#X=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#X)return;const[t,e]=this.#X;this.#X=null,e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}#yt(){const t=this._signal;window.addEventListener("keydown",this.#ot,{signal:t}),window.addEventListener("keyup",this.#ht,{signal:t})}#Mt(){window.removeEventListener("keydown",this.#ot),window.removeEventListener("keyup",this.#ht)}#kt(){const t=this._signal;document.addEventListener("copy",this.#nt,{signal:t}),document.addEventListener("cut",this.#at,{signal:t}),document.addEventListener("paste",this.#rt,{signal:t})}#Pt(){document.removeEventListener("copy",this.#nt),document.removeEventListener("cut",this.#at),document.removeEventListener("paste",this.#rt)}#At(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#yt(),this.#kt()}removeEditListeners(){this.#Mt(),this.#Pt()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const s of this.#N)if(s.isHandlingMimeForPasting(e))return t.dataTransfer.dropEffect="copy",void t.preventDefault()}drop(t){for(const e of t.dataTransfer.items)for(const s of this.#N)if(s.isHandlingMimeForPasting(e.type))return s.paste(e,this.currentLayer),void t.preventDefault()}copy(t){if(t.preventDefault(),this.#T?.commitOrRemove(),!this.hasSelection)return;const e=[];for(const t of this.#J){const s=t.serialize(!0);s&&e.push(s)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#N)if(e.isHandlingMimeForPasting(t.type))return void e.paste(t,this.currentLayer);let s=e.getData("application/pdfjs");if(!s)return;try{s=JSON.parse(s)}catch(t){return void et(`paste: "${t.message}".`)}if(!Array.isArray(s))return;this.unselectAll();const i=this.currentLayer;try{const t=[];for(const e of s){const s=i.deserialize(e);if(!s)return;t.push(s)}const e=()=>{for(const e of t)this.#It(e);this.#Rt(t)},n=()=>{for(const e of t)e.remove()};this.addCommands({cmd:e,undo:n,mustExec:!0})}catch(t){et(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0),this.#Q===g.NONE||this.isEditorHandlingKeyboard||me._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&"Shift"===t.key&&(this.isShiftKeyDown=!1,this.#$&&(this.#$=!1,this.#Ct("main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#Et(t){Object.entries(t).some(([t,e])=>this.#pt[t]!==e)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#pt,t)}),this.#Q===g.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#Dt([[m.HIGHLIGHT_FREE,!0]]))}#Dt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#St(),this.#kt(),this.#Et({isEditing:this.#Q!==g.NONE,isEmpty:this.#Lt(),hasSomethingToUndo:this.#D.hasSomethingToUndo(),hasSomethingToRedo:this.#D.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#Tt(),this.#Pt(),this.#Et({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#N){this.#N=t;for(const t of this.#N)this.#Dt(t.defaultPropertiesToUpdate)}}getId(){return this.#G.id}get currentLayer(){return this.#k.get(this.#L)}getLayer(t){return this.#k.get(t)}get currentPageIndex(){return this.#L}addLayer(t){this.#k.set(t.pageIndex,t),this.#W?t.enable():t.disable()}removeLayer(t){this.#k.delete(t.pageIndex)}updateMode(t,e=null,s=!1){if(this.#Q!==t){if(this.#Q=t,t===g.NONE)return this.setEditingState(!1),void this.#Ft();this.setEditingState(!0),this.#Ot(),this.unselectAll();for(const e of this.#k.values())e.updateMode(t);if(e||!s){if(e)for(const t of this.#M.values())if(t.annotationElementId===e){this.setSelected(t),t.enterInEditMode();break}}else this.addNewEditorFromKeyboard()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#Q&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#N){switch(t){case m.CREATE:return void this.currentLayer.addNewEditor();case m.HIGHLIGHT_DEFAULT_COLOR:this.#K?.updateColor(e);break;case m.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#et||=new Map).set(t,e),this.showAllEditors("highlight",e)}for(const s of this.#J)s.updateParams(t,e);for(const s of this.#N)s.updateDefaultParams(t,e)}}showAllEditors(t,e,s=!1){for(const s of this.#M.values())s.editorType===t&&s.show(e);(this.#et?.get(m.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#Dt([[m.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#q!==t){this.#q=t;for(const e of this.#k.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}#Ot(){if(!this.#W){this.#W=!0;for(const t of this.#k.values())t.enable();for(const t of this.#M.values())t.enable()}}#Ft(){if(this.unselectAll(),this.#W){this.#W=!1;for(const t of this.#k.values())t.disable();for(const t of this.#M.values())t.disable()}}getEditors(t){const e=[];for(const s of this.#M.values())s.pageIndex===t&&e.push(s);return e}getEditor(t){return this.#M.get(t)}addEditor(t){this.#M.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#j&&clearTimeout(this.#j),this.#j=setTimeout(()=>{this.focusMainContainer(),this.#j=null},0)),this.#M.delete(t.id),this.unselect(t),t.annotationElementId&&this.#F.has(t.annotationElementId)||this.#I?.remove(t.id)}addDeletedAnnotationElement(t){this.#F.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#F.has(t)}removeDeletedAnnotationElement(t){this.#F.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#It(t){const e=this.#k.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#T!==t&&(this.#T=t,t&&this.#Dt(t.propertiesToUpdate))}get#Nt(){let t=null;for(t of this.#J);return t}updateUI(t){this.#Nt===t&&this.#Dt(t.propertiesToUpdate)}toggleSelected(t){if(this.#J.has(t))return this.#J.delete(t),t.unselect(),void this.#Et({hasSelectedEditor:this.hasSelection});this.#J.add(t),t.select(),this.#Dt(t.propertiesToUpdate),this.#Et({hasSelectedEditor:!0})}setSelected(t){for(const e of this.#J)e!==t&&e.unselect();this.#J.clear(),this.#J.add(t),t.select(),this.#Dt(t.propertiesToUpdate),this.#Et({hasSelectedEditor:!0})}isSelected(t){return this.#J.has(t)}get firstSelectedEditor(){return this.#J.values().next().value}unselect(t){t.unselect(),this.#J.delete(t),this.#Et({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#J.size}get isEnterHandled(){return 1===this.#J.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#D.undo(),this.#Et({hasSomethingToUndo:this.#D.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#Lt()})}redo(){this.#D.redo(),this.#Et({hasSomethingToUndo:!0,hasSomethingToRedo:this.#D.hasSomethingToRedo(),isEmpty:this.#Lt()})}addCommands(t){this.#D.add(t),this.#Et({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#Lt()})}#Lt(){if(0===this.#M.size)return!0;if(1===this.#M.size)for(const t of this.#M.values())return t.isEmpty();return!1}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const t=[...this.#J];this.addCommands({cmd:()=>{for(const e of t)e.remove()},undo:()=>{for(const e of t)this.#It(e)},mustExec:!0})}commitOrRemove(){this.#T?.commitOrRemove()}hasSomethingToControl(){return this.#T||this.hasSelection}#Rt(t){for(const t of this.#J)t.unselect();this.#J.clear();for(const e of t)e.isEmpty()||(this.#J.add(e),e.select());this.#Et({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#J)t.commit();this.#Rt(this.#M.values())}unselectAll(){if((!this.#T||(this.#T.commitOrRemove(),this.#Q===g.NONE))&&this.hasSelection){for(const t of this.#J)t.unselect();this.#J.clear(),this.#Et({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;this.#gt[0]+=t,this.#gt[1]+=e;const[i,n]=this.#gt,a=[...this.#J];this.#mt&&clearTimeout(this.#mt),this.#mt=setTimeout(()=>{this.#mt=null,this.#gt[0]=this.#gt[1]=0,this.addCommands({cmd:()=>{for(const t of a)this.#M.has(t.id)&&t.translateInPage(i,n)},undo:()=>{for(const t of a)this.#M.has(t.id)&&t.translateInPage(-i,-n)},mustExec:!1})},1e3);for(const s of a)s.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#O=new Map;for(const t of this.#J)this.#O.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#O)return!1;this.disableUserSelect(!1);const t=this.#O;this.#O=null;let e=!1;for(const[{x:s,y:i,pageIndex:n},a]of t)a.newX=s,a.newY=i,a.newPageIndex=n,e||=s!==a.savedX||i!==a.savedY||n!==a.savedPageIndex;if(!e)return!1;const s=(t,e,s,i)=>{if(this.#M.has(t.id)){const n=this.#k.get(i);n?t._setParentAndPosition(n,e,s):(t.pageIndex=i,t.x=e,t.y=s)}};return this.addCommands({cmd:()=>{for(const[e,{newX:i,newY:n,newPageIndex:a}]of t)s(e,i,n,a)},undo:()=>{for(const[e,{savedX:i,savedY:n,savedPageIndex:a}]of t)s(e,i,n,a)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#O)for(const s of this.#O.keys())s.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);e?(e.changeParent(t),e.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#J.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#T===t}getActive(){return this.#T}getMode(){return this.#Q}get imageManager(){return at(this,"imageManager",new ce)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let s=0,i=e.rangeCount;s<i;s++)if(!t.contains(e.getRangeAt(s).commonAncestorContainer))return null;const{x:s,y:i,width:n,height:a}=t.getBoundingClientRect();let r;switch(t.getAttribute("data-main-rotation")){case"90":r=(t,e,r,o)=>({x:(e-i)/a,y:1-(t+r-s)/n,width:o/a,height:r/n});break;case"180":r=(t,e,r,o)=>({x:1-(t+r-s)/n,y:1-(e+o-i)/a,width:r/n,height:o/a});break;case"270":r=(t,e,r,o)=>({x:1-(e+o-i)/a,y:(t-s)/n,width:o/a,height:r/n});break;default:r=(t,e,r,o)=>({x:(t-s)/n,y:(e-i)/a,width:r/n,height:o/a})}const o=[];for(let t=0,s=e.rangeCount;t<s;t++){const s=e.getRangeAt(t);if(!s.collapsed)for(const{x:t,y:e,width:i,height:n}of s.getClientRects())0!==i&&0!==n&&o.push(r(t,e,i,n))}return 0===o.length?null:o}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#R||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#R?.delete(t)}renderAnnotationElement(t){const e=this.#R?.get(t.data.id);if(!e)return;const s=this.#I.getRawValue(e);s&&(this.#Q!==g.NONE||s.hasBeenModified)&&s.renderAnnotationElement(t)}}class fe{#Bt="";#Ht=!1;#zt=null;#jt=null;#Ut=null;#$t=!1;#a=null;static _l10nPromise=null;constructor(t){this.#a=t}static initialize(t){fe._l10nPromise||=t}async render(){const t=this.#zt=document.createElement("button");t.className="altText";const e=await fe._l10nPromise.get("pdfjs-editor-alt-text-button-label");t.textContent=e,t.setAttribute("aria-label",e),t.tabIndex="0";const s=this.#a._uiManager._signal;t.addEventListener("contextmenu",Jt,{signal:s}),t.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:s});const i=t=>{t.preventDefault(),this.#a._uiManager.editAltText(this.#a)};return t.addEventListener("click",i,{capture:!0,signal:s}),t.addEventListener("keydown",e=>{e.target===t&&"Enter"===e.key&&(this.#$t=!0,i(e))},{signal:s}),await this.#Vt(),t}finish(){this.#zt&&(this.#zt.focus({focusVisible:this.#$t}),this.#$t=!1)}isEmpty(){return!this.#Bt&&!this.#Ht}get data(){return{altText:this.#Bt,decorative:this.#Ht}}set data({altText:t,decorative:e}){this.#Bt===t&&this.#Ht===e||(this.#Bt=t,this.#Ht=e,this.#Vt())}toggle(t=!1){this.#zt&&(!t&&this.#Ut&&(clearTimeout(this.#Ut),this.#Ut=null),this.#zt.disabled=!t)}destroy(){this.#zt?.remove(),this.#zt=null,this.#jt=null}async#Vt(){const t=this.#zt;if(!t)return;if(!this.#Bt&&!this.#Ht)return t.classList.remove("done"),void this.#jt?.remove();t.classList.add("done"),fe._l10nPromise.get("pdfjs-editor-alt-text-edit-button-label").then(e=>{t.setAttribute("aria-label",e)});let e=this.#jt;if(!e){this.#jt=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip");const s=e.id=`alt-text-tooltip-${this.#a.id}`;t.setAttribute("aria-describedby",s);const i=100,n=this.#a._uiManager._signal;n.addEventListener("abort",()=>{clearTimeout(this.#Ut),this.#Ut=null},{once:!0}),t.addEventListener("mouseenter",()=>{this.#Ut=setTimeout(()=>{this.#Ut=null,this.#jt.classList.add("show"),this.#a._reportTelemetry({action:"alt_text_tooltip"})},i)},{signal:n}),t.addEventListener("mouseleave",()=>{this.#Ut&&(clearTimeout(this.#Ut),this.#Ut=null),this.#jt?.classList.remove("show")},{signal:n})}e.innerText=this.#Ht?await fe._l10nPromise.get("pdfjs-editor-alt-text-decorative-tooltip"):this.#Bt,e.parentNode||t.append(e);const s=this.#a.getImageForAltText();s?.setAttribute("aria-describedby",e.id)}}class be{#Gt=null;#Wt=null;#Bt=null;#qt=!1;#Xt=!1;#Kt=null;#Yt=null;#Qt=this.focusin.bind(this);#Jt=this.focusout.bind(this);#Zt=null;#te="";#ee=!1;#se=null;#ie=!1;#ne=!1;#ae=!1;#re=null;#oe=0;#he=0;#le=null;_initialOptions=Object.create(null);_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;_l10nPromise=null;#de=!1;#ce=be._zIndex++;static _borderLineWidth=-1;static _colorManager=new ge;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=be.prototype._resizeWithKeyboard,e=me.TRANSLATE_SMALL,s=me.TRANSLATE_BIG;return at(this,"_resizerKeyboardManager",new pe([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-s,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[s,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-s]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,s]}],[["Escape","mac+Escape"],be.prototype._stopResizingWithKeyboard]]))}constructor(t){this.constructor===be&&st("Cannot initialize AnnotationEditor."),this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:s,pageHeight:i,pageX:n,pageY:a}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[s,i],this.pageTranslation=[n,a];const[r,o]=this.parentDimensions;this.x=t.x/r,this.y=t.y/o,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return at(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new ve({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId,e.deleted=!0,e._uiManager.addToAnnotationStorage(e)}static initialize(t,e,s){if(be._l10nPromise||=new Map(["pdfjs-editor-alt-text-button-label","pdfjs-editor-alt-text-edit-button-label","pdfjs-editor-alt-text-decorative-tooltip","pdfjs-editor-resizer-label-topLeft","pdfjs-editor-resizer-label-topMiddle","pdfjs-editor-resizer-label-topRight","pdfjs-editor-resizer-label-middleRight","pdfjs-editor-resizer-label-bottomRight","pdfjs-editor-resizer-label-bottomMiddle","pdfjs-editor-resizer-label-bottomLeft","pdfjs-editor-resizer-label-middleLeft"].map(e=>[e,t.get(e.replaceAll(/([A-Z])/g,t=>`-${t.toLowerCase()}`))])),s?.strings)for(const e of s.strings)be._l10nPromise.set(e,t.get(e));if(-1!==be._borderLineWidth)return;const i=getComputedStyle(document.documentElement);be._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){st("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#de}set _isDraggable(t){this.#de=t,this.div?.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(2*t),this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t),this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#ce}setParent(t){null!==t?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):this.#ue(),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#ee?this.#ee=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;e?.closest(`#${this.id}`)||(t.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,s,i){const[n,a]=this.parentDimensions;[s,i]=this.screenToPageTranslation(s,i),this.x=(t+s)/n,this.y=(e+i)/a,this.fixAndSetPosition()}#pe([t,e],s,i){[s,i]=this.screenToPageTranslation(s,i),this.x+=s/t,this.y+=i/e,this.fixAndSetPosition()}translate(t,e){this.#pe(this.parentDimensions,t,e)}translateInPage(t,e){this.#se||=[this.x,this.y],this.#pe(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#se||=[this.x,this.y];const[s,i]=this.parentDimensions;if(this.x+=t/s,this.y+=e/i,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();this.parent.findNewParent(this,t,e)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:n,y:a}=this;const[r,o]=this.getBaseTranslation();n+=r,a+=o,this.div.style.left=`${(100*n).toFixed(2)}%`,this.div.style.top=`${(100*a).toFixed(2)}%`,this.div.scrollIntoView({block:"nearest"})}get _hasBeenMoved(){return!!this.#se&&(this.#se[0]!==this.x||this.#se[1]!==this.y)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:s}=be,i=s/t,n=s/e;switch(this.rotation){case 90:return[-i,n];case 180:return[i,n];case 270:return[i,-n];default:return[-i,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const[e,s]=this.pageDimensions;let{x:i,y:n,width:a,height:r}=this;if(a*=e,r*=s,i*=e,n*=s,this._mustFixPosition)switch(t){case 0:i=Math.max(0,Math.min(e-a,i)),n=Math.max(0,Math.min(s-r,n));break;case 90:i=Math.max(0,Math.min(e-r,i)),n=Math.min(s,Math.max(a,n));break;case 180:i=Math.min(e,Math.max(a,i)),n=Math.min(s,Math.max(r,n));break;case 270:i=Math.min(e,Math.max(r,i)),n=Math.max(0,Math.min(s-a,n))}this.x=i/=e,this.y=n/=s;const[o,h]=this.getBaseTranslation();i+=o,n+=h;const{style:l}=this.div;l.left=`${(100*i).toFixed(2)}%`,l.top=`${(100*n).toFixed(2)}%`,this.moveInDOM()}static#ge(t,e,s){switch(s){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return be.#ge(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return be.#ge(t,e,360-this.parentRotation)}#me(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,s]}=this,i=e*t,n=s*t;return bt.isCSSRoundSupported?[Math.round(i),Math.round(n)]:[i,n]}setDims(t,e){const[s,i]=this.parentDimensions;this.div.style.width=`${(100*t/s).toFixed(2)}%`,this.#Xt||(this.div.style.height=`${(100*e/i).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:s}=t,i=s.endsWith("%"),n=!this.#Xt&&e.endsWith("%");if(i&&n)return;const[a,r]=this.parentDimensions;i||(t.width=`${(100*parseFloat(s)/a).toFixed(2)}%`),this.#Xt||n||(t.height=`${(100*parseFloat(e)/r).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#fe(){if(this.#Kt)return;this.#Kt=document.createElement("div"),this.#Kt.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const s of t){const t=document.createElement("div");this.#Kt.append(t),t.classList.add("resizer",s),t.setAttribute("data-resizer-name",s),t.addEventListener("pointerdown",this.#be.bind(this,s),{signal:e}),t.addEventListener("contextmenu",Jt,{signal:e}),t.tabIndex=-1}this.div.prepend(this.#Kt)}#be(t,e){e.preventDefault();const{isMac:s}=bt.platform;if(0!==e.button||e.ctrlKey&&s)return;this.#Bt?.toggle(!1);const i=this.#ve.bind(this,t),n=this._isDraggable;this._isDraggable=!1;const a=this._uiManager._signal,r={passive:!0,capture:!0,signal:a};this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",i,r),window.addEventListener("contextmenu",Jt,{signal:a});const o=this.x,h=this.y,l=this.width,d=this.height,c=this.parent.div.style.cursor,u=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const p=()=>{this.parent.togglePointerEvents(!0),this.#Bt?.toggle(!0),this._isDraggable=n,window.removeEventListener("pointerup",p),window.removeEventListener("blur",p),window.removeEventListener("pointermove",i,r),window.removeEventListener("contextmenu",Jt),this.parent.div.style.cursor=c,this.div.style.cursor=u,this.#Ae(o,h,l,d)};window.addEventListener("pointerup",p,{signal:a}),window.addEventListener("blur",p,{signal:a})}#Ae(t,e,s,i){const n=this.x,a=this.y,r=this.width,o=this.height;n===t&&a===e&&r===s&&o===i||this.addCommands({cmd:()=>{this.width=r,this.height=o,this.x=n,this.y=a;const[t,e]=this.parentDimensions;this.setDims(t*r,e*o),this.fixAndSetPosition()},undo:()=>{this.width=s,this.height=i,this.x=t,this.y=e;const[n,a]=this.parentDimensions;this.setDims(n*s,a*i),this.fixAndSetPosition()},mustExec:!0})}#ve(t,e){const[s,i]=this.parentDimensions,n=this.x,a=this.y,r=this.width,o=this.height,h=be.MIN_SIZE/s,l=be.MIN_SIZE/i,d=t=>Math.round(1e4*t)/1e4,c=this.#me(this.rotation),u=(t,e)=>[c[0]*t+c[2]*e,c[1]*t+c[3]*e],p=this.#me(360-this.rotation);let g,m,f=!1,b=!1;switch(t){case"topLeft":f=!0,g=(t,e)=>[0,0],m=(t,e)=>[t,e];break;case"topMiddle":g=(t,e)=>[t/2,0],m=(t,e)=>[t/2,e];break;case"topRight":f=!0,g=(t,e)=>[t,0],m=(t,e)=>[0,e];break;case"middleRight":b=!0,g=(t,e)=>[t,e/2],m=(t,e)=>[0,e/2];break;case"bottomRight":f=!0,g=(t,e)=>[t,e],m=(t,e)=>[0,0];break;case"bottomMiddle":g=(t,e)=>[t/2,e],m=(t,e)=>[t/2,0];break;case"bottomLeft":f=!0,g=(t,e)=>[0,e],m=(t,e)=>[t,0];break;case"middleLeft":b=!0,g=(t,e)=>[0,e/2],m=(t,e)=>[t,e/2]}const v=g(r,o),A=m(r,o);let y=u(...A);const w=d(n+y[0]),_=d(a+y[1]);let x=1,E=1,[C,S]=this.screenToPageTranslation(e.movementX,e.movementY);var T,M;if([C,S]=(T=C/s,M=S/i,[p[0]*T+p[2]*M,p[1]*T+p[3]*M]),f){const t=Math.hypot(r,o);x=E=Math.max(Math.min(Math.hypot(A[0]-v[0]-C,A[1]-v[1]-S)/t,1/r,1/o),h/r,l/o)}else b?x=Math.max(h,Math.min(1,Math.abs(A[0]-v[0]-C)))/r:E=Math.max(l,Math.min(1,Math.abs(A[1]-v[1]-S)))/o;const k=d(r*x),P=d(o*E);y=u(...m(k,P));const I=w-y[0],R=_-y[1];this.width=k,this.height=P,this.x=I,this.y=R,this.setDims(s*k,i*P),this.fixAndSetPosition()}altTextFinish(){this.#Bt?.finish()}async addEditToolbar(){return this.#Zt||this.#ne||(this.#Zt=new oe(this),this.div.append(this.#Zt.render()),this.#Bt&&this.#Zt.addAltTextButton(await this.#Bt.render())),this.#Zt}removeEditToolbar(){this.#Zt&&(this.#Zt.remove(),this.#Zt=null,this.#Bt?.destroy())}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#Bt||(fe.initialize(be._l10nPromise),this.#Bt=new fe(this),this.#Gt&&(this.#Bt.data=this.#Gt,this.#Gt=null),await this.addEditToolbar())}get altTextData(){return this.#Bt?.data}set altTextData(t){this.#Bt&&(this.#Bt.data=t)}hasAltText(){return!this.#Bt?.isEmpty()}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=this.#qt?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground();const t=this._uiManager._signal;this.div.addEventListener("focusin",this.#Qt,{signal:t}),this.div.addEventListener("focusout",this.#Jt,{signal:t});const[e,s]=this.parentDimensions;this.parentRotation%180!=0&&(this.div.style.maxWidth=`${(100*s/e).toFixed(2)}%`,this.div.style.maxHeight=`${(100*e/s).toFixed(2)}%`);const[i,n]=this.getInitialTranslation();return this.translate(i,n),le(this,this.div,["pointerdown"]),this.div}pointerdown(t){const{isMac:e}=bt.platform;0!==t.button||t.ctrlKey&&e?t.preventDefault():(this.#ee=!0,this._isDraggable?this.#ye(t):this.#we(t))}#we(t){const{isMac:e}=bt.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#ye(t){const e=this._uiManager.isSelected(this);let s,i;this._uiManager.setUpDragSession();const n=this._uiManager._signal;e&&(this.div.classList.add("moving"),s={passive:!0,capture:!0,signal:n},this.#oe=t.clientX,this.#he=t.clientY,i=t=>{const{clientX:e,clientY:s}=t,[i,n]=this.screenToPageTranslation(e-this.#oe,s-this.#he);this.#oe=e,this.#he=s,this._uiManager.dragSelectedEditors(i,n)},window.addEventListener("pointermove",i,s));const a=()=>{window.removeEventListener("pointerup",a),window.removeEventListener("blur",a),e&&(this.div.classList.remove("moving"),window.removeEventListener("pointermove",i,s)),this.#ee=!1,this._uiManager.endDragSession()||this.#we(t)};window.addEventListener("pointerup",a,{signal:n}),window.addEventListener("blur",a,{signal:n})}moveInDOM(){this.#re&&clearTimeout(this.#re),this.#re=setTimeout(()=>{this.#re=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(t,e,s){t.changeParent(this),this.x=e,this.y=s,this.fixAndSetPosition()}getRect(t,e,s=this.rotation){const i=this.parentScale,[n,a]=this.pageDimensions,[r,o]=this.pageTranslation,h=t/i,l=e/i,d=this.x*n,c=this.y*a,u=this.width*n,p=this.height*a;switch(s){case 0:return[d+h+r,a-c-l-p+o,d+h+u+r,a-c-l+o];case 90:return[d+l+r,a-c+h+o,d+l+p+r,a-c+h+u+o];case 180:return[d-h-u+r,a-c+l+o,d-h+r,a-c+l+p+o];case 270:return[d-l-p+r,a-c-h-u+o,d-l+r,a-c-h+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[s,i,n,a]=t,r=n-s,o=a-i;switch(this.rotation){case 0:return[s,e-a,r,o];case 90:return[s,e-i,o,r];case 180:return[n,e-i,r,o];case 270:return[n,e-a,o,r];default:throw new Error("Invalid rotation")}}onceAdded(){}isEmpty(){return!1}enableEditMode(){this.#ne=!0}disableEditMode(){this.#ne=!1}isInEditMode(){return this.#ne}shouldGetKeyboardEvents(){return this.#ae}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){const t=this._uiManager._signal;this.div?.addEventListener("focusin",this.#Qt,{signal:t}),this.div?.addEventListener("focusout",this.#Jt,{signal:t})}rotate(t){}serialize(t=!1,e=null){st("An editor must be serializable")}static deserialize(t,e,s){const i=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:s});i.rotation=t.rotation,i.#Gt=t.accessibilityData;const[n,a]=i.pageDimensions,[r,o,h,l]=i.getRectInCurrentCoords(t.rect,a);return i.x=r/n,i.y=o/a,i.width=h/n,i.height=l/a,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){if(this.div.removeEventListener("focusin",this.#Qt),this.div.removeEventListener("focusout",this.#Jt),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#re&&(clearTimeout(this.#re),this.#re=null),this.#ue(),this.removeEditToolbar(),this.#le){for(const t of this.#le.values())clearTimeout(t);this.#le=null}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#fe(),this.#Kt.classList.remove("hidden"),le(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this),this.#Yt={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#Kt.children;if(!this.#Wt){this.#Wt=Array.from(e);const t=this.#_e.bind(this),s=this.#xe.bind(this),i=this._uiManager._signal;for(const e of this.#Wt){const n=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton"),e.addEventListener("keydown",t,{signal:i}),e.addEventListener("blur",s,{signal:i}),e.addEventListener("focus",this.#Ee.bind(this,n),{signal:i}),be._l10nPromise.get(`pdfjs-editor-resizer-label-${n}`).then(t=>e.setAttribute("aria-label",t))}}const s=this.#Wt[0];let i=0;for(const t of e){if(t===s)break;i++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#Wt.length/4);if(n!==i){if(n<i)for(let t=0;t<i-n;t++)this.#Kt.append(this.#Kt.firstChild);else if(n>i)for(let t=0;t<n-i;t++)this.#Kt.firstChild.before(this.#Kt.lastChild);let t=0;for(const s of e){const e=this.#Wt[t++].getAttribute("data-resizer-name");be._l10nPromise.get(`pdfjs-editor-resizer-label-${e}`).then(t=>s.setAttribute("aria-label",t))}}this.#Ce(0),this.#ae=!0,this.#Kt.firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#_e(t){be._resizerKeyboardManager.exec(this,t)}#xe(t){this.#ae&&t.relatedTarget?.parentNode!==this.#Kt&&this.#ue()}#Ee(t){this.#te=this.#ae?t:""}#Ce(t){if(this.#Wt)for(const e of this.#Wt)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#ae&&this.#ve(this.#te,{movementX:t,movementY:e})}#ue(){if(this.#ae=!1,this.#Ce(-1),this.#Yt){const{savedX:t,savedY:e,savedWidth:s,savedHeight:i}=this.#Yt;this.#Ae(t,e,s,i),this.#Yt=null}}_stopResizingWithKeyboard(){this.#ue(),this.div.focus()}select(){this.makeResizable(),this.div?.classList.add("selectedEditor"),this.#Zt?this.#Zt?.show():this.addEditToolbar().then(()=>{this.div?.classList.contains("selectedEditor")&&this.#Zt?.show()})}unselect(){this.#Kt?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this.#Zt?.hide()}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#ie}set isEditing(t){this.#ie=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,e){this.#Xt=!0;const s=t/e,{style:i}=this.div;i.aspectRatio=s,i.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#le||=new Map;const{action:e}=t;let s=this.#le.get(e);return s&&clearTimeout(s),s=setTimeout(()=>{this._reportTelemetry(t),this.#le.delete(e),0===this.#le.size&&(this.#le=null)},be._telemetryTimeout),void this.#le.set(e,s)}t.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t),this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0),this.#qt=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#qt=!0}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(e){if("CANVAS"===e.nodeName){const t=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.before(e)}}else e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);return e}resetAnnotationElement(t){const{firstChild:e}=t.container;"DIV"===e.nodeName&&e.classList.contains("annotationContent")&&e.remove()}}class ve extends be{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex}}}const Ae=3285377520,ye=4294901760,we=65535;class _e{constructor(t){this.h1=t?4294967295&t:Ae,this.h2=t?4294967295&t:Ae}update(t){let e,s;if("string"==typeof t){e=new Uint8Array(2*t.length),s=0;for(let i=0,n=t.length;i<n;i++){const n=t.charCodeAt(i);n<=255?e[s++]=n:(e[s++]=n>>>8,e[s++]=255&n)}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice(),s=e.byteLength}const i=s>>2,n=s-4*i,a=new Uint32Array(e.buffer,0,i);let r=0,o=0,h=this.h1,l=this.h2;const d=3432918353,c=461845907,u=11601,p=13715;for(let t=0;t<i;t++)1&t?(r=a[t],r=r*d&ye|r*u&we,r=r<<15|r>>>17,r=r*c&ye|r*p&we,h^=r,h=h<<13|h>>>19,h=5*h+3864292196):(o=a[t],o=o*d&ye|o*u&we,o=o<<15|o>>>17,o=o*c&ye|o*p&we,l^=o,l=l<<13|l>>>19,l=5*l+3864292196);switch(r=0,n){case 3:r^=e[4*i+2]<<16;case 2:r^=e[4*i+1]<<8;case 1:r^=e[4*i],r=r*d&ye|r*u&we,r=r<<15|r>>>17,r=r*c&ye|r*p&we,1&i?h^=r:l^=r}this.h1=h,this.h2=l}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=3981806797*t&ye|36045*t&we,e=4283543511*e&ye|(2950163797*(e<<16|t>>>16)&ye)>>>16,t^=e>>>1,t=444984403*t&ye|60499*t&we,e=3301882366*e&ye|(3120437893*(e<<16|t>>>16)&ye)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const xe=Object.freeze({map:null,hash:"",transfer:void 0});class Ee{#Se=!1;#Te=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const s=this.#Te.get(t);return void 0===s?e:Object.assign(e,s)}getRawValue(t){return this.#Te.get(t)}remove(t){if(this.#Te.delete(t),0===this.#Te.size&&this.resetModified(),"function"==typeof this.onAnnotationEditor){for(const t of this.#Te.values())if(t instanceof be)return;this.onAnnotationEditor(null)}}setValue(t,e){const s=this.#Te.get(t);let i=!1;if(void 0!==s)for(const[t,n]of Object.entries(e))s[t]!==n&&(i=!0,s[t]=n);else i=!0,this.#Te.set(t,e);i&&this.#Me(),e instanceof be&&"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#Te.has(t)}getAll(){return this.#Te.size>0?ft(this.#Te):null}setAll(t){for(const[e,s]of Object.entries(t))this.setValue(e,s)}get size(){return this.#Te.size}#Me(){this.#Se||(this.#Se=!0,"function"==typeof this.onSetModified&&this.onSetModified())}resetModified(){this.#Se&&(this.#Se=!1,"function"==typeof this.onResetModified&&this.onResetModified())}get print(){return new Ce(this)}get serializable(){if(0===this.#Te.size)return xe;const t=new Map,e=new _e,s=[],i=Object.create(null);let n=!1;for(const[s,a]of this.#Te){const r=a instanceof be?a.serialize(!1,i):a;r&&(t.set(s,r),e.update(`${s}:${JSON.stringify(r)}`),n||=!!r.bitmap)}if(n)for(const e of t.values())e.bitmap&&s.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:s}:xe}get editorStats(){let t=null;const e=new Map;for(const s of this.#Te.values()){if(!(s instanceof be))continue;const i=s.telemetryFinalData;if(!i)continue;const{type:n}=i;e.has(n)||e.set(n,Object.getPrototypeOf(s).constructor),t||=Object.create(null);const a=t[n]||=new Map;for(const[t,e]of Object.entries(i)){if("type"===t)continue;let s=a.get(t);s||(s=new Map,a.set(t,s));const i=s.get(e)??0;s.set(e,i+1)}}for(const[s,i]of e)t[s]=i.computeTelemetryFinalData(t[s]);return t}}class Ce extends Ee{#ke;constructor(t){super();const{map:e,hash:s,transfer:i}=t.serializable,n=structuredClone(e,i?{transfer:i}:null);this.#ke={map:n,hash:s,transfer:i}}get print(){st("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#ke}}class Se{#Pe=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear(),this.#Pe.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(t&&!this.#Pe.has(t.loadedName)){if(it(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:s,src:i,style:n}=t,a=new FontFace(s,i,n);this.addNativeFontFace(a);try{await a.load(),this.#Pe.add(s),e?.(t)}catch{et(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(a)}return}st("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo)return void await this.loadSystemFont(t);if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(s){throw et(`Failed to load font '${e.family}': '${s}'.`),t.disableFontFace=!0,s}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise(e=>{const s=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,s)})}}get isFontLoadingAPISupported(){return at(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){let t=!1;return(s||"undefined"!=typeof navigator&&"string"==typeof navigator?.userAgent&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),at(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){const{loadingRequests:e}=this,s={done:!1,complete:function(){for(it(!s.done,"completeRequest() cannot be called twice."),s.done=!0;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};return e.push(s),s}get _loadTestFont(){return at(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function s(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function i(t,e,s,i){return t.substring(0,e)+i+t.substring(e+s)}let n,a;const r=this._document.createElement("canvas");r.width=1,r.height=1;const o=r.getContext("2d");let h=0;const l=`lt${Date.now()}${this.loadTestFontId++}`;let d=this._loadTestFont;d=i(d,976,l.length,l);const c=1482184792;let u=s(d,16);for(n=0,a=l.length-3;n<a;n+=4)u=u-c+s(l,n)|0;var p;n<l.length&&(u=u-c+s(l+"XXX",n)|0),d=i(d,16,4,(p=u,String.fromCharCode(p>>24&255,p>>16&255,p>>8&255,255&p)));const g=`@font-face {font-family:"${l}";src:${`url(data:font/opentype;base64,${btoa(d)});`}}`;this.insertRule(g);const m=this._document.createElement("div");m.style.visibility="hidden",m.style.width=m.style.height="10px",m.style.position="absolute",m.style.top=m.style.left="0px";for(const e of[t.loadedName,l]){const t=this._document.createElement("span");t.textContent="Hi",t.style.fontFamily=e,m.append(t)}this._document.body.append(m),function t(e,s){if(++h>30)return et("Load test font never loaded."),void s();o.font="30px "+e,o.fillText(".",0,20),o.getImageData(0,0,1,1).data[3]>0?s():setTimeout(t.bind(null,e,s))}(l,()=>{m.remove(),e.complete()})}}class Te{constructor(t,{disableFontFace:e=!1,inspectFont:s=null}){this.compiledGlyphs=Object.create(null);for(const e in t)this[e]=t[e];this.disableFontFace=!0===e,this._inspectFont=s}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});return this._inspectFont?.(this),t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=gt(this.data),e=`url(data:${this.mimetype};base64,${btoa(t)});`;let s;if(this.cssFontInfo){let t=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(t+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),s=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${t}src:${e}}`}else s=`@font-face {font-family:"${this.loadedName}";src:${e}}`;return this._inspectFont?.(this,e),s}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];let s;try{s=t.get(this.loadedName+"_path_"+e)}catch(t){et(`getPathGenerator - ignoring character: "${t}".`)}if(!Array.isArray(s)||0===s.length)return this.compiledGlyphs[e]=function(t,e){};const i=[];for(let t=0,e=s.length;t<e;)switch(s[t++]){case Et:{const[e,n,a,r,o,h]=s.slice(t,t+6);i.push(t=>t.bezierCurveTo(e,n,a,r,o,h)),t+=6}break;case Ct:{const[e,n]=s.slice(t,t+2);i.push(t=>t.moveTo(e,n)),t+=2}break;case St:{const[e,n]=s.slice(t,t+2);i.push(t=>t.lineTo(e,n)),t+=2}break;case Tt:{const[e,n,a,r]=s.slice(t,t+4);i.push(t=>t.quadraticCurveTo(e,n,a,r)),t+=4}break;case Mt:i.push(t=>t.restore());break;case kt:i.push(t=>t.save());break;case Pt:it(2===i.length,"Scale command is only valid at the third position.");break;case It:{const[e,n,a,r,o,h]=s.slice(t,t+6);i.push(t=>t.transform(e,n,a,r,o,h)),t+=6}break;case Rt:{const[e,n]=s.slice(t,t+2);i.push(t=>t.translate(e,n)),t+=2}}return this.compiledGlyphs[e]=function(t,e){i[0](t),i[1](t),t.scale(e,-e);for(let e=2,s=i.length;e<s;e++)i[e](t)}}}if(s){var Me=Promise.withResolvers(),ke=null;(async()=>{const t=await import("fs"),e=await import("http"),s=await import("https"),i=await import("url");return new Map(Object.entries({fs:t,http:e,https:s,url:i,canvas:undefined,path2d:undefined}))})().then(t=>{ke=t,Me.resolve()},t=>{et(`loadPackages: ${t}`),ke=new Map,Me.resolve()})}class Pe{static get promise(){return Me.promise}static get(t){return ke?.get(t)}}const Ie=function(t){return Pe.get("fs").promises.readFile(t).then(t=>new Uint8Array(t))};const Re="Fill",De="Stroke",Le="Shading";function Fe(t,e){if(!e)return;const s=e[2]-e[0],i=e[3]-e[1],n=new Path2D;n.rect(e[0],e[1],s,i),t.clip(n)}class Oe{constructor(){this.constructor===Oe&&st("Cannot initialize BaseShadingPattern.")}getPattern(){st("Abstract method `getPattern` called.")}}class Ne extends Oe{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}_createGradient(t){let e;"axial"===this._type?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):"radial"===this._type&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const t of this._colorStops)e.addColorStop(t[0],t[1]);return e}getPattern(t,e,s,i){let n;if(i===De||i===Re){const a=e.current.getClippedPathBoundingBox(i,ne(t))||[0,0,0,0],r=Math.ceil(a[2]-a[0])||1,o=Math.ceil(a[3]-a[1])||1,h=e.cachedCanvases.getCanvas("pattern",r,o,!0),l=h.context;l.clearRect(0,0,l.canvas.width,l.canvas.height),l.beginPath(),l.rect(0,0,l.canvas.width,l.canvas.height),l.translate(-a[0],-a[1]),s=At.transform(s,[1,0,0,1,a[0],a[1]]),l.transform(...e.baseTransform),this.matrix&&l.transform(...this.matrix),Fe(l,this._bbox),l.fillStyle=this._createGradient(l),l.fill(),n=t.createPattern(h.canvas,"no-repeat");const d=new DOMMatrix(s);n.setTransform(d)}else Fe(t,this._bbox),n=this._createGradient(t);return n}}function Be(t,e,s,i,n,a,r,o){const h=e.coords,l=e.colors,d=t.data,c=4*t.width;let u;h[s+1]>h[i+1]&&(u=s,s=i,i=u,u=a,a=r,r=u),h[i+1]>h[n+1]&&(u=i,i=n,n=u,u=r,r=o,o=u),h[s+1]>h[i+1]&&(u=s,s=i,i=u,u=a,a=r,r=u);const p=(h[s]+e.offsetX)*e.scaleX,g=(h[s+1]+e.offsetY)*e.scaleY,m=(h[i]+e.offsetX)*e.scaleX,f=(h[i+1]+e.offsetY)*e.scaleY,b=(h[n]+e.offsetX)*e.scaleX,v=(h[n+1]+e.offsetY)*e.scaleY;if(g>=v)return;const A=l[a],y=l[a+1],w=l[a+2],_=l[r],x=l[r+1],E=l[r+2],C=l[o],S=l[o+1],T=l[o+2],M=Math.round(g),k=Math.round(v);let P,I,R,D,L,F,O,N;for(let t=M;t<=k;t++){if(t<f){const e=t<g?0:(g-t)/(g-f);P=p-(p-m)*e,I=A-(A-_)*e,R=y-(y-x)*e,D=w-(w-E)*e}else{let e;e=t>v?1:f===v?0:(f-t)/(f-v),P=m-(m-b)*e,I=_-(_-C)*e,R=x-(x-S)*e,D=E-(E-T)*e}let e;e=t<g?0:t>v?1:(g-t)/(g-v),L=p-(p-b)*e,F=A-(A-C)*e,O=y-(y-S)*e,N=w-(w-T)*e;const s=Math.round(Math.min(P,L)),i=Math.round(Math.max(P,L));let n=c*t+4*s;for(let t=s;t<=i;t++)e=(P-t)/(P-L),e<0?e=0:e>1&&(e=1),d[n++]=I-(I-F)*e|0,d[n++]=R-(R-O)*e|0,d[n++]=D-(D-N)*e|0,d[n++]=255}}function He(t,e,s){const i=e.coords,n=e.colors;let a,r;switch(e.type){case"lattice":const o=e.verticesPerRow,h=Math.floor(i.length/o)-1,l=o-1;for(a=0;a<h;a++){let e=a*o;for(let a=0;a<l;a++,e++)Be(t,s,i[e],i[e+1],i[e+o],n[e],n[e+1],n[e+o]),Be(t,s,i[e+o+1],i[e+1],i[e+o],n[e+o+1],n[e+1],n[e+o])}break;case"triangles":for(a=0,r=i.length;a<r;a+=3)Be(t,s,i[a],i[a+1],i[a+2],n[a],n[a+1],n[a+2]);break;default:throw new Error("illegal figure")}}class ze extends Oe{constructor(t){super(),this._coords=t[2],this._colors=t[3],this._figures=t[4],this._bounds=t[5],this._bbox=t[7],this._background=t[8],this.matrix=null}_createMeshCanvas(t,e,s){const i=Math.floor(this._bounds[0]),n=Math.floor(this._bounds[1]),a=Math.ceil(this._bounds[2])-i,r=Math.ceil(this._bounds[3])-n,o=Math.min(Math.ceil(Math.abs(a*t[0]*1.1)),3e3),h=Math.min(Math.ceil(Math.abs(r*t[1]*1.1)),3e3),l=a/o,d=r/h,c={coords:this._coords,colors:this._colors,offsetX:-i,offsetY:-n,scaleX:1/l,scaleY:1/d},u=o+4,p=h+4,g=s.getCanvas("mesh",u,p,!1),m=g.context,f=m.createImageData(o,h);if(e){const t=f.data;for(let s=0,i=t.length;s<i;s+=4)t[s]=e[0],t[s+1]=e[1],t[s+2]=e[2],t[s+3]=255}for(const t of this._figures)He(f,t,c);m.putImageData(f,2,2);return{canvas:g.canvas,offsetX:i-2*l,offsetY:n-2*d,scaleX:l,scaleY:d}}getPattern(t,e,s,i){let n;if(Fe(t,this._bbox),i===Le)n=At.singularValueDecompose2dScale(ne(t));else if(n=At.singularValueDecompose2dScale(e.baseTransform),this.matrix){const t=At.singularValueDecompose2dScale(this.matrix);n=[n[0]*t[0],n[1]*t[1]]}const a=this._createMeshCanvas(n,i===Le?null:this._background,e.cachedCanvases);return i!==Le&&(t.setTransform(...e.baseTransform),this.matrix&&t.transform(...this.matrix)),t.translate(a.offsetX,a.offsetY),t.scale(a.scaleX,a.scaleY),t.createPattern(a.canvas,"no-repeat")}}class je extends Oe{getPattern(){return"hotpink"}}const Ue=1,$e=2;class Ve{static MAX_PATTERN_SIZE=3e3;constructor(t,e,s,i,n){this.operatorList=t[2],this.matrix=t[3],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.color=e,this.ctx=s,this.canvasGraphicsFactory=i,this.baseTransform=n}createPatternCanvas(t){const e=this.operatorList,s=this.bbox,i=this.xstep,n=this.ystep,a=this.paintType,r=this.tilingType,o=this.color,h=this.canvasGraphicsFactory;tt("TilingType: "+r);const l=s[0],d=s[1],c=s[2],u=s[3],p=At.singularValueDecompose2dScale(this.matrix),g=At.singularValueDecompose2dScale(this.baseTransform),m=[p[0]*g[0],p[1]*g[1]],f=this.getSizeAndScale(i,this.ctx.canvas.width,m[0]),b=this.getSizeAndScale(n,this.ctx.canvas.height,m[1]),v=t.cachedCanvases.getCanvas("pattern",f.size,b.size,!0),A=v.context,y=h.createCanvasGraphics(A);y.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(y,a,o);let w=l,_=d,x=c,E=u;return l<0&&(w=0,x+=Math.abs(l)),d<0&&(_=0,E+=Math.abs(d)),A.translate(-f.scale*w,-b.scale*_),y.transform(f.scale,0,0,b.scale,0,0),A.save(),this.clipBbox(y,w,_,x,E),y.baseTransform=ne(y.ctx),y.executeOperatorList(e),y.endDrawing(),{canvas:v.canvas,scaleX:f.scale,scaleY:b.scale,offsetX:w,offsetY:_}}getSizeAndScale(t,e,s){t=Math.abs(t);const i=Math.max(Ve.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*s);return n>=i?n=i:s=n/t,{scale:s,size:n}}clipBbox(t,e,s,i,n){const a=i-e,r=n-s;t.ctx.rect(e,s,a,r),t.current.updateRectMinMax(ne(t.ctx),[e,s,i,n]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(e){case Ue:const t=this.ctx;i.fillStyle=t.fillStyle,i.strokeStyle=t.strokeStyle,n.fillColor=t.fillStyle,n.strokeColor=t.strokeStyle;break;case $e:const a=At.makeHexColor(s[0],s[1],s[2]);i.fillStyle=a,i.strokeStyle=a,n.fillColor=a,n.strokeColor=a;break;default:throw new ut(`Unsupported paint type: ${e}`)}}getPattern(t,e,s,i){let n=s;i!==Le&&(n=At.transform(n,e.baseTransform),this.matrix&&(n=At.transform(n,this.matrix)));const a=this.createPatternCanvas(e);let r=new DOMMatrix(n);r=r.translate(a.offsetX,a.offsetY),r=r.scale(1/a.scaleX,1/a.scaleY);const o=t.createPattern(a.canvas,"repeat");return o.setTransform(r),o}}function Ge({src:t,srcPos:e=0,dest:s,width:i,height:n,nonBlackColor:a=4294967295,inverseDecode:r=!1}){const o=bt.isLittleEndian?4278190080:255,[h,l]=r?[a,o]:[o,a],d=i>>3,c=7&i,u=t.length;s=new Uint32Array(s.buffer);let p=0;for(let i=0;i<n;i++){for(const i=e+d;e<i;e++){const i=e<u?t[e]:255;s[p++]=128&i?l:h,s[p++]=64&i?l:h,s[p++]=32&i?l:h,s[p++]=16&i?l:h,s[p++]=8&i?l:h,s[p++]=4&i?l:h,s[p++]=2&i?l:h,s[p++]=1&i?l:h}if(0===c)continue;const i=e<u?t[e++]:255;for(let t=0;t<c;t++)s[p++]=i&1<<7-t?l:h}return{srcPos:e,destPos:p}}const We=16;class qe{constructor(t){this.canvasFactory=t,this.cache=Object.create(null)}getCanvas(t,e,s){let i;return void 0!==this.cache[t]?(i=this.cache[t],this.canvasFactory.reset(i,e,s)):(i=this.canvasFactory.create(e,s),this.cache[t]=i),i}delete(t){delete this.cache[t]}clear(){for(const t in this.cache){const e=this.cache[t];this.canvasFactory.destroy(e),delete this.cache[t]}}}function Xe(t,e,s,i,n,a,r,o,h,l){const[d,c,u,p,g,m]=ne(t);if(0===c&&0===u){const f=r*d+g,b=Math.round(f),v=o*p+m,A=Math.round(v),y=(r+h)*d+g,w=Math.abs(Math.round(y)-b)||1,_=(o+l)*p+m,x=Math.abs(Math.round(_)-A)||1;return t.setTransform(Math.sign(d),0,0,Math.sign(p),b,A),t.drawImage(e,s,i,n,a,0,0,w,x),t.setTransform(d,c,u,p,g,m),[w,x]}if(0===d&&0===p){const f=o*u+g,b=Math.round(f),v=r*c+m,A=Math.round(v),y=(o+l)*u+g,w=Math.abs(Math.round(y)-b)||1,_=(r+h)*c+m,x=Math.abs(Math.round(_)-A)||1;return t.setTransform(0,Math.sign(c),Math.sign(u),0,b,A),t.drawImage(e,s,i,n,a,0,0,x,w),t.setTransform(d,c,u,p,g,m),[x,w]}t.drawImage(e,s,i,n,a,r,o,h,l);return[Math.hypot(d,c)*h,Math.hypot(u,p)*l]}class Ke{constructor(t,e){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=i,this.textMatrixScale=1,this.fontMatrix=n,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=b,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps="none",this.startNewPathAndClipBox([0,0,t,e])}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t}setCurrentPoint(t,e){this.x=t,this.y=e}updatePathMinMax(t,e,s){[e,s]=At.applyTransform([e,s],t),this.minX=Math.min(this.minX,e),this.minY=Math.min(this.minY,s),this.maxX=Math.max(this.maxX,e),this.maxY=Math.max(this.maxY,s)}updateRectMinMax(t,e){const s=At.applyTransform(e,t),i=At.applyTransform(e.slice(2),t),n=At.applyTransform([e[0],e[3]],t),a=At.applyTransform([e[2],e[1]],t);this.minX=Math.min(this.minX,s[0],i[0],n[0],a[0]),this.minY=Math.min(this.minY,s[1],i[1],n[1],a[1]),this.maxX=Math.max(this.maxX,s[0],i[0],n[0],a[0]),this.maxY=Math.max(this.maxY,s[1],i[1],n[1],a[1])}updateScalingPathMinMax(t,e){At.scaleMinMax(t,e),this.minX=Math.min(this.minX,e[0]),this.minY=Math.min(this.minY,e[1]),this.maxX=Math.max(this.maxX,e[2]),this.maxY=Math.max(this.maxY,e[3])}updateCurvePathMinMax(t,e,s,i,n,a,r,o,h,l){const d=At.bezierBoundingBox(e,s,i,n,a,r,o,h,l);l||this.updateRectMinMax(t,d)}getPathBoundingBox(t=Re,e=null){const s=[this.minX,this.minY,this.maxX,this.maxY];if(t===De){e||st("Stroke bounding box must include transform.");const t=At.singularValueDecompose2dScale(e),i=t[0]*this.lineWidth/2,n=t[1]*this.lineWidth/2;s[0]-=i,s[1]-=n,s[2]+=i,s[3]+=n}return s}updateClipFromPath(){const t=At.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(t){this.clipBox=t,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(t=Re,e=null){return At.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function Ye(t,e){if("undefined"!=typeof ImageData&&e instanceof ImageData)return void t.putImageData(e,0,0);const s=e.height,i=e.width,n=s%We,a=(s-n)/We,r=0===n?a:a+1,o=t.createImageData(i,We);let h,l=0;const d=e.data,c=o.data;let u,p,g,m;if(e.kind===x.GRAYSCALE_1BPP){const e=d.byteLength,s=new Uint32Array(c.buffer,0,c.byteLength>>2),m=s.length,f=i+7>>3,b=4294967295,v=bt.isLittleEndian?4278190080:255;for(u=0;u<r;u++){for(g=u<a?We:n,h=0,p=0;p<g;p++){const t=e-l;let n=0;const a=t>f?i:8*t-7,r=-8&a;let o=0,c=0;for(;n<r;n+=8)c=d[l++],s[h++]=128&c?b:v,s[h++]=64&c?b:v,s[h++]=32&c?b:v,s[h++]=16&c?b:v,s[h++]=8&c?b:v,s[h++]=4&c?b:v,s[h++]=2&c?b:v,s[h++]=1&c?b:v;for(;n<a;n++)0===o&&(c=d[l++],o=128),s[h++]=c&o?b:v,o>>=1}for(;h<m;)s[h++]=0;t.putImageData(o,0,u*We)}}else if(e.kind===x.RGBA_32BPP){for(p=0,m=i*We*4,u=0;u<a;u++)c.set(d.subarray(l,l+m)),l+=m,t.putImageData(o,0,p),p+=We;u<r&&(m=i*n*4,c.set(d.subarray(l,l+m)),t.putImageData(o,0,p))}else{if(e.kind!==x.RGB_24BPP)throw new Error(`bad image kind: ${e.kind}`);for(g=We,m=i*g,u=0;u<r;u++){for(u>=a&&(g=n,m=i*g),h=0,p=m;p--;)c[h++]=d[l++],c[h++]=d[l++],c[h++]=d[l++],c[h++]=255;t.putImageData(o,0,u*We)}}}function Qe(t,e){if(e.bitmap)return void t.drawImage(e.bitmap,0,0);const s=e.height,i=e.width,n=s%We,a=(s-n)/We,r=0===n?a:a+1,o=t.createImageData(i,We);let h=0;const l=e.data,d=o.data;for(let e=0;e<r;e++){const s=e<a?We:n;({srcPos:h}=Ge({src:l,srcPos:h,dest:d,width:i,height:s,nonBlackColor:0})),t.putImageData(o,0,e*We)}}function Je(t,e){const s=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const i of s)void 0!==t[i]&&(e[i]=t[i]);void 0!==t.setLineDash&&(e.setLineDash(t.getLineDash()),e.lineDashOffset=t.lineDashOffset)}function Ze(t){if(t.strokeStyle=t.fillStyle="#000000",t.fillRule="nonzero",t.globalAlpha=1,t.lineWidth=1,t.lineCap="butt",t.lineJoin="miter",t.miterLimit=10,t.globalCompositeOperation="source-over",t.font="10px sans-serif",void 0!==t.setLineDash&&(t.setLineDash([]),t.lineDashOffset=0),!s){const{filter:e}=t;"none"!==e&&""!==e&&(t.filter="none")}}function ts(t,e){if(e)return!0;const s=At.singularValueDecompose2dScale(t);s[0]=Math.fround(s[0]),s[1]=Math.fround(s[1]);const i=Math.fround((globalThis.devicePixelRatio||1)*Ht.PDF_TO_CSS_UNITS);return s[0]<=i&&s[1]<=i}const es=["butt","round","square"],ss=["miter","round","bevel"],is={},ns={};class as{constructor(t,e,s,i,n,{optionalContentConfig:a,markedContentStack:r=null},o,h){this.ctx=t,this.current=new Ke(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=e,this.objs=s,this.canvasFactory=i,this.filterFactory=n,this.groupStack=[],this.processingType3=null,this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=r||[],this.optionalContentConfig=a,this.cachedCanvases=new qe(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=o,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=h,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(t,e=null){return"string"==typeof t?t.startsWith("g_")?this.commonObjs.get(t):this.objs.get(t):e}beginDrawing({transform:t,viewport:e,transparency:s=!1,background:i=null}){const n=this.ctx.canvas.width,a=this.ctx.canvas.height,r=this.ctx.fillStyle;if(this.ctx.fillStyle=i||"#ffffff",this.ctx.fillRect(0,0,n,a),this.ctx.fillStyle=r,s){const t=this.cachedCanvases.getCanvas("transparent",n,a);this.compositeCtx=this.ctx,this.transparentCanvas=t.canvas,this.ctx=t.context,this.ctx.save(),this.ctx.transform(...ne(this.compositeCtx))}this.ctx.save(),Ze(this.ctx),t&&(this.ctx.transform(...t),this.outputScaleX=t[0],this.outputScaleY=t[0]),this.ctx.transform(...e.transform),this.viewportScale=e.scale,this.baseTransform=ne(this.ctx)}executeOperatorList(t,e,s,i){const n=t.argsArray,a=t.fnArray;let r=e||0;const o=n.length;if(o===r)return r;const h=o-r>10&&"function"==typeof s,l=h?Date.now()+15:0;let d=0;const c=this.commonObjs,u=this.objs;let p;for(;;){if(void 0!==i&&r===i.nextBreakPoint)return i.breakIt(r,s),r;if(p=a[r],p!==K.dependency)this[p].apply(this,n[r]);else for(const t of n[r]){const e=t.startsWith("g_")?c:u;if(!e.has(t))return e.get(t,s),r}if(r++,r===o)return r;if(h&&++d>10){if(Date.now()>l)return s(),r;d=0}}}#Ie(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)}endDrawing(){this.#Ie(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear(),this.#Re()}#Re(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}}_scaleImage(t,e){const s=t.width,i=t.height;let n,a,r=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),h=s,l=i,d="prescale1";for(;r>2&&h>1||o>2&&l>1;){let e=h,s=l;r>2&&h>1&&(e=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h/2),r/=h/e),o>2&&l>1&&(s=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l)/2,o/=l/s),n=this.cachedCanvases.getCanvas(d,e,s),a=n.context,a.clearRect(0,0,e,s),a.drawImage(t,0,0,h,l,0,0,e,s),t=n.canvas,h=e,l=s,d="prescale1"===d?"prescale2":"prescale1"}return{img:t,paintWidth:h,paintHeight:l}}_createMaskCanvas(t){const e=this.ctx,{width:s,height:i}=t,n=this.current.fillColor,a=this.current.patternFill,r=ne(e);let o,h,l,d;if((t.bitmap||t.data)&&t.count>1){const e=t.bitmap||t.data.buffer;h=JSON.stringify(a?r:[r.slice(0,4),n]),o=this._cachedBitmapsMap.get(e),o||(o=new Map,this._cachedBitmapsMap.set(e,o));const s=o.get(h);if(s&&!a){return{canvas:s,offsetX:Math.round(Math.min(r[0],r[2])+r[4]),offsetY:Math.round(Math.min(r[1],r[3])+r[5])}}l=s}l||(d=this.cachedCanvases.getCanvas("maskCanvas",s,i),Qe(d.context,t));let c=At.transform(r,[1/s,0,0,-1/i,0,0]);c=At.transform(c,[1,0,0,1,0,-i]);const[u,p,g,m]=At.getAxialAlignedBoundingBox([0,0,s,i],c),f=Math.round(g-u)||1,b=Math.round(m-p)||1,v=this.cachedCanvases.getCanvas("fillCanvas",f,b),A=v.context,y=u,w=p;A.translate(-y,-w),A.transform(...c),l||(l=this._scaleImage(d.canvas,ae(A)),l=l.img,o&&a&&o.set(h,l)),A.imageSmoothingEnabled=ts(ne(A),t.interpolate),Xe(A,l,0,0,l.width,l.height,0,0,s,i),A.globalCompositeOperation="source-in";const _=At.transform(ae(A),[1,0,0,1,-y,-w]);return A.fillStyle=a?n.getPattern(e,this,_,Re):n,A.fillRect(0,0,s,i),o&&!a&&(this.cachedCanvases.delete("fillCanvas"),o.set(h,v.canvas)),{canvas:v.canvas,offsetX:Math.round(y),offsetY:Math.round(w)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=es[t]}setLineJoin(t){this.ctx.lineJoin=ss[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const s=this.ctx;void 0!==s.setLineDash&&(s.setLineDash(t),s.lineDashOffset=e)}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,s]of t)switch(e){case"LW":this.setLineWidth(s);break;case"LC":this.setLineCap(s);break;case"LJ":this.setLineJoin(s);break;case"ML":this.setMiterLimit(s);break;case"D":this.setDash(s[0],s[1]);break;case"RI":this.setRenderingIntent(s);break;case"FL":this.setFlatness(s);break;case"Font":this.setFont(s[0],s[1]);break;case"CA":this.current.strokeAlpha=s;break;case"ca":this.current.fillAlpha=s,this.ctx.globalAlpha=s;break;case"BM":this.ctx.globalCompositeOperation=s;break;case"SMask":this.current.activeSMask=s?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(s)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,s="smaskGroupAt"+this.groupLevel,i=this.cachedCanvases.getCanvas(s,t,e);this.suspendedCtx=this.ctx,this.ctx=i.context;const n=this.ctx;n.setTransform(...ne(this.suspendedCtx)),Je(this.suspendedCtx,n),function(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");t.__originalSave=t.save,t.__originalRestore=t.restore,t.__originalRotate=t.rotate,t.__originalScale=t.scale,t.__originalTranslate=t.translate,t.__originalTransform=t.transform,t.__originalSetTransform=t.setTransform,t.__originalResetTransform=t.resetTransform,t.__originalClip=t.clip,t.__originalMoveTo=t.moveTo,t.__originalLineTo=t.lineTo,t.__originalBezierCurveTo=t.bezierCurveTo,t.__originalRect=t.rect,t.__originalClosePath=t.closePath,t.__originalBeginPath=t.beginPath,t._removeMirroring=()=>{t.save=t.__originalSave,t.restore=t.__originalRestore,t.rotate=t.__originalRotate,t.scale=t.__originalScale,t.translate=t.__originalTranslate,t.transform=t.__originalTransform,t.setTransform=t.__originalSetTransform,t.resetTransform=t.__originalResetTransform,t.clip=t.__originalClip,t.moveTo=t.__originalMoveTo,t.lineTo=t.__originalLineTo,t.bezierCurveTo=t.__originalBezierCurveTo,t.rect=t.__originalRect,t.closePath=t.__originalClosePath,t.beginPath=t.__originalBeginPath,delete t._removeMirroring},t.save=function(){e.save(),this.__originalSave()},t.restore=function(){e.restore(),this.__originalRestore()},t.translate=function(t,s){e.translate(t,s),this.__originalTranslate(t,s)},t.scale=function(t,s){e.scale(t,s),this.__originalScale(t,s)},t.transform=function(t,s,i,n,a,r){e.transform(t,s,i,n,a,r),this.__originalTransform(t,s,i,n,a,r)},t.setTransform=function(t,s,i,n,a,r){e.setTransform(t,s,i,n,a,r),this.__originalSetTransform(t,s,i,n,a,r)},t.resetTransform=function(){e.resetTransform(),this.__originalResetTransform()},t.rotate=function(t){e.rotate(t),this.__originalRotate(t)},t.clip=function(t){e.clip(t),this.__originalClip(t)},t.moveTo=function(t,s){e.moveTo(t,s),this.__originalMoveTo(t,s)},t.lineTo=function(t,s){e.lineTo(t,s),this.__originalLineTo(t,s)},t.bezierCurveTo=function(t,s,i,n,a,r){e.bezierCurveTo(t,s,i,n,a,r),this.__originalBezierCurveTo(t,s,i,n,a,r)},t.rect=function(t,s,i,n){e.rect(t,s,i,n),this.__originalRect(t,s,i,n)},t.closePath=function(){e.closePath(),this.__originalClosePath()},t.beginPath=function(){e.beginPath(),this.__originalBeginPath()}}(n,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),Je(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,s=this.suspendedCtx;this.composeSMask(s,e,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,e,s,i){const n=i[0],a=i[1],r=i[2]-n,o=i[3]-a;0!==r&&0!==o&&(this.genericComposeSMask(e.context,s,r,o,e.subtype,e.backdrop,e.transferMap,n,a,e.offsetX,e.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(s.canvas,0,0),t.restore())}genericComposeSMask(t,e,s,i,n,a,r,o,h,l,d){let c=t.canvas,u=o-l,p=h-d;if(a)if(u<0||p<0||u+s>c.width||p+i>c.height){const t=this.cachedCanvases.getCanvas("maskExtension",s,i),e=t.context;e.drawImage(c,-u,-p),a.some(t=>0!==t)&&(e.globalCompositeOperation="destination-atop",e.fillStyle=At.makeHexColor(...a),e.fillRect(0,0,s,i),e.globalCompositeOperation="source-over"),c=t.canvas,u=p=0}else if(a.some(t=>0!==t)){t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const e=new Path2D;e.rect(u,p,s,i),t.clip(e),t.globalCompositeOperation="destination-atop",t.fillStyle=At.makeHexColor(...a),t.fillRect(u,p,s,i),t.restore()}e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0),"Alpha"===n&&r?e.filter=this.filterFactory.addAlphaFilter(r):"Luminosity"===n&&(e.filter=this.filterFactory.addLuminosityFilter(r));const g=new Path2D;g.rect(o,h,s,i),e.clip(g),e.globalCompositeOperation="destination-in",e.drawImage(c,u,p,s,i,o,h,s,i),e.restore()}save(){this.inSMaskMode?(Je(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();const t=this.current;this.stateStack.push(t),this.current=t.clone()}restore(){0===this.stateStack.length&&this.inSMaskMode&&this.endSMaskMode(),0!==this.stateStack.length&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),Je(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(t,e,s,i,n,a){this.ctx.transform(t,e,s,i,n,a),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,s){const i=this.ctx,n=this.current;let a,r,o=n.x,h=n.y;const l=ne(i),d=0===l[0]&&0===l[3]||0===l[1]&&0===l[2],c=d?s.slice(0):null;for(let s=0,u=0,p=t.length;s<p;s++)switch(0|t[s]){case K.rectangle:o=e[u++],h=e[u++];const t=e[u++],s=e[u++],p=o+t,g=h+s;i.moveTo(o,h),0===t||0===s?i.lineTo(p,g):(i.lineTo(p,h),i.lineTo(p,g),i.lineTo(o,g)),d||n.updateRectMinMax(l,[o,h,p,g]),i.closePath();break;case K.moveTo:o=e[u++],h=e[u++],i.moveTo(o,h),d||n.updatePathMinMax(l,o,h);break;case K.lineTo:o=e[u++],h=e[u++],i.lineTo(o,h),d||n.updatePathMinMax(l,o,h);break;case K.curveTo:a=o,r=h,o=e[u+4],h=e[u+5],i.bezierCurveTo(e[u],e[u+1],e[u+2],e[u+3],o,h),n.updateCurvePathMinMax(l,a,r,e[u],e[u+1],e[u+2],e[u+3],o,h,c),u+=6;break;case K.curveTo2:a=o,r=h,i.bezierCurveTo(o,h,e[u],e[u+1],e[u+2],e[u+3]),n.updateCurvePathMinMax(l,a,r,o,h,e[u],e[u+1],e[u+2],e[u+3],c),o=e[u+2],h=e[u+3],u+=4;break;case K.curveTo3:a=o,r=h,o=e[u+2],h=e[u+3],i.bezierCurveTo(e[u],e[u+1],o,h,o,h),n.updateCurvePathMinMax(l,a,r,e[u],e[u+1],o,h,o,h,c),u+=4;break;case K.closePath:i.closePath()}d&&n.updateScalingPathMinMax(l,c),n.setCurrentPoint(o,h)}closePath(){this.ctx.closePath()}stroke(t=!0){const e=this.ctx,s=this.current.strokeColor;e.globalAlpha=this.current.strokeAlpha,this.contentVisible&&("object"==typeof s&&s?.getPattern?(e.save(),e.strokeStyle=s.getPattern(e,this,ae(e),De),this.rescaleAndStroke(!1),e.restore()):this.rescaleAndStroke(!0)),t&&this.consumePath(this.current.getClippedPathBoundingBox()),e.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(t=!0){const e=this.ctx,s=this.current.fillColor;let i=!1;this.current.patternFill&&(e.save(),e.fillStyle=s.getPattern(e,this,ae(e),Re),i=!0);const n=this.current.getClippedPathBoundingBox();this.contentVisible&&null!==n&&(this.pendingEOFill?(e.fill("evenodd"),this.pendingEOFill=!1):e.fill()),i&&e.restore(),t&&this.consumePath(n)}eoFill(){this.pendingEOFill=!0,this.fill()}fillStroke(){this.fill(!1),this.stroke(!1),this.consumePath()}eoFillStroke(){this.pendingEOFill=!0,this.fillStroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()}endPath(){this.consumePath()}clip(){this.pendingClip=is}eoClip(){this.pendingClip=ns}beginText(){this.current.textMatrix=i,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}endText(){const t=this.pendingTextPaths,e=this.ctx;if(void 0!==t){e.save(),e.beginPath();for(const s of t)e.setTransform(...s.transform),e.translate(s.x,s.y),s.addToPath(e,s.fontSize);e.restore(),e.clip(),e.beginPath(),delete this.pendingTextPaths}else e.beginPath()}setCharSpacing(t){this.current.charSpacing=t}setWordSpacing(t){this.current.wordSpacing=t}setHScale(t){this.current.textHScale=t/100}setLeading(t){this.current.leading=-t}setFont(t,e){const s=this.commonObjs.get(t),i=this.current;if(!s)throw new Error(`Can't find font for ${t}`);if(i.fontMatrix=s.fontMatrix||n,0!==i.fontMatrix[0]&&0!==i.fontMatrix[3]||et("Invalid font matrix for font "+t),e<0?(e=-e,i.fontDirection=-1):i.fontDirection=1,this.current.font=s,this.current.fontSize=e,s.isType3Font)return;const a=s.loadedName||"sans-serif",r=s.systemFontInfo?.css||`"${a}", ${s.fallbackName}`;let o="normal";s.black?o="900":s.bold&&(o="bold");const h=s.italic?"italic":"normal";let l=e;e<16?l=16:e>100&&(l=100),this.current.fontSizeScale=e/l,this.ctx.font=`${h} ${o} ${l}px ${r}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e),this.moveText(t,e)}setTextMatrix(t,e,s,i,n,a){this.current.textMatrix=[t,e,s,i,n,a],this.current.textMatrixScale=Math.hypot(t,e),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(t,e,s,i){const n=this.ctx,a=this.current,r=a.font,o=a.textRenderingMode,h=a.fontSize/a.fontSizeScale,l=o&w,d=!!(o&_),c=a.patternFill&&!r.missingFile;let u;if((r.disableFontFace||d||c)&&(u=r.getPathGenerator(this.commonObjs,t)),r.disableFontFace||c?(n.save(),n.translate(e,s),n.beginPath(),u(n,h),i&&n.setTransform(...i),l!==b&&l!==A||n.fill(),l!==v&&l!==A||n.stroke(),n.restore()):(l!==b&&l!==A||n.fillText(t,e,s),l!==v&&l!==A||n.strokeText(t,e,s)),d){(this.pendingTextPaths||=[]).push({transform:ne(n),x:e,y:s,fontSize:h,addToPath:u})}}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let s=!1;for(let t=3;t<e.length;t+=4)if(e[t]>0&&e[t]<255){s=!0;break}return at(this,"isFontSubpixelAAEnabled",s)}showText(t){const e=this.current,s=e.font;if(s.isType3Font)return this.showType3Text(t);const i=e.fontSize;if(0===i)return;const n=this.ctx,a=e.fontSizeScale,r=e.charSpacing,o=e.wordSpacing,h=e.fontDirection,l=e.textHScale*h,d=t.length,c=s.vertical,u=c?1:-1,p=s.defaultVMetrics,g=i*e.fontMatrix[0],m=e.textRenderingMode===b&&!s.disableFontFace&&!e.patternFill;let f;if(n.save(),n.transform(...e.textMatrix),n.translate(e.x,e.y+e.textRise),h>0?n.scale(l,-1):n.scale(l,1),e.patternFill){n.save();const t=e.fillColor.getPattern(n,this,ae(n),Re);f=ne(n),n.restore(),n.fillStyle=t}let y=e.lineWidth;const _=e.textMatrixScale;if(0===_||0===y){const t=e.textRenderingMode&w;t!==v&&t!==A||(y=this.getSinglePixelWidth())}else y/=_;if(1!==a&&(n.scale(a,a),y/=a),n.lineWidth=y,s.isInvalidPDFjsFont){const s=[];let i=0;for(const e of t)s.push(e.unicode),i+=e.width;return n.fillText(s.join(""),0,0),e.x+=i*g*l,n.restore(),void this.compose()}let x,E=0;for(x=0;x<d;++x){const e=t[x];if("number"==typeof e){E+=u*e*i/1e3;continue}let l=!1;const d=(e.isSpace?o:0)+r,b=e.fontChar,v=e.accent;let A,y,w=e.width;if(c){const t=e.vmetric||p,s=-(e.vmetric?t[1]:.5*w)*g,i=t[2]*g;w=t?-t[0]:w,A=s/a,y=(E+i)/a}else A=E/a,y=0;if(s.remeasure&&w>0){const t=1e3*n.measureText(b).width/i*a;if(w<t&&this.isFontSubpixelAAEnabled){const e=w/t;l=!0,n.save(),n.scale(e,1),A/=e}else w!==t&&(A+=(w-t)/2e3*i/a)}if(this.contentVisible&&(e.isInFont||s.missingFile))if(m&&!v)n.fillText(b,A,y);else if(this.paintChar(b,A,y,f),v){const t=A+i*v.offset.x/a,e=y-i*v.offset.y/a;this.paintChar(v.fontChar,t,e,f)}E+=c?w*g-d*h:w*g+d*h,l&&n.restore()}c?e.y-=E:e.x+=E*l,n.restore(),this.compose()}showType3Text(t){const e=this.ctx,s=this.current,i=s.font,a=s.fontSize,r=s.fontDirection,o=i.vertical?1:-1,h=s.charSpacing,l=s.wordSpacing,d=s.textHScale*r,c=s.fontMatrix||n,u=t.length;let p,g,m,f;if(!(s.textRenderingMode===y)&&0!==a){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,e.save(),e.transform(...s.textMatrix),e.translate(s.x,s.y),e.scale(d,r),p=0;p<u;++p){if(g=t[p],"number"==typeof g){f=o*g*a/1e3,this.ctx.translate(f,0),s.x+=f*d;continue}const n=(g.isSpace?l:0)+h,r=i.charProcOperatorList[g.operatorListId];if(!r){et(`Type3 character "${g.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=g,this.save(),e.scale(a,a),e.transform(...c),this.executeOperatorList(r),this.restore());m=At.applyTransform([g.width,0],c)[0]*a+n,e.translate(m,0),s.x+=m*d}e.restore(),this.processingType3=null}}setCharWidth(t,e){}setCharWidthAndBounds(t,e,s,i,n,a){this.ctx.rect(s,i,n-s,a-i),this.ctx.clip(),this.endPath()}getColorN_Pattern(t){let e;if("TilingPattern"===t[0]){const s=t[1],i=this.baseTransform||ne(this.ctx),n={createCanvasGraphics:t=>new as(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new Ve(t,s,this.ctx,n,i)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(t,e,s){const i=At.makeHexColor(t,e,s);this.ctx.strokeStyle=i,this.current.strokeColor=i}setFillRGBColor(t,e,s){const i=At.makeHexColor(t,e,s);this.ctx.fillStyle=i,this.current.fillColor=i,this.current.patternFill=!1}_getPattern(t,e=null){let s;return this.cachedPatterns.has(t)?s=this.cachedPatterns.get(t):(s=function(t){switch(t[0]){case"RadialAxial":return new Ne(t);case"Mesh":return new ze(t);case"Dummy":return new je}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t)),this.cachedPatterns.set(t,s)),e&&(s.matrix=e),s}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const s=this._getPattern(t);e.fillStyle=s.getPattern(e,this,ae(e),Le);const i=ae(e);if(i){const{width:t,height:s}=e.canvas,[n,a,r,o]=At.getAxialAlignedBoundingBox([0,0,t,s],i);this.ctx.fillRect(n,a,r-n,o-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){st("Should not call beginInlineImage")}beginImageData(){st("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=ne(this.ctx),e)){const t=e[2]-e[0],s=e[3]-e[1];this.ctx.rect(e[0],e[1],t,s),this.current.updateRectMinMax(ne(this.ctx),e),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const e=this.ctx;t.isolated||tt("TODO: Support non-isolated groups."),t.knockout&&et("Knockout groups not supported.");const s=ne(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let i=At.getAxialAlignedBoundingBox(t.bbox,ne(e));const n=[0,0,e.canvas.width,e.canvas.height];i=At.intersect(i,n)||[0,0,0,0];const a=Math.floor(i[0]),r=Math.floor(i[1]),o=Math.max(Math.ceil(i[2])-a,1),h=Math.max(Math.ceil(i[3])-r,1);this.current.startNewPathAndClipBox([0,0,o,h]);let l="groupAt"+this.groupLevel;t.smask&&(l+="_smask_"+this.smaskCounter++%2);const d=this.cachedCanvases.getCanvas(l,o,h),c=d.context;c.translate(-a,-r),c.transform(...s),t.smask?this.smaskStack.push({canvas:d.canvas,context:c,offsetX:a,offsetY:r,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null}):(e.setTransform(1,0,0,1,0,0),e.translate(a,r),e.save()),Je(e,c),this.ctx=c,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(e),this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx,s=this.groupStack.pop();if(this.ctx=s,this.ctx.imageSmoothingEnabled=!1,t.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const t=ne(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...t);const s=At.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],t);this.ctx.drawImage(e.canvas,0,0),this.ctx.restore(),this.compose(s)}}beginAnnotation(t,e,s,i,n){if(this.#Ie(),Ze(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),e){const i=e[2]-e[0],a=e[3]-e[1];if(n&&this.annotationCanvasMap){(s=s.slice())[4]-=e[0],s[5]-=e[1],(e=e.slice())[0]=e[1]=0,e[2]=i,e[3]=a;const[n,r]=At.singularValueDecompose2dScale(ne(this.ctx)),{viewportScale:o}=this,h=Math.ceil(i*this.outputScaleX*o),l=Math.ceil(a*this.outputScaleY*o);this.annotationCanvas=this.canvasFactory.create(h,l);const{canvas:d,context:c}=this.annotationCanvas;this.annotationCanvasMap.set(t,d),this.annotationCanvas.savedCtx=this.ctx,this.ctx=c,this.ctx.save(),this.ctx.setTransform(n,0,0,-r,0,a*r),Ze(this.ctx)}else Ze(this.ctx),this.ctx.rect(e[0],e[1],i,a),this.ctx.clip(),this.endPath()}this.current=new Ke(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...s),this.transform(...i)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#Re(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(t){if(!this.contentVisible)return;const e=t.count;(t=this.getObject(t.data,t)).count=e;const s=this.ctx,i=this.processingType3;if(i&&(void 0===i.compiled&&(i.compiled=function(t){const{width:e,height:s}=t;if(e>1e3||s>1e3)return null;const i=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),n=e+1;let a,r,o,h=new Uint8Array(n*(s+1));const l=e+7&-8;let d=new Uint8Array(l*s),c=0;for(const e of t.data){let t=128;for(;t>0;)d[c++]=e&t?0:255,t>>=1}let u=0;for(c=0,0!==d[c]&&(h[0]=1,++u),r=1;r<e;r++)d[c]!==d[c+1]&&(h[r]=d[c]?2:1,++u),c++;for(0!==d[c]&&(h[r]=2,++u),a=1;a<s;a++){c=a*l,o=a*n,d[c-l]!==d[c]&&(h[o]=d[c]?1:8,++u);let t=(d[c]?4:0)+(d[c-l]?8:0);for(r=1;r<e;r++)t=(t>>2)+(d[c+1]?4:0)+(d[c-l+1]?8:0),i[t]&&(h[o+r]=i[t],++u),c++;if(d[c-l]!==d[c]&&(h[o+r]=d[c]?2:4,++u),u>1e3)return null}for(c=l*(s-1),o=a*n,0!==d[c]&&(h[o]=8,++u),r=1;r<e;r++)d[c]!==d[c+1]&&(h[o+r]=d[c]?4:8,++u),c++;if(0!==d[c]&&(h[o+r]=4,++u),u>1e3)return null;const p=new Int32Array([0,n,-1,0,-n,0,0,0,1]),g=new Path2D;for(a=0;u&&a<=s;a++){let t=a*n;const s=t+e;for(;t<s&&!h[t];)t++;if(t===s)continue;g.moveTo(t%n,a);const i=t;let r=h[t];do{const e=p[r];do{t+=e}while(!h[t]);const s=h[t];5!==s&&10!==s?(r=s,h[t]=0):(r=s&51*r>>4,h[t]&=r>>2|r<<2),g.lineTo(t%n,t/n|0),h[t]||--u}while(i!==t);--a}return d=null,h=null,function(t){t.save(),t.scale(1/e,-1/s),t.translate(0,-s),t.fill(g),t.beginPath(),t.restore()}}(t)),i.compiled))return void i.compiled(s);const n=this._createMaskCanvas(t),a=n.canvas;s.save(),s.setTransform(1,0,0,1,0,0),s.drawImage(a,n.offsetX,n.offsetY),s.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,s=0,i=0,n,a){if(!this.contentVisible)return;t=this.getObject(t.data,t);const r=this.ctx;r.save();const o=ne(r);r.transform(e,s,i,n,0,0);const h=this._createMaskCanvas(t);r.setTransform(1,0,0,1,h.offsetX-o[4],h.offsetY-o[5]);for(let t=0,l=a.length;t<l;t+=2){const l=At.transform(o,[e,s,i,n,a[t],a[t+1]]),[d,c]=At.applyTransform([0,0],l);r.drawImage(h.canvas,d,c)}r.restore(),this.compose()}paintImageMaskXObjectGroup(t){if(!this.contentVisible)return;const e=this.ctx,s=this.current.fillColor,i=this.current.patternFill;for(const n of t){const{data:t,width:a,height:r,transform:o}=n,h=this.cachedCanvases.getCanvas("maskCanvas",a,r),l=h.context;l.save();Qe(l,this.getObject(t,n)),l.globalCompositeOperation="source-in",l.fillStyle=i?s.getPattern(l,this,ae(e),Re):s,l.fillRect(0,0,a,r),l.restore(),e.save(),e.transform(...o),e.scale(1,-1),Xe(e,h.canvas,0,0,a,r,0,-1,1,1),e.restore()}this.compose()}paintImageXObject(t){if(!this.contentVisible)return;const e=this.getObject(t);e?this.paintInlineImageXObject(e):et("Dependent image isn't ready yet")}paintImageXObjectRepeat(t,e,s,i){if(!this.contentVisible)return;const n=this.getObject(t);if(!n)return void et("Dependent image isn't ready yet");const a=n.width,r=n.height,o=[];for(let t=0,n=i.length;t<n;t+=2)o.push({transform:[e,0,0,s,i[t],i[t+1]],x:0,y:0,w:a,h:r});this.paintInlineImageXObjectGroup(n,o)}applyTransferMapsToCanvas(t){return"none"!==this.current.transferMaps&&(t.filter=this.current.transferMaps,t.drawImage(t.canvas,0,0),t.filter="none"),t.canvas}applyTransferMapsToBitmap(t){if("none"===this.current.transferMaps)return t.bitmap;const{bitmap:e,width:s,height:i}=t,n=this.cachedCanvases.getCanvas("inlineImage",s,i),a=n.context;return a.filter=this.current.transferMaps,a.drawImage(e,0,0),a.filter="none",n.canvas}paintInlineImageXObject(t){if(!this.contentVisible)return;const e=t.width,i=t.height,n=this.ctx;if(this.save(),!s){const{filter:t}=n;"none"!==t&&""!==t&&(n.filter="none")}let a;if(n.scale(1/e,-1/i),t.bitmap)a=this.applyTransferMapsToBitmap(t);else if("function"==typeof HTMLElement&&t instanceof HTMLElement||!t.data)a=t;else{const s=this.cachedCanvases.getCanvas("inlineImage",e,i).context;Ye(s,t),a=this.applyTransferMapsToCanvas(s)}const r=this._scaleImage(a,ae(n));n.imageSmoothingEnabled=ts(ne(n),t.interpolate),Xe(n,r.img,0,0,r.paintWidth,r.paintHeight,0,-i,e,i),this.compose(),this.restore()}paintInlineImageXObjectGroup(t,e){if(!this.contentVisible)return;const s=this.ctx;let i;if(t.bitmap)i=t.bitmap;else{const e=t.width,s=t.height,n=this.cachedCanvases.getCanvas("inlineImage",e,s).context;Ye(n,t),i=this.applyTransferMapsToCanvas(n)}for(const t of e)s.save(),s.transform(...t.transform),s.scale(1,-1),Xe(s,i,t.x,t.y,t.w,t.h,0,-1,1,1),s.restore();this.compose()}paintSolidColorImageMask(){this.contentVisible&&(this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(t){}markPointProps(t,e){}beginMarkedContent(t){this.markedContentStack.push({visible:!0})}beginMarkedContentProps(t,e){"OC"===t?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(e)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(){this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(){}endCompat(){}consumePath(t){const e=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(t);const s=this.ctx;this.pendingClip&&(e||(this.pendingClip===ns?s.clip("evenodd"):s.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),s.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=ne(this.ctx);if(0===t[1]&&0===t[2])this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]),s=Math.hypot(t[0],t[2]),i=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(s,i)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(-1===this._cachedScaleForStroking[0]){const{lineWidth:t}=this.current,{a:e,b:s,c:i,d:n}=this.ctx.getTransform();let a,r;if(0===s&&0===i){const s=Math.abs(e),i=Math.abs(n);if(s===i)if(0===t)a=r=1/s;else{const e=s*t;a=r=e<1?1/e:1}else if(0===t)a=1/s,r=1/i;else{const e=s*t,n=i*t;a=e<1?1/e:1,r=n<1?1/n:1}}else{const o=Math.abs(e*n-s*i),h=Math.hypot(e,s),l=Math.hypot(i,n);if(0===t)a=l/o,r=h/o;else{const e=t*o;a=l>e?l/e:1,r=h>e?h/e:1}}this._cachedScaleForStroking[0]=a,this._cachedScaleForStroking[1]=r}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:s}=this.current,[i,n]=this.getScaleForStroking();if(e.lineWidth=s||1,1===i&&1===n)return void e.stroke();const a=e.getLineDash();if(t&&e.save(),e.scale(i,n),a.length>0){const t=Math.max(i,n);e.setLineDash(a.map(e=>e/t)),e.lineDashOffset/=t}e.stroke(),t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const t in K)void 0!==as.prototype[t]&&(as.prototype[K[t]]=as.prototype[t]);class rs{static#De=null;static#Le="";static get workerPort(){return this.#De}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#De=t}static get workerSrc(){return this.#Le}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#Le=t}}const os=1,hs=2,ls=1,ds=2,cs=3,us=4,ps=5,gs=6,ms=7,fs=8;function bs(t){switch(t instanceof Error||"object"==typeof t&&null!==t||st('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),t.name){case"AbortException":return new pt(t.message);case"MissingPDFException":return new dt(t.message);case"PasswordException":return new ot(t.message,t.code);case"UnexpectedResponseException":return new ct(t.message,t.status);case"UnknownErrorException":return new ht(t.message,t.details);default:return new ht(t.message,t.toString())}}class vs{constructor(t,e,s){this.sourceName=t,this.targetName=e,this.comObj=s,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),this._onComObjOnMessage=t=>{const e=t.data;if(e.targetName!==this.sourceName)return;if(e.stream)return void this.#Fe(e);if(e.callback){const t=e.callbackId,s=this.callbackCapabilities[t];if(!s)throw new Error(`Cannot resolve callback ${t}`);if(delete this.callbackCapabilities[t],e.callback===os)s.resolve(e.data);else{if(e.callback!==hs)throw new Error("Unexpected callback case");s.reject(bs(e.reason))}return}const i=this.actionHandler[e.action];if(!i)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const t=this.sourceName,n=e.sourceName;return void new Promise(function(t){t(i(e.data))}).then(function(i){s.postMessage({sourceName:t,targetName:n,callback:os,callbackId:e.callbackId,data:i})},function(i){s.postMessage({sourceName:t,targetName:n,callback:hs,callbackId:e.callbackId,reason:bs(i)})})}e.streamId?this.#Oe(e):i(e.data)},s.addEventListener("message",this._onComObjOnMessage)}on(t,e){const s=this.actionHandler;if(s[t])throw new Error(`There is already an actionName called "${t}"`);s[t]=e}send(t,e,s){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},s)}sendWithPromise(t,e,s){const i=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[i]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:i,data:e},s)}catch(t){n.reject(t)}return n.promise}sendWithStream(t,e,s,i){const n=this.streamId++,a=this.sourceName,r=this.targetName,o=this.comObj;return new ReadableStream({start:s=>{const h=Promise.withResolvers();return this.streamControllers[n]={controller:s,startCall:h,pullCall:null,cancelCall:null,isClosed:!1},o.postMessage({sourceName:a,targetName:r,action:t,streamId:n,data:e,desiredSize:s.desiredSize},i),h.promise},pull:t=>{const e=Promise.withResolvers();return this.streamControllers[n].pullCall=e,o.postMessage({sourceName:a,targetName:r,stream:gs,streamId:n,desiredSize:t.desiredSize}),e.promise},cancel:t=>{it(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();return this.streamControllers[n].cancelCall=e,this.streamControllers[n].isClosed=!0,o.postMessage({sourceName:a,targetName:r,stream:ls,streamId:n,reason:bs(t)}),e.promise}},s)}#Oe(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,a=this,r=this.actionHandler[t.action],o={enqueue(t,a=1,r){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=a,o>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),n.postMessage({sourceName:s,targetName:i,stream:us,streamId:e,chunk:t},r)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:cs,streamId:e}),delete a.streamSinks[e])},error(t){it(t instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:ps,streamId:e,reason:bs(t)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve(),o.ready=o.sinkCapability.promise,this.streamSinks[e]=o,new Promise(function(e){e(r(t.data,o))}).then(function(){n.postMessage({sourceName:s,targetName:i,stream:fs,streamId:e,success:!0})},function(t){n.postMessage({sourceName:s,targetName:i,stream:fs,streamId:e,reason:bs(t)})})}#Fe(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,a=this.streamControllers[e],r=this.streamSinks[e];switch(t.stream){case fs:t.success?a.startCall.resolve():a.startCall.reject(bs(t.reason));break;case ms:t.success?a.pullCall.resolve():a.pullCall.reject(bs(t.reason));break;case gs:if(!r){n.postMessage({sourceName:s,targetName:i,stream:ms,streamId:e,success:!0});break}r.desiredSize<=0&&t.desiredSize>0&&r.sinkCapability.resolve(),r.desiredSize=t.desiredSize,new Promise(function(t){t(r.onPull?.())}).then(function(){n.postMessage({sourceName:s,targetName:i,stream:ms,streamId:e,success:!0})},function(t){n.postMessage({sourceName:s,targetName:i,stream:ms,streamId:e,reason:bs(t)})});break;case us:if(it(a,"enqueue should have stream controller"),a.isClosed)break;a.controller.enqueue(t.chunk);break;case cs:if(it(a,"close should have stream controller"),a.isClosed)break;a.isClosed=!0,a.controller.close(),this.#Ne(a,e);break;case ps:it(a,"error should have stream controller"),a.controller.error(bs(t.reason)),this.#Ne(a,e);break;case ds:t.success?a.cancelCall.resolve():a.cancelCall.reject(bs(t.reason)),this.#Ne(a,e);break;case ls:if(!r)break;new Promise(function(e){e(r.onCancel?.(bs(t.reason)))}).then(function(){n.postMessage({sourceName:s,targetName:i,stream:ds,streamId:e,success:!0})},function(t){n.postMessage({sourceName:s,targetName:i,stream:ds,streamId:e,reason:bs(t)})}),r.sinkCapability.reject(bs(t.reason)),r.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#Ne(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}class As{#Be;#He;constructor({parsedData:t,rawData:e}){this.#Be=t,this.#He=e}getRaw(){return this.#He}get(t){return this.#Be.get(t)??null}getAll(){return ft(this.#Be)}has(t){return this.#Be.has(t)}}const ys=Symbol("INTERNAL");class ws{#ze=!1;#je=!1;#Ue=!1;#$e=!0;constructor(t,{name:e,intent:s,usage:i}){this.#ze=!!(t&o),this.#je=!!(t&h),this.name=e,this.intent=s,this.usage=i}get visible(){if(this.#Ue)return this.#$e;if(!this.#$e)return!1;const{print:t,view:e}=this.usage;return this.#ze?"OFF"!==e?.viewState:!this.#je||"OFF"!==t?.printState}_setVisible(t,e,s=!1){t!==ys&&st("Internal method `_setVisible` called."),this.#Ue=s,this.#$e=e}}class _s{#Ve=null;#Ge=new Map;#We=null;#qe=null;constructor(t,e=o){if(this.renderingIntent=e,this.name=null,this.creator=null,null!==t){this.name=t.name,this.creator=t.creator,this.#qe=t.order;for(const s of t.groups)this.#Ge.set(s.id,new ws(e,s));if("OFF"===t.baseState)for(const t of this.#Ge.values())t._setVisible(ys,!1);for(const e of t.on)this.#Ge.get(e)._setVisible(ys,!0);for(const e of t.off)this.#Ge.get(e)._setVisible(ys,!1);this.#We=this.getHash()}}#Xe(t){const e=t.length;if(e<2)return!0;const s=t[0];for(let i=1;i<e;i++){const e=t[i];let n;if(Array.isArray(e))n=this.#Xe(e);else{if(!this.#Ge.has(e))return et(`Optional content group not found: ${e}`),!0;n=this.#Ge.get(e).visible}switch(s){case"And":if(!n)return!1;break;case"Or":if(n)return!0;break;case"Not":return!n;default:return!0}}return"And"===s}isVisible(t){if(0===this.#Ge.size)return!0;if(!t)return tt("Optional content group not defined."),!0;if("OCG"===t.type)return this.#Ge.has(t.id)?this.#Ge.get(t.id).visible:(et(`Optional content group not found: ${t.id}`),!0);if("OCMD"===t.type){if(t.expression)return this.#Xe(t.expression);if(!t.policy||"AnyOn"===t.policy){for(const e of t.ids){if(!this.#Ge.has(e))return et(`Optional content group not found: ${e}`),!0;if(this.#Ge.get(e).visible)return!0}return!1}if("AllOn"===t.policy){for(const e of t.ids){if(!this.#Ge.has(e))return et(`Optional content group not found: ${e}`),!0;if(!this.#Ge.get(e).visible)return!1}return!0}if("AnyOff"===t.policy){for(const e of t.ids){if(!this.#Ge.has(e))return et(`Optional content group not found: ${e}`),!0;if(!this.#Ge.get(e).visible)return!0}return!1}if("AllOff"===t.policy){for(const e of t.ids){if(!this.#Ge.has(e))return et(`Optional content group not found: ${e}`),!0;if(this.#Ge.get(e).visible)return!1}return!0}return et(`Unknown optional content policy ${t.policy}.`),!0}return et(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0){const s=this.#Ge.get(t);s?(s._setVisible(ys,!!e,!0),this.#Ve=null):et(`Optional content group not found: ${t}`)}setOCGState({state:t,preserveRB:e}){let s;for(const e of t){switch(e){case"ON":case"OFF":case"Toggle":s=e;continue}const t=this.#Ge.get(e);if(t)switch(s){case"ON":t._setVisible(ys,!0);break;case"OFF":t._setVisible(ys,!1);break;case"Toggle":t._setVisible(ys,!t.visible)}}this.#Ve=null}get hasInitialVisibility(){return null===this.#We||this.getHash()===this.#We}getOrder(){return this.#Ge.size?this.#qe?this.#qe.slice():[...this.#Ge.keys()]:null}getGroups(){return this.#Ge.size>0?ft(this.#Ge):null}getGroup(t){return this.#Ge.get(t)||null}getHash(){if(null!==this.#Ve)return this.#Ve;const t=new _e;for(const[e,s]of this.#Ge)t.update(`${e}:${s.visible}`);return this.#Ve=t.hexdigest()}}class xs{constructor(t,{disableRange:e=!1,disableStream:s=!1}){it(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:i,initialData:n,progressiveDone:a,contentDispositionFilename:r}=t;if(this._queuedChunks=[],this._progressiveDone=a,this._contentDispositionFilename=r,n?.length>0){const t=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(t)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!s,this._isRangeSupported=!e,this._contentLength=i,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener((t,e)=>{this._onReceiveData({begin:t,chunk:e})}),t.addProgressListener((t,e)=>{this._onProgress({loaded:t,total:e})}),t.addProgressiveReadListener(t=>{this._onReceiveData({chunk:t})}),t.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),t.transportReady()}_onReceiveData({begin:t,chunk:e}){const s=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(void 0===t)this._fullRequestReader?this._fullRequestReader._enqueue(s):this._queuedChunks.push(s);else{it(this._rangeReaders.some(function(e){return e._begin===t&&(e._enqueue(s),!0)}),"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){void 0===t.total?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){it(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new Es(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new Cs(this,t,e);return this._pdfDataRangeTransport.requestDataRange(t,e),this._rangeReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class Es{constructor(t,e,s=!1,i=null){this._stream=t,this._done=s||!1,this._filename=qt(i)?i:null,this._queuedChunks=e||[],this._loaded=0;for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._requests=[],this._headersReady=Promise.resolve(),t._fullRequestReader=this,this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunks.push(t);this._loaded+=t.byteLength}}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0){return{value:this._queuedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class Cs{constructor(t,e,s){this._stream=t,this._begin=e,this._end=s,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(t){if(!this._done){if(0===this._requests.length)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}function Ss({getResponseHeader:t,isHttp:e,rangeChunkSize:s,disableRange:i}){const n={allowRangeRequests:!1,suggestedLength:void 0},a=parseInt(t("Content-Length"),10);if(!Number.isInteger(a))return n;if(n.suggestedLength=a,a<=2*s)return n;if(i||!e)return n;if("bytes"!==t("Accept-Ranges"))return n;return"identity"!==(t("Content-Encoding")||"identity")||(n.allowRangeRequests=!0),n}function Ts(t){const e=t("Content-Disposition");if(e){let t=function(t){let e=!0,s=i("filename\\*","i").exec(t);if(s){s=s[1];let t=r(s);return t=unescape(t),t=o(t),t=h(t),a(t)}if(s=function(t){const e=[];let s;const n=i("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(s=n.exec(t));){let[,t,i,n]=s;if(t=parseInt(t,10),t in e){if(0===t)break}else e[t]=[i,n]}const a=[];for(let t=0;t<e.length&&t in e;++t){let[s,i]=e[t];i=r(i),s&&(i=unescape(i),0===t&&(i=o(i))),a.push(i)}return a.join("")}(t),s)return a(h(s));if(s=i("filename","i").exec(t),s){s=s[1];let t=r(s);return t=h(t),a(t)}function i(t,e){return new RegExp("(?:^|;)\\s*"+t+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',e)}function n(t,s){if(t){if(!/^[\x00-\xFF]+$/.test(s))return s;try{const i=new TextDecoder(t,{fatal:!0}),n=mt(s);s=i.decode(n),e=!1}catch{}}return s}function a(t){return e&&/[\x80-\xff]/.test(t)&&(t=n("utf-8",t),e&&(t=n("iso-8859-1",t))),t}function r(t){if(t.startsWith('"')){const e=t.slice(1).split('\\"');for(let t=0;t<e.length;++t){const s=e[t].indexOf('"');-1!==s&&(e[t]=e[t].slice(0,s),e.length=t+1),e[t]=e[t].replaceAll(/\\(.)/g,"$1")}t=e.join('"')}return t}function o(t){const e=t.indexOf("'");return-1===e?t:n(t.slice(0,e),t.slice(e+1).replace(/^[^']*'/,""))}function h(t){return!t.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(t)?t:t.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(t,e,s,i){if("q"===s||"Q"===s)return n(e,i=(i=i.replaceAll("_"," ")).replaceAll(/=([0-9a-fA-F]{2})/g,function(t,e){return String.fromCharCode(parseInt(e,16))}));try{i=atob(i)}catch{}return n(e,i)})}return""}(e);if(t.includes("%"))try{t=decodeURIComponent(t)}catch{}if(qt(t))return t}return null}function Ms(t,e){return 404===t||0===t&&e.startsWith("file:")?new dt('Missing PDF "'+e+'".'):new ct(`Unexpected server response (${t}) while retrieving PDF "${e}".`,t)}function ks(t){return 200===t||206===t}function Ps(t,e,s){return{method:"GET",headers:t,signal:s.signal,mode:"cors",credentials:e?"include":"same-origin",redirect:"follow"}}function Is(t){const e=new Headers;for(const s in t){const i=t[s];void 0!==i&&e.append(s,i)}return e}function Rs(t){return t instanceof Uint8Array?t.buffer:t instanceof ArrayBuffer?t:(et(`getArrayBuffer - unexpected data format: ${t}`),new Uint8Array(t).buffer)}class Ds{constructor(t){this.source=t,this.isHttp=/^https?:/i.test(t.url),this.httpHeaders=this.isHttp&&t.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return it(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new Ls(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new Fs(this,t,e);return this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Ls{constructor(t){this._stream=t,this._reader=null,this._loaded=0,this._filename=null;const e=t.source;this._withCredentials=e.withCredentials||!1,this._contentLength=e.length,this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange,this._headers=Is(this._stream.httpHeaders);const s=e.url;fetch(s,Ps(this._headers,this._withCredentials,this._abortController)).then(t=>{if(!ks(t.status))throw Ms(t.status,s);this._reader=t.body.getReader(),this._headersCapability.resolve();const e=e=>t.headers.get(e),{allowRangeRequests:i,suggestedLength:n}=Ss({getResponseHeader:e,isHttp:this._stream.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=i,this._contentLength=n||this._contentLength,this._filename=Ts(e),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new pt("Streaming is disabled."))}).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:Rs(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class Fs{constructor(t,e,s){this._stream=t,this._reader=null,this._loaded=0;const i=t.source;this._withCredentials=i.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!i.disableStream,this._abortController=new AbortController,this._headers=Is(this._stream.httpHeaders),this._headers.append("Range",`bytes=${e}-${s-1}`);const n=i.url;fetch(n,Ps(this._headers,this._withCredentials,this._abortController)).then(t=>{if(!ks(t.status))throw Ms(t.status,n);this._readCapability.resolve(),this._reader=t.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded}),{value:Rs(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class Os{constructor(t,e={}){this.url=t,this.isHttp=/^https?:/i.test(t),this.httpHeaders=this.isHttp&&e.httpHeaders||Object.create(null),this.withCredentials=e.withCredentials||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(t,e,s){const i={begin:t,end:e};for(const t in s)i[t]=s[t];return this.request(i)}requestFull(t){return this.request(t)}request(t){const e=new XMLHttpRequest,s=this.currXhrId++,i=this.pendingRequests[s]={xhr:e};e.open("GET",this.url),e.withCredentials=this.withCredentials;for(const t in this.httpHeaders){const s=this.httpHeaders[t];void 0!==s&&e.setRequestHeader(t,s)}return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),i.expectedStatus=206):i.expectedStatus=200,e.responseType="arraybuffer",t.onError&&(e.onerror=function(s){t.onError(e.status)}),e.onreadystatechange=this.onStateChange.bind(this,s),e.onprogress=this.onProgress.bind(this,s),i.onHeadersReceived=t.onHeadersReceived,i.onDone=t.onDone,i.onError=t.onError,i.onProgress=t.onProgress,e.send(null),s}onProgress(t,e){const s=this.pendingRequests[t];s&&s.onProgress?.(e)}onStateChange(t,e){const s=this.pendingRequests[t];if(!s)return;const i=s.xhr;if(i.readyState>=2&&s.onHeadersReceived&&(s.onHeadersReceived(),delete s.onHeadersReceived),4!==i.readyState)return;if(!(t in this.pendingRequests))return;if(delete this.pendingRequests[t],0===i.status&&this.isHttp)return void s.onError?.(i.status);const n=i.status||200;if(!(200===n&&206===s.expectedStatus)&&n!==s.expectedStatus)return void s.onError?.(i.status);const a=function(t){const e=t.response;return"string"!=typeof e?e:mt(e).buffer}(i);if(206===n){const t=i.getResponseHeader("Content-Range"),e=/bytes (\d+)-(\d+)\/(\d+)/.exec(t);s.onDone({begin:parseInt(e[1],10),chunk:a})}else a?s.onDone({begin:0,chunk:a}):s.onError?.(i.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t],e.abort()}}class Ns{constructor(t){this._source=t,this._manager=new Os(t.url,{httpHeaders:t.httpHeaders,withCredentials:t.withCredentials}),this._rangeChunkSize=t.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){return it(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new Bs(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const s=new Hs(this._manager,t,e);return s.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Bs{constructor(t,e){this._manager=t;const s={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=e.url,this._fullRequestId=t.requestFull(s),this._headersReceivedCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._contentLength=e.length,this._rangeChunkSize=e.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t),s=t=>e.getResponseHeader(t),{allowRangeRequests:i,suggestedLength:n}=Ss({getResponseHeader:s,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});i&&(this._isRangeSupported=!0),this._contentLength=n||this._contentLength,this._filename=Ts(s),this._isRangeSupported&&this._manager.abortRequest(t),this._headersReceivedCapability.resolve()}_onDone(t){if(t)if(this._requests.length>0){this._requests.shift().resolve({value:t.chunk,done:!1})}else this._cachedChunks.push(t.chunk);if(this._done=!0,!(this._cachedChunks.length>0)){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=Ms(t,this._url),this._headersReceivedCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersReceivedCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0){return{value:this._cachedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersReceivedCapability.reject(t);for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class Hs{constructor(t,e,s){this._manager=t;const i={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=t.url,this._requestId=t.requestRange(e,s,i),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;if(this._requests.length>0){this._requests.shift().resolve({value:e,done:!1})}else this._queuedChunk=e;this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(t){this._storedError=Ms(t,this._url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(t){this.isStreamingSupported||this.onProgress?.({loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(null!==this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}const zs=/^file:\/\/\/[a-zA-Z]:\//;class js{constructor(t){this.source=t,this.url=function(t){const e=Pe.get("url"),s=e.parse(t);return"file:"===s.protocol||s.host?s:/^[a-z]:[/\\]/i.test(t)?e.parse(`file:///${t}`):(s.host||(s.protocol="file:"),s)}(t.url),this.isHttp="http:"===this.url.protocol||"https:"===this.url.protocol,this.isFsUrl="file:"===this.url.protocol,this.httpHeaders=this.isHttp&&t.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return it(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new qs(this):new Gs(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=this.isFsUrl?new Xs(this,t,e):new Ws(this,t,e);return this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Us{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null;const e=t.source;this._contentLength=e.length,this._loaded=0,this._filename=null,this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers()}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t)return this._readCapability=Promise.withResolvers(),this.read();this._loaded+=t.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",t=>{this._error(t)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new pt("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class $s{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const e=t.source;this._isStreamingSupported=!e.disableStream}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t)return this._readCapability=Promise.withResolvers(),this.read();this._loaded+=t.length,this.onProgress?.({loaded:this._loaded});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",t=>{this._error(t)}),this._storedError&&this._readableStream.destroy(this._storedError)}}function Vs(t,e){return{protocol:t.protocol,auth:t.auth,host:t.hostname,port:t.port,path:t.path,method:"GET",headers:e}}class Gs extends Us{constructor(t){super(t);const e=e=>{if(404===e.statusCode){const t=new dt(`Missing PDF "${this._url}".`);return this._storedError=t,void this._headersCapability.reject(t)}this._headersCapability.resolve(),this._setReadableStream(e);const s=t=>this._readableStream.headers[t.toLowerCase()],{allowRangeRequests:i,suggestedLength:n}=Ss({getResponseHeader:s,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=i,this._contentLength=n||this._contentLength,this._filename=Ts(s)};if(this._request=null,"http:"===this._url.protocol){const s=Pe.get("http");this._request=s.request(Vs(this._url,t.httpHeaders),e)}else{const s=Pe.get("https");this._request=s.request(Vs(this._url,t.httpHeaders),e)}this._request.on("error",t=>{this._storedError=t,this._headersCapability.reject(t)}),this._request.end()}}class Ws extends $s{constructor(t,e,s){super(t),this._httpHeaders={};for(const e in t.httpHeaders){const s=t.httpHeaders[e];void 0!==s&&(this._httpHeaders[e]=s)}this._httpHeaders.Range=`bytes=${e}-${s-1}`;const i=t=>{if(404===t.statusCode){const t=new dt(`Missing PDF "${this._url}".`);return void(this._storedError=t)}this._setReadableStream(t)};if(this._request=null,"http:"===this._url.protocol){const t=Pe.get("http");this._request=t.request(Vs(this._url,this._httpHeaders),i)}else{const t=Pe.get("https");this._request=t.request(Vs(this._url,this._httpHeaders),i)}this._request.on("error",t=>{this._storedError=t}),this._request.end()}}class qs extends Us{constructor(t){super(t);let e=decodeURIComponent(this._url.path);zs.test(this._url.href)&&(e=e.replace(/^\//,""));const s=Pe.get("fs");s.promises.lstat(e).then(t=>{this._contentLength=t.size,this._setReadableStream(s.createReadStream(e)),this._headersCapability.resolve()},t=>{"ENOENT"===t.code&&(t=new dt(`Missing PDF "${e}".`)),this._storedError=t,this._headersCapability.reject(t)})}}class Xs extends $s{constructor(t,e,s){super(t);let i=decodeURIComponent(this._url.path);zs.test(this._url.href)&&(i=i.replace(/^\//,""));const n=Pe.get("fs");this._setReadableStream(n.createReadStream(i,{start:e,end:s-1}))}}const Ks=30;class Ys{#Ke=Promise.withResolvers();#ft=null;#Ye=!1;#Qe=!!globalThis.FontInspector?.enabled;#Je=null;#Ze=null;#ts=0;#es=0;#ss=null;#is=null;#ns=0;#as=0;#rs=Object.create(null);#os=[];#hs=null;#ls=[];#ds=new WeakMap;#cs=null;static#us=new Map;static#ps=new Map;static#gs=null;static#ms=new Set;constructor({textContentSource:t,container:e,viewport:s}){if(t instanceof ReadableStream)this.#hs=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#hs=new ReadableStream({start(e){e.enqueue(t),e.close()}})}this.#ft=this.#is=e,this.#as=s.scale*(globalThis.devicePixelRatio||1),this.#ns=s.rotation,this.#Ze={prevFontSize:null,prevFontFamily:null,div:null,properties:null,ctx:null};const{pageWidth:i,pageHeight:n,pageX:a,pageY:r}=s.rawDims;this.#cs=[1,0,0,-1,-a,r+n],this.#es=i,this.#ts=n,Ys.#fs(),re(e,s),this.#Ke.promise.catch(()=>{}).then(()=>{Ys.#ms.delete(this),this.#Ze=null,this.#rs=null})}render(){const t=()=>{this.#ss.read().then(({value:e,done:s})=>{s?this.#Ke.resolve():(this.#Je??=e.lang,Object.assign(this.#rs,e.styles),this.#bs(e.items),t())},this.#Ke.reject)};return this.#ss=this.#hs.getReader(),Ys.#ms.add(this),t(),this.#Ke.promise}update({viewport:t,onBefore:e=null}){const s=t.scale*(globalThis.devicePixelRatio||1),i=t.rotation;if(i!==this.#ns&&(e?.(),this.#ns=i,re(this.#is,{rotation:i})),s!==this.#as){e?.(),this.#as=s;const t={prevFontSize:null,prevFontFamily:null,div:null,properties:null,ctx:Ys.#vs(this.#Je)};for(const e of this.#ls)t.properties=this.#ds.get(e),t.div=e,this.#As(t)}}cancel(){const t=new pt("TextLayer task cancelled.");this.#ss?.cancel(t).catch(()=>{}),this.#ss=null,this.#Ke.reject(t)}get textDivs(){return this.#ls}get textContentItemsStr(){return this.#os}#bs(t){if(this.#Ye)return;this.#Ze.ctx??=Ys.#vs(this.#Je);const e=this.#ls,s=this.#os;for(const i of t){if(e.length>1e5)return et("Ignoring additional textDivs for performance reasons."),void(this.#Ye=!0);if(void 0!==i.str)s.push(i.str),this.#ys(i);else if("beginMarkedContentProps"===i.type||"beginMarkedContent"===i.type){const t=this.#ft;this.#ft=document.createElement("span"),this.#ft.classList.add("markedContent"),null!==i.id&&this.#ft.setAttribute("id",`${i.id}`),t.append(this.#ft)}else"endMarkedContent"===i.type&&(this.#ft=this.#ft.parentNode)}}#ys(t){const e=document.createElement("span"),s={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#ls.push(e);const i=At.transform(this.#cs,t.transform);let n=Math.atan2(i[1],i[0]);const a=this.#rs[t.fontName];a.vertical&&(n+=Math.PI/2);const r=this.#Qe&&a.fontSubstitution||a.fontFamily,o=Math.hypot(i[2],i[3]),h=o*Ys.#ws(r,this.#Je);let l,d;0===n?(l=i[4],d=i[5]-h):(l=i[4]+h*Math.sin(n),d=i[5]-h*Math.cos(n));const c="calc(var(--scale-factor)*",u=e.style;this.#ft===this.#is?(u.left=`${(100*l/this.#es).toFixed(2)}%`,u.top=`${(100*d/this.#ts).toFixed(2)}%`):(u.left=`${c}${l.toFixed(2)}px)`,u.top=`${c}${d.toFixed(2)}px)`),u.fontSize=`${c}${(Ys.#gs*o).toFixed(2)}px)`,u.fontFamily=r,s.fontSize=o,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,this.#Qe&&(e.dataset.fontName=a.fontSubstitutionLoadedName||t.fontName),0!==n&&(s.angle=n*(180/Math.PI));let p=!1;if(t.str.length>1)p=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){const e=Math.abs(t.transform[0]),s=Math.abs(t.transform[3]);e!==s&&Math.max(e,s)/Math.min(e,s)>1.5&&(p=!0)}if(p&&(s.canvasWidth=a.vertical?t.height:t.width),this.#ds.set(e,s),this.#Ze.div=e,this.#Ze.properties=s,this.#As(this.#Ze),s.hasText&&this.#ft.append(e),s.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation"),this.#ft.append(t)}}#As(t){const{div:e,properties:s,ctx:i,prevFontSize:n,prevFontFamily:a}=t,{style:r}=e;let o="";if(Ys.#gs>1&&(o=`scale(${1/Ys.#gs})`),0!==s.canvasWidth&&s.hasText){const{fontFamily:h}=r,{canvasWidth:l,fontSize:d}=s;n===d&&a===h||(i.font=`${d*this.#as}px ${h}`,t.prevFontSize=d,t.prevFontFamily=h);const{width:c}=i.measureText(e.textContent);c>0&&(o=`scaleX(${l*this.#as/c}) ${o}`)}0!==s.angle&&(o=`rotate(${s.angle}deg) ${o}`),o.length>0&&(r.transform=o)}static cleanup(){if(!(this.#ms.size>0)){this.#us.clear();for(const{canvas:t}of this.#ps.values())t.remove();this.#ps.clear()}}static#vs(t=null){let e=this.#ps.get(t||="");if(!e){const s=document.createElement("canvas");s.className="hiddenCanvasElement",s.lang=t,document.body.append(s),e=s.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#ps.set(t,e)}return e}static#fs(){if(null!==this.#gs)return;const t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.textContent="X",document.body.append(t),this.#gs=t.getBoundingClientRect().height,t.remove()}static#ws(t,e){const s=this.#us.get(t);if(s)return s;const i=this.#vs(e),n=i.font;i.canvas.width=i.canvas.height=Ks,i.font=`30px ${t}`;const a=i.measureText("");let r=a.fontBoundingBoxAscent,o=Math.abs(a.fontBoundingBoxDescent);if(r){const e=r/(r+o);return this.#us.set(t,e),i.canvas.width=i.canvas.height=0,i.font=n,e}i.strokeStyle="red",i.clearRect(0,0,Ks,Ks),i.strokeText("g",0,0);let h=i.getImageData(0,0,Ks,Ks).data;o=0;for(let t=h.length-1-3;t>=0;t-=4)if(h[t]>0){o=Math.ceil(t/4/Ks);break}i.clearRect(0,0,Ks,Ks),i.strokeText("A",0,Ks),h=i.getImageData(0,0,Ks,Ks).data,r=0;for(let t=0,e=h.length;t<e;t+=4)if(h[t]>0){r=Ks-Math.floor(t/4/Ks);break}i.canvas.width=i.canvas.height=0,i.font=n;const l=r?r/(r+o):.8;return this.#us.set(t,l),l}}function Qs(){Zt("`renderTextLayer`, please use `TextLayer` instead.");const{textContentSource:t,container:e,viewport:s,...i}=arguments[0],n=Object.keys(i);n.length>0&&et("Ignoring `renderTextLayer` parameters: "+n.join(", "));const a=new Ys({textContentSource:t,container:e,viewport:s}),{textDivs:r,textContentItemsStr:o}=a;return{promise:a.render(),textDivs:r,textContentItemsStr:o}}function Js(){Zt("`updateTextLayer`, please use `TextLayer` instead.")}class Zs{static textContent(t){const e=[],s={items:e,styles:Object.create(null)};return function t(s){if(!s)return;let i=null;const n=s.name;if("#text"===n)i=s.value;else{if(!Zs.shouldBuildText(n))return;s?.attributes?.textContent?i=s.attributes.textContent:s.value&&(i=s.value)}if(null!==i&&e.push({str:i}),s.children)for(const e of s.children)t(e)}(t),s}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}const ti=65536,ei=s?class extends Lt{_createCanvas(t,e){return Pe.get("canvas").createCanvas(t,e)}}:class extends Lt{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}={}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){const s=this._document.createElement("canvas");return s.width=t,s.height=e,s}},si=s?class extends Ft{_fetchData(t,e){return Ie(t).then(t=>({cMapData:t,compressionType:e}))}}:jt,ii=s?class extends Dt{}:class extends Dt{#_s;#xs;#Es;#Cs;#Ss;#b=0;constructor({docId:t,ownerDocument:e=globalThis.document}={}){super(),this.#Es=t,this.#Cs=e}get#A(){return this.#_s||=new Map}get#Ts(){return this.#Ss||=new Map}get#Ms(){if(!this.#xs){const t=this.#Cs.createElement("div"),{style:e}=t;e.visibility="hidden",e.contain="strict",e.width=e.height=0,e.position="absolute",e.top=e.left=0,e.zIndex=-1;const s=this.#Cs.createElementNS(Bt,"svg");s.setAttribute("width",0),s.setAttribute("height",0),this.#xs=this.#Cs.createElementNS(Bt,"defs"),t.append(s),s.append(this.#xs),this.#Cs.body.append(t)}return this.#xs}#ks(t){if(1===t.length){const e=t[0],s=new Array(256);for(let t=0;t<256;t++)s[t]=e[t]/255;const i=s.join(",");return[i,i,i]}const[e,s,i]=t,n=new Array(256),a=new Array(256),r=new Array(256);for(let t=0;t<256;t++)n[t]=e[t]/255,a[t]=s[t]/255,r[t]=i[t]/255;return[n.join(","),a.join(","),r.join(",")]}addFilter(t){if(!t)return"none";let e=this.#A.get(t);if(e)return e;const[s,i,n]=this.#ks(t),a=1===t.length?s:`${s}${i}${n}`;if(e=this.#A.get(a),e)return this.#A.set(t,e),e;const r=`g_${this.#Es}_transfer_map_${this.#b++}`,o=`url(#${r})`;this.#A.set(t,o),this.#A.set(a,o);const h=this.#Ps(r);return this.#Is(s,i,n,h),o}addHCMFilter(t,e){const s=`${t}-${e}`,i="base";let n=this.#Ts.get(i);if(n?.key===s)return n.url;if(n?(n.filter?.remove(),n.key=s,n.url="none",n.filter=null):(n={key:s,url:"none",filter:null},this.#Ts.set(i,n)),!t||!e)return n.url;const a=this.#Rs(t);t=At.makeHexColor(...a);const r=this.#Rs(e);if(e=At.makeHexColor(...r),this.#Ms.style.color="","#000000"===t&&"#ffffff"===e||t===e)return n.url;const o=new Array(256);for(let t=0;t<=255;t++){const e=t/255;o[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}const h=o.join(","),l=`g_${this.#Es}_hcm_filter`,d=n.filter=this.#Ps(l);this.#Is(h,h,h,d),this.#Ds(d);const c=(t,e)=>{const s=a[t]/255,i=r[t]/255,n=new Array(e+1);for(let t=0;t<=e;t++)n[t]=s+t/e*(i-s);return n.join(",")};return this.#Is(c(0,5),c(1,5),c(2,5),d),n.url=`url(#${l})`,n.url}addAlphaFilter(t){let e=this.#A.get(t);if(e)return e;const[s]=this.#ks([t]),i=`alpha_${s}`;if(e=this.#A.get(i),e)return this.#A.set(t,e),e;const n=`g_${this.#Es}_alpha_map_${this.#b++}`,a=`url(#${n})`;this.#A.set(t,a),this.#A.set(i,a);const r=this.#Ps(n);return this.#Ls(s,r),a}addLuminosityFilter(t){let e,s,i=this.#A.get(t||"luminosity");if(i)return i;if(t?([e]=this.#ks([t]),s=`luminosity_${e}`):s="luminosity",i=this.#A.get(s),i)return this.#A.set(t,i),i;const n=`g_${this.#Es}_luminosity_map_${this.#b++}`,a=`url(#${n})`;this.#A.set(t,a),this.#A.set(s,a);const r=this.#Ps(n);return this.#Fs(r),t&&this.#Ls(e,r),a}addHighlightHCMFilter(t,e,s,i,n){const a=`${e}-${s}-${i}-${n}`;let r=this.#Ts.get(t);if(r?.key===a)return r.url;if(r?(r.filter?.remove(),r.key=a,r.url="none",r.filter=null):(r={key:a,url:"none",filter:null},this.#Ts.set(t,r)),!e||!s)return r.url;const[o,h]=[e,s].map(this.#Rs.bind(this));let l=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),d=Math.round(.2126*h[0]+.7152*h[1]+.0722*h[2]),[c,u]=[i,n].map(this.#Rs.bind(this));d<l&&([l,d,c,u]=[d,l,u,c]),this.#Ms.style.color="";const p=(t,e,s)=>{const i=new Array(256),n=(d-l)/s,a=t/255,r=(e-t)/(255*s);let o=0;for(let t=0;t<=s;t++){const e=Math.round(l+t*n),s=a+t*r;for(let t=o;t<=e;t++)i[t]=s;o=e+1}for(let t=o;t<256;t++)i[t]=i[o-1];return i.join(",")},g=`g_${this.#Es}_hcm_${t}_filter`,m=r.filter=this.#Ps(g);return this.#Ds(m),this.#Is(p(c[0],u[0],5),p(c[1],u[1],5),p(c[2],u[2],5),m),r.url=`url(#${g})`,r.url}destroy(t=!1){t&&0!==this.#Ts.size||(this.#xs&&(this.#xs.parentNode.parentNode.remove(),this.#xs=null),this.#_s&&(this.#_s.clear(),this.#_s=null),this.#b=0)}#Fs(t){const e=this.#Cs.createElementNS(Bt,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),t.append(e)}#Ds(t){const e=this.#Cs.createElementNS(Bt,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),t.append(e)}#Ps(t){const e=this.#Cs.createElementNS(Bt,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#Ms.append(e),e}#Os(t,e,s){const i=this.#Cs.createElementNS(Bt,e);i.setAttribute("type","discrete"),i.setAttribute("tableValues",s),t.append(i)}#Is(t,e,s,i){const n=this.#Cs.createElementNS(Bt,"feComponentTransfer");i.append(n),this.#Os(n,"feFuncR",t),this.#Os(n,"feFuncG",e),this.#Os(n,"feFuncB",s)}#Ls(t,e){const s=this.#Cs.createElementNS(Bt,"feComponentTransfer");e.append(s),this.#Os(s,"feFuncA",t)}#Rs(t){return this.#Ms.style.color=t,ie(getComputedStyle(this.#Ms).getPropertyValue("color"))}},ni=s?class extends Ot{_fetchData(t){return Ie(t)}}:Ut;function ai(t={}){"string"==typeof t||t instanceof URL?t={url:t}:(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t});const e=new oi,{docId:i}=e,n=t.url?function(t){if(t instanceof URL)return t.href;try{return new URL(t,window.location).href}catch{if(s&&"string"==typeof t)return t}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(t.url):null,a=t.data?function(t){if(s&&"undefined"!=typeof Buffer&&t instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength)return t;if("string"==typeof t)return mt(t);if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)||"object"==typeof t&&!isNaN(t?.length))return new Uint8Array(t);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}(t.data):null,r=t.httpHeaders||null,o=!0===t.withCredentials,h=t.password??null,l=t.range instanceof hi?t.range:null,d=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:ti;let c=t.worker instanceof pi?t.worker:null;const u=t.verbosity,p="string"!=typeof t.docBaseUrl||Wt(t.docBaseUrl)?null:t.docBaseUrl,g="string"==typeof t.cMapUrl?t.cMapUrl:null,m=!1!==t.cMapPacked,f=t.CMapReaderFactory||si,b="string"==typeof t.standardFontDataUrl?t.standardFontDataUrl:null,v=t.StandardFontDataFactory||ni,A=!0!==t.stopAtErrors,y=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,w=!1!==t.isEvalSupported,_="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!s,x=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,E="boolean"==typeof t.disableFontFace?t.disableFontFace:s,C=!0===t.fontExtraProperties,S=!0===t.enableXfa,T=t.ownerDocument||globalThis.document,M=!0===t.disableRange,k=!0===t.disableStream,P=!0===t.disableAutoFetch,I=!0===t.pdfBug,R=!0===t.enableHWA,D=l?l.length:t.length??NaN,L="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!s&&!E,F="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:f===jt&&v===Ut&&g&&b&&Qt(g,document.baseURI)&&Qt(b,document.baseURI),O=t.canvasFactory||new ei({ownerDocument:T,enableHWA:R}),N=t.filterFactory||new ii({docId:i,ownerDocument:T});J(u);const B={canvasFactory:O,filterFactory:N};if(F||(B.cMapReaderFactory=new f({baseUrl:g,isCompressed:m}),B.standardFontDataFactory=new v({baseUrl:b})),!c){const t={verbosity:u,port:rs.workerPort};c=t.port?pi.fromPort(t):new pi(t),e._worker=c}const H={docId:i,apiVersion:"4.4.168",data:a,password:h,disableAutoFetch:P,rangeChunkSize:d,length:D,docBaseUrl:p,enableXfa:S,evaluatorOptions:{maxImageSize:y,disableFontFace:E,ignoreErrors:A,isEvalSupported:w,isOffscreenCanvasSupported:_,canvasMaxAreaInBytes:x,fontExtraProperties:C,useSystemFonts:L,cMapUrl:F?g:null,standardFontDataUrl:F?b:null}},z={disableFontFace:E,fontExtraProperties:C,ownerDocument:T,pdfBug:I,styleElement:null,loadingParams:{disableAutoFetch:P,enableXfa:S}};return c.promise.then(function(){if(e.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const t=c.messageHandler.sendWithPromise("GetDocRequest",H,a?[a.buffer]:null);let h;if(l)h=new xs(l,{disableRange:M,disableStream:k});else if(!a){if(!n)throw new Error("getDocument - no `url` parameter provided.");h=(t=>{if(s){return function(){return"undefined"!=typeof fetch&&"undefined"!=typeof Response&&"body"in Response.prototype}()&&Qt(t.url)?new Ds(t):new js(t)}return Qt(t.url)?new Ds(t):new Ns(t)})({url:n,length:D,httpHeaders:r,withCredentials:o,rangeChunkSize:d,disableRange:M,disableStream:k})}return t.then(t=>{if(e.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const s=new vs(i,t,c.port),n=new gi(s,e,h,z,B);e._transport=n,s.send("Ready",null)})}).catch(e._capability.reject),e}function ri(t){return"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0}class oi{static#Es=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId="d"+oi.#Es++,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await(this._transport?.destroy())}catch(t){throw this._worker?.port&&delete this._worker._pendingDestroy,t}this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}}class hi{constructor(t,e,s=!1,i=null){this.length=t,this.initialData=e,this.progressiveDone=s,this.contentDispositionFilename=i,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const s of this._rangeListeners)s(t,e)}onDataProgress(t,e){this._readyCapability.promise.then(()=>{for(const s of this._progressListeners)s(t,e)})}onDataProgressiveRead(t){this._readyCapability.promise.then(()=>{for(const e of this._progressiveReadListeners)e(t)})}onDataProgressiveDone(){this._readyCapability.promise.then(()=>{for(const t of this._progressiveDoneListeners)t()})}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){st("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class li{constructor(t,e){this._pdfInfo=t,this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return at(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class di{#Ns=null;#Bs=!1;constructor(t,e,s,i=!1){this._pageIndex=t,this._pageInfo=e,this._transport=s,this._stats=i?new Yt:null,this._pdfBug=i,this.commonObjs=s.commonObjs,this.objs=new fi,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:s=0,offsetY:i=0,dontFlip:n=!1}={}){return new Vt({viewBox:this.view,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return at(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:s="display",annotationMode:i=p.ENABLE,transform:n=null,background:a=null,optionalContentConfigPromise:r=null,annotationCanvasMap:o=null,pageColors:l=null,printAnnotationStorage:d=null}){this._stats?.time("Overall");const c=this._transport.getRenderingIntent(s,i,d),{renderingIntent:u,cacheKey:g}=c;this.#Bs=!1,this.#Hs(),r||=this._transport.getOptionalContentConfig(u);let m=this._intentStates.get(g);m||(m=Object.create(null),this._intentStates.set(g,m)),m.streamReaderCancelTimeout&&(clearTimeout(m.streamReaderCancelTimeout),m.streamReaderCancelTimeout=null);const f=!!(u&h);m.displayReadyCapability||(m.displayReadyCapability=Promise.withResolvers(),m.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(c));const b=t=>{m.renderTasks.delete(v),(this._maybeCleanupAfterRender||f)&&(this.#Bs=!0),this.#zs(!f),t?(v.capability.reject(t),this._abortOperatorList({intentState:m,reason:t instanceof Error?t:new Error(t)})):v.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},v=new vi({callback:b,params:{canvasContext:t,viewport:e,transform:n,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:o,operatorList:m.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!f,pdfBug:this._pdfBug,pageColors:l});(m.renderTasks||=new Set).add(v);const A=v.task;return Promise.all([m.displayReadyCapability.promise,r]).then(([t,e])=>{if(this.destroyed)b();else{if(this._stats?.time("Rendering"),!(e.renderingIntent&u))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");v.initializeGraphics({transparency:t,optionalContentConfig:e}),v.operatorListChanged()}}).catch(b),A}getOperatorList({intent:t="display",annotationMode:e=p.ENABLE,printAnnotationStorage:s=null}={}){const i=this._transport.getRenderingIntent(t,e,s,!0);let n,a=this._intentStates.get(i.cacheKey);return a||(a=Object.create(null),this._intentStates.set(i.cacheKey,a)),a.opListReadCapability||(n=Object.create(null),n.operatorListChanged=function(){a.operatorList.lastChunk&&(a.opListReadCapability.resolve(a.operatorList),a.renderTasks.delete(n))},a.opListReadCapability=Promise.withResolvers(),(a.renderTasks||=new Set).add(n),a.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(i)),a.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(t=>Zs.textContent(t));const e=this.streamTextContent(t);return new Promise(function(t,s){const i=e.getReader(),n={items:[],styles:Object.create(null),lang:null};!function e(){i.read().then(function({value:s,done:i}){i?t(n):(n.lang??=s.lang,Object.assign(n.styles,s.styles),n.items.push(...s.items),e())},s)}()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(const s of e.renderTasks)t.push(s.completed),s.cancel();return this.objs.clear(),this.#Bs=!1,this.#Hs(),Promise.all(t)}cleanup(t=!1){this.#Bs=!0;const e=this.#zs(!1);return t&&e&&(this._stats&&=new Yt),e}#zs(t=!1){if(this.#Hs(),!this.#Bs||this.destroyed)return!1;if(t)return this.#Ns=setTimeout(()=>{this.#Ns=null,this.#zs(!1)},5e3),!1;for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#Bs=!1,!0}#Hs(){this.#Ns&&(clearTimeout(this.#Ns),this.#Ns=null)}_startRenderPage(t,e){const s=this._intentStates.get(e);s&&(this._stats?.timeEnd("Page Request"),s.displayReadyCapability?.resolve(t))}_renderPageChunk(t,e){for(let s=0,i=t.length;s<i;s++)e.operatorList.fnArray.push(t.fnArray[s]),e.operatorList.argsArray.push(t.argsArray[s]);e.operatorList.lastChunk=t.lastChunk,e.operatorList.separateAnnots=t.separateAnnots;for(const t of e.renderTasks)t.operatorListChanged();t.lastChunk&&this.#zs(!0)}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:s}){const{map:i,transfer:n}=s,a=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:i},n).getReader(),r=this._intentStates.get(e);r.streamReader=a;const o=()=>{a.read().then(({value:t,done:e})=>{e?r.streamReader=null:this._transport.destroyed||(this._renderPageChunk(t,r),o())},t=>{if(r.streamReader=null,!this._transport.destroyed){if(r.operatorList){r.operatorList.lastChunk=!0;for(const t of r.renderTasks)t.operatorListChanged();this.#zs(!0)}if(r.displayReadyCapability)r.displayReadyCapability.reject(t);else{if(!r.opListReadCapability)throw t;r.opListReadCapability.reject(t)}}})};o()}_abortOperatorList({intentState:t,reason:e,force:s=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!s){if(t.renderTasks.size>0)return;if(e instanceof Gt){let s=100;return e.extraDelay>0&&e.extraDelay<1e3&&(s+=e.extraDelay),void(t.streamReaderCancelTimeout=setTimeout(()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:e,force:!0})},s))}}if(t.streamReader.cancel(new pt(e.message)).catch(()=>{}),t.streamReader=null,!this._transport.destroyed){for(const[e,s]of this._intentStates)if(s===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class ci{#js=new Set;#Us=Promise.resolve();postMessage(t,e){const s={data:structuredClone(t,e?{transfer:e}:null)};this.#Us.then(()=>{for(const t of this.#js)t.call(this,s)})}addEventListener(t,e){this.#js.add(e)}removeEventListener(t,e){this.#js.delete(e)}terminate(){this.#js.clear()}}const ui={isWorkerDisabled:!1,fakeWorkerId:0};s&&(ui.isWorkerDisabled=!0,rs.workerSrc||="./pdf.worker.mjs"),ui.isSameOrigin=function(t,e){let s;try{if(s=new URL(t),!s.origin||"null"===s.origin)return!1}catch{return!1}const i=new URL(e,s);return s.origin===i.origin},ui.createCDNWrapper=function(t){const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))};class pi{static#$s;constructor({name:t=null,port:e=null,verbosity:s=Z()}={}){if(this.name=t,this.destroyed=!1,this.verbosity=s,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,e){if(pi.#$s?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");return(pi.#$s||=new WeakMap).set(e,this),void this._initializeFromPort(e)}this._initialize()}get promise(){return s?Promise.all([Pe.promise,this._readyCapability.promise]):this._readyCapability.promise}#Vs(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t,this._messageHandler=new vs("main","worker",t),this._messageHandler.on("ready",function(){}),this.#Vs()}_initialize(){if(ui.isWorkerDisabled||pi.#Gs)return void this._setupFakeWorker();let{workerSrc:t}=pi;try{ui.isSameOrigin(window.location.href,t)||(t=ui.createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),s=new vs("main","worker",e),i=()=>{n.abort(),s.destroy(),e.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},n=new AbortController;e.addEventListener("error",()=>{this._webWorker||i()},{signal:n.signal}),s.on("test",t=>{n.abort(),!this.destroyed&&t?(this._messageHandler=s,this._port=e,this._webWorker=e,this.#Vs()):i()}),s.on("ready",t=>{if(n.abort(),this.destroyed)i();else try{a()}catch{this._setupFakeWorker()}});const a=()=>{const t=new Uint8Array;s.send("test",t,[t.buffer])};return void a()}catch{tt("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){ui.isWorkerDisabled||(et("Setting up fake worker."),ui.isWorkerDisabled=!0),pi._setupFakeWorkerGlobal.then(t=>{if(this.destroyed)return void this._readyCapability.reject(new Error("Worker was destroyed"));const e=new ci;this._port=e;const s="fake"+ui.fakeWorkerId++,i=new vs(s+"_worker",s,e);t.setup(i,e),this._messageHandler=new vs(s,s+"_worker",e),this.#Vs()}).catch(t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),pi.#$s?.delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const e=this.#$s?.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new pi(t)}static get workerSrc(){if(rs.workerSrc)return rs.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#Gs(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return at(this,"_setupFakeWorkerGlobal",(async()=>{if(this.#Gs)return this.#Gs;return(await import(this.workerSrc)).WorkerMessageHandler})())}}class gi{#Ws=new Map;#qs=new Map;#Xs=new Map;#Ks=new Map;#Ys=null;constructor(t,e,s,i,n){this.messageHandler=t,this.loadingTask=e,this.commonObjs=new fi,this.fontLoader=new Se({ownerDocument:i.ownerDocument,styleElement:i.styleElement}),this.loadingParams=i.loadingParams,this._params=i,this.canvasFactory=n.canvasFactory,this.filterFactory=n.filterFactory,this.cMapReaderFactory=n.cMapReaderFactory,this.standardFontDataFactory=n.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=s,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#Qs(t,e=null){const s=this.#Ws.get(t);if(s)return s;const i=this.messageHandler.sendWithPromise(t,e);return this.#Ws.set(t,i),i}get annotationStorage(){return at(this,"annotationStorage",new Ee)}getRenderingIntent(t,e=p.ENABLE,s=null,i=!1){let n=o,a=xe;switch(t){case"any":n=r;break;case"display":break;case"print":n=h;break;default:et(`getRenderingIntent - invalid intent: ${t}`)}switch(e){case p.DISABLE:n+=c;break;case p.ENABLE:break;case p.ENABLE_FORMS:n+=l;break;case p.ENABLE_STORAGE:n+=d;a=(n&h&&s instanceof Ce?s:this.annotationStorage).serializable;break;default:et(`getRenderingIntent - invalid annotationMode: ${e}`)}return i&&(n+=u),{renderingIntent:n,cacheKey:`${n}_${a.hash}`,annotationStorageSerializable:a}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#Ys?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#qs.values())t.push(e._destroy());this.#qs.clear(),this.#Xs.clear(),this.#Ks.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#Ws.clear(),this.filterFactory.destroy(),Ys.cleanup(),this._networkStream?.cancelAllRequests(new pt("Worker was terminated.")),this.messageHandler&&(this.messageHandler.destroy(),this.messageHandler=null),this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",(t,e)=>{it(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=t=>{this._lastProgress={loaded:t.loaded,total:t.total}},e.onPull=()=>{this._fullReader.read().then(function({value:t,done:s}){s?e.close():(it(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))}).catch(t=>{e.error(t)})},e.onCancel=t=>{this._fullReader.cancel(t),e.ready.catch(t=>{if(!this.destroyed)throw t})}}),t.on("ReaderHeadersReady",t=>{const s=Promise.withResolvers(),i=this._fullReader;return i.headersReady.then(()=>{i.isStreamingSupported&&i.isRangeSupported||(this._lastProgress&&e.onProgress?.(this._lastProgress),i.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}),s.resolve({isStreamingSupported:i.isStreamingSupported,isRangeSupported:i.isRangeSupported,contentLength:i.contentLength})},s.reject),s.promise}),t.on("GetRangeReader",(t,e)=>{it(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const s=this._networkStream.getRangeReader(t.begin,t.end);s?(e.onPull=()=>{s.read().then(function({value:t,done:s}){s?e.close():(it(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))}).catch(t=>{e.error(t)})},e.onCancel=t=>{s.cancel(t),e.ready.catch(t=>{if(!this.destroyed)throw t})}):e.close()}),t.on("GetDoc",({pdfInfo:t})=>{this._numPages=t.numPages,this._htmlForXfa=t.htmlForXfa,delete t.htmlForXfa,e._capability.resolve(new li(t,this))}),t.on("DocException",function(t){let s;switch(t.name){case"PasswordException":s=new ot(t.message,t.code);break;case"InvalidPDFException":s=new lt(t.message);break;case"MissingPDFException":s=new dt(t.message);break;case"UnexpectedResponseException":s=new ct(t.message,t.status);break;case"UnknownErrorException":s=new ht(t.message,t.details);break;default:st("DocException - expected a valid Error.")}e._capability.reject(s)}),t.on("PasswordRequest",t=>{if(this.#Ys=Promise.withResolvers(),e.onPassword){const s=t=>{t instanceof Error?this.#Ys.reject(t):this.#Ys.resolve({password:t})};try{e.onPassword(s,t.code)}catch(t){this.#Ys.reject(t)}}else this.#Ys.reject(new ot(t.message,t.code));return this.#Ys.promise}),t.on("DataLoaded",t=>{e.onProgress?.({loaded:t.length,total:t.length}),this.downloadInfoCapability.resolve(t)}),t.on("StartRenderPage",t=>{if(this.destroyed)return;this.#qs.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)}),t.on("commonobj",([e,s,i])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(s){case"Font":const{disableFontFace:n,fontExtraProperties:a,pdfBug:r}=this._params;if("error"in i){const t=i.error;et(`Error during font loading: ${t}`),this.commonObjs.resolve(e,t);break}const o=r&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,h=new Te(i,{disableFontFace:n,inspectFont:o});this.fontLoader.bind(h).catch(()=>t.sendWithPromise("FontFallback",{id:e})).finally(()=>{!a&&h.data&&(h.data=null),this.commonObjs.resolve(e,h)});break;case"CopyLocalImage":const{imageRef:l}=i;it(l,"The imageRef must be defined.");for(const t of this.#qs.values())for(const[,s]of t.objs)if(s?.ref===l)return s.dataLen?(this.commonObjs.resolve(e,structuredClone(s)),s.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(e,i);break;default:throw new Error(`Got unknown common object type ${s}`)}return null}),t.on("obj",([t,e,s,i])=>{if(this.destroyed)return;const n=this.#qs.get(e);if(!n.objs.has(t))if(0!==n._intentStates.size)switch(s){case"Image":n.objs.resolve(t,i),i?.dataLen>1e7&&(n._maybeCleanupAfterRender=!0);break;case"Pattern":n.objs.resolve(t,i);break;default:throw new Error(`Got unknown object type ${s}`)}else i?.bitmap?.close()}),t.on("DocProgress",t=>{this.destroyed||e.onProgress?.({loaded:t.loaded,total:t.total})}),t.on("FetchBuiltInCMap",t=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.cMapReaderFactory?this.cMapReaderFactory.fetch(t):Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."))),t.on("FetchStandardFontData",t=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.standardFontDataFactory?this.standardFontDataFactory.fetch(t):Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.")))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&et("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,s=this.#Xs.get(e);if(s)return s;const i=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then(s=>{if(this.destroyed)throw new Error("Transport destroyed");s.refStr&&this.#Ks.set(s.refStr,t);const i=new di(e,s,this,this._params.pdfBug);return this.#qs.set(e,i),i});return this.#Xs.set(e,i),i}getPageIndex(t){return ri(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this.#Qs("GetFieldObjects")}hasJSActions(){return this.#Qs("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#Qs("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#Qs("GetOptionalContentConfig").then(e=>new _s(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#Ws.get(t);if(e)return e;const s=this.messageHandler.sendWithPromise(t,null).then(t=>({info:t[0],metadata:t[1]?new As(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null}));return this.#Ws.set(t,s),s}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#qs.values()){if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear(),t||this.fontLoader.clear(),this.#Ws.clear(),this.filterFactory.destroy(!0),Ys.cleanup()}}cachedPageNumber(t){if(!ri(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`;return this.#Ks.get(e)??null}}const mi=Symbol("INITIAL_DATA");class fi{#Js=Object.create(null);#Zs(t){return this.#Js[t]||={...Promise.withResolvers(),data:mi}}get(t,e=null){if(e){const s=this.#Zs(t);return s.promise.then(()=>e(s.data)),null}const s=this.#Js[t];if(!s||s.data===mi)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return s.data}has(t){const e=this.#Js[t];return!!e&&e.data!==mi}resolve(t,e=null){const s=this.#Zs(t);s.data=e,s.resolve()}clear(){for(const t in this.#Js){const{data:e}=this.#Js[t];e?.bitmap?.close()}this.#Js=Object.create(null)}*[Symbol.iterator](){for(const t in this.#Js){const{data:e}=this.#Js[t];e!==mi&&(yield[t,e])}}}class bi{#ti=null;constructor(t){this.#ti=t,this.onContinue=null}get promise(){return this.#ti.capability.promise}cancel(t=0){this.#ti.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#ti.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#ti;return t.form||t.canvas&&e?.size>0}}class vi{#ei=null;static#si=new WeakSet;constructor({callback:t,params:e,objs:s,commonObjs:i,annotationCanvasMap:n,operatorList:a,pageIndex:r,canvasFactory:o,filterFactory:h,useRequestAnimationFrame:l=!1,pdfBug:d=!1,pageColors:c=null}){this.callback=t,this.params=e,this.objs=s,this.commonObjs=i,this.annotationCanvasMap=n,this.operatorListIdx=null,this.operatorList=a,this._pageIndex=r,this.canvasFactory=o,this.filterFactory=h,this._pdfBug=d,this.pageColors=c,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=!0===l&&"undefined"!=typeof window,this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new bi(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=e.canvasContext.canvas}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(vi.#si.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");vi.#si.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{canvasContext:s,viewport:i,transform:n,background:a}=this.params;this.gfx=new as(s,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:n,viewport:i,transparency:t,background:a}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#ei&&(window.cancelAnimationFrame(this.#ei),this.#ei=null),vi.#si.delete(this._canvas),this.callback(t||new Gt(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){this.graphicsReady?(this.stepper?.updateOperatorList(this.operatorList),this.running||this._continue()):this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0,this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#ei=window.requestAnimationFrame(()=>{this.#ei=null,this._nextBound().catch(this._cancelBound)}):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),vi.#si.delete(this._canvas),this.callback())))}}const Ai="4.4.168",yi="19fbc8998";function wi(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function _i(t){return Math.max(0,Math.min(255,255*t))}class xi{static CMYK_G([t,e,s,i]){return["G",1-Math.min(1,.3*t+.59*s+.11*e+i)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=_i(t),t,t]}static G_HTML([t]){const e=wi(t);return`#${e}${e}${e}`}static RGB_G([t,e,s]){return["G",.3*t+.59*e+.11*s]}static RGB_rgb(t){return t.map(_i)}static RGB_HTML(t){return`#${t.map(wi).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,s,i]){return["RGB",1-Math.min(1,t+i),1-Math.min(1,s+i),1-Math.min(1,e+i)]}static CMYK_rgb([t,e,s,i]){return[_i(1-Math.min(1,t+i)),_i(1-Math.min(1,s+i)),_i(1-Math.min(1,e+i))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,s]){const i=1-t,n=1-e,a=1-s;return["CMYK",i,n,a,Math.min(i,n,a)]}}class Ei{static setupStorage(t,e,s,i,n){const a=i.getValue(e,{value:null});switch(s.name){case"textarea":if(null!==a.value&&(t.textContent=a.value),"print"===n)break;t.addEventListener("input",t=>{i.setValue(e,{value:t.target.value})});break;case"input":if("radio"===s.attributes.type||"checkbox"===s.attributes.type){if(a.value===s.attributes.xfaOn?t.setAttribute("checked",!0):a.value===s.attributes.xfaOff&&t.removeAttribute("checked"),"print"===n)break;t.addEventListener("change",t=>{i.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})})}else{if(null!==a.value&&t.setAttribute("value",a.value),"print"===n)break;t.addEventListener("input",t=>{i.setValue(e,{value:t.target.value})})}break;case"select":if(null!==a.value){t.setAttribute("value",a.value);for(const t of s.children)t.attributes.value===a.value?t.attributes.selected=!0:t.attributes.hasOwnProperty("selected")&&delete t.attributes.selected}t.addEventListener("input",t=>{const s=t.target.options,n=-1===s.selectedIndex?"":s[s.selectedIndex].value;i.setValue(e,{value:n})})}}static setAttributes({html:t,element:e,storage:s=null,intent:i,linkService:n}){const{attributes:a}=e,r=t instanceof HTMLAnchorElement;"radio"===a.type&&(a.name=`${a.name}-${i}`);for(const[e,s]of Object.entries(a))if(null!=s)switch(e){case"class":s.length&&t.setAttribute(e,s.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",s);break;case"style":Object.assign(t.style,s);break;case"textContent":t.textContent=s;break;default:(!r||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,s)}r&&n.addLinkAttributes(t,a.href,a.newWindow),s&&a.dataId&&this.setupStorage(t,a.dataId,e,s)}static render(t){const e=t.annotationStorage,s=t.linkService,i=t.xfaHtml,n=t.intent||"display",a=document.createElement(i.name);i.attributes&&this.setAttributes({html:a,element:i,intent:n,linkService:s});const r="richText"!==n,o=t.div;if(o.append(a),t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}r&&o.setAttribute("class","xfaLayer xfaFont");const h=[];if(0===i.children.length){if(i.value){const t=document.createTextNode(i.value);a.append(t),r&&Zs.shouldBuildText(i.name)&&h.push(t)}return{textDivs:h}}const l=[[i,-1,a]];for(;l.length>0;){const[t,i,a]=l.at(-1);if(i+1===t.children.length){l.pop();continue}const o=t.children[++l.at(-1)[1]];if(null===o)continue;const{name:d}=o;if("#text"===d){const t=document.createTextNode(o.value);h.push(t),a.append(t);continue}const c=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,d):document.createElement(d);if(a.append(c),o.attributes&&this.setAttributes({html:c,element:o,storage:e,intent:n,linkService:s}),o.children?.length>0)l.push([o,-1,c]);else if(o.value){const t=document.createTextNode(o.value);r&&Zs.shouldBuildText(d)&&h.push(t),c.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:h}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}const Ci=1e3,Si=new WeakSet;function Ti(t){return{width:t[2]-t[0],height:t[3]-t[1]}}class Mi{static create(t){switch(t.data.annotationType){case C:return new Pi(t);case E:return new Ii(t);case j:switch(t.data.fieldType){case"Tx":return new Di(t);case"Btn":return t.data.radioButton?new Oi(t):t.data.checkBox?new Fi(t):new Ni(t);case"Ch":return new Bi(t);case"Sig":return new Li(t)}return new Ri(t);case H:return new Hi(t);case S:return new ji(t);case T:return new Ui(t);case M:return new $i(t);case k:return new Vi(t);case I:return new Gi(t);case N:return new qi(t);case B:return new Xi(t);case P:return new Wi(t);case R:return new Ki(t);case D:return new Yi(t);case L:return new Qi(t);case F:return new Ji(t);case O:return new Zi(t);case z:return new tn(t);default:return new ki(t)}}}class ki{#ii=null;#ni=!1;#ai=null;constructor(t,{isRenderable:e=!1,ignoreBorder:s=!1,createQuadrilaterals:i=!1}={}){this.isRenderable=e,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,e&&(this.container=this._createContainer(s)),i&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:s}){return!!(t?.str||e?.str||s?.str)}get hasPopupData(){return ki._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#ii||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#ri(e),this.#ai?.popup.updateEdited(t)}resetEdited(){this.#ii&&(this.#ri(this.#ii.rect),this.#ai?.popup.resetEdited(),this.#ii=null)}#ri(t){const{container:{style:e},data:{rect:s,rotation:i},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:a,pageX:r,pageY:o}}}}=this;s?.splice(0,4,...t);const{width:h,height:l}=Ti(t);e.left=100*(t[0]-r)/n+"%",e.top=100*(a-t[3]+o)/a+"%",0===i?(e.width=100*h/n+"%",e.height=100*l/a+"%"):this.setRotation(i)}_createContainer(t){const{data:e,parent:{page:s,viewport:i}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id),this instanceof Ri||(n.tabIndex=Ci);const{style:a}=n;if(a.zIndex=this.parent.zIndex++,e.popupRef&&n.setAttribute("aria-haspopup","dialog"),e.alternativeText&&(n.title=e.alternativeText),e.noRotate&&n.classList.add("norotate"),!e.rect||this instanceof Hi){const{rotation:t}=e;return e.hasOwnCanvas||0===t||this.setRotation(t,n),n}const{width:r,height:o}=Ti(e.rect);if(!t&&e.borderStyle.width>0){a.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,s=e.borderStyle.verticalCornerRadius;if(t>0||s>0){const e=`calc(${t}px * var(--scale-factor)) / calc(${s}px * var(--scale-factor))`;a.borderRadius=e}else if(this instanceof Oi){const t=`calc(${r}px * var(--scale-factor)) / calc(${o}px * var(--scale-factor))`;a.borderRadius=t}switch(e.borderStyle.style){case U:a.borderStyle="solid";break;case $:a.borderStyle="dashed";break;case V:et("Unimplemented border style: beveled");break;case G:et("Unimplemented border style: inset");break;case W:a.borderBottomStyle="solid"}const i=e.borderColor||null;i?(this.#ni=!0,a.borderColor=At.makeHexColor(0|i[0],0|i[1],0|i[2])):a.borderWidth=0}const h=At.normalizeRect([e.rect[0],s.view[3]-e.rect[1]+s.view[1],e.rect[2],s.view[3]-e.rect[3]+s.view[1]]),{pageWidth:l,pageHeight:d,pageX:c,pageY:u}=i.rawDims;a.left=100*(h[0]-c)/l+"%",a.top=100*(h[1]-u)/d+"%";const{rotation:p}=e;return e.hasOwnCanvas||0===p?(a.width=100*r/l+"%",a.height=100*o/d+"%"):this.setRotation(p,n),n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:s,pageHeight:i}=this.parent.viewport.rawDims,{width:n,height:a}=Ti(this.data.rect);let r,o;t%180==0?(r=100*n/s,o=100*a/i):(r=100*a/s,o=100*n/i),e.style.width=`${r}%`,e.style.height=`${o}%`,e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(t,e,s)=>{const i=s.detail[t],n=i[0],a=i.slice(1);s.target.style[e]=xi[`${n}_HTML`](a),this.annotationStorage.setValue(this.data.id,{[e]:xi[`${n}_rgb`](a)})};return at(this,"_commonActions",{display:t=>{const{display:e}=t.detail,s=e%2==1;this.container.style.visibility=s?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:s,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout(()=>t.target.focus({preventScroll:!1}),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:e=>{t("bgColor","backgroundColor",e)},fillColor:e=>{t("fillColor","backgroundColor",e)},fgColor:e=>{t("fgColor","color",e)},textColor:e=>{t("textColor","color",e)},borderColor:e=>{t("borderColor","borderColor",e)},strokeColor:e=>{t("strokeColor","borderColor",e)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e),this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const s=this._commonActions;for(const i of Object.keys(e.detail)){const n=t[i]||s[i];n?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const s=this._commonActions;for(const[i,n]of Object.entries(e)){const a=s[i];if(a){a({detail:{[i]:n},target:t}),delete e[i]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,s,i,n]=this.data.rect.map(t=>Math.fround(t));if(8===t.length){const[a,r,o,h]=t.subarray(2,6);if(i===a&&n===r&&e===o&&s===h)return}const{style:a}=this.container;let r;if(this.#ni){const{borderColor:t,borderWidth:e}=a;a.borderWidth=0,r=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${t}" stroke-width="${e}">`],this.container.classList.add("hasBorder")}const o=i-e,h=n-s,{svgFactory:l}=this,d=l.createElement("svg");d.classList.add("quadrilateralsContainer"),d.setAttribute("width",0),d.setAttribute("height",0);const c=l.createElement("defs");d.append(c);const u=l.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p),u.setAttribute("clipPathUnits","objectBoundingBox"),c.append(u);for(let s=2,i=t.length;s<i;s+=8){const i=t[s],a=t[s+1],d=t[s+2],c=t[s+3],p=l.createElement("rect"),g=(d-e)/o,m=(n-a)/h,f=(i-d)/o,b=(a-c)/h;p.setAttribute("x",g),p.setAttribute("y",m),p.setAttribute("width",f),p.setAttribute("height",b),u.append(p),r?.push(`<rect vector-effect="non-scaling-stroke" x="${g}" y="${m}" width="${f}" height="${b}"/>`)}this.#ni&&(r.push("</g></svg>')"),a.backgroundImage=r.join("")),this.container.append(d),this.container.style.clipPath=`url(#${p})`}_createPopup(){const{container:t,data:e}=this;t.setAttribute("aria-haspopup","dialog");const s=this.#ai=new Hi({data:{color:e.color,titleObj:e.titleObj,modificationDate:e.modificationDate,contentsObj:e.contentsObj,richText:e.richText,parentRect:e.rect,borderStyle:0,id:`popup_${e.id}`,rotation:e.rotation},parent:this.parent,elements:[this]});this.parent.div.append(s.render())}render(){st("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const s=[];if(this._fieldObjects){const i=this._fieldObjects[t];if(i)for(const{page:t,id:n,exportValues:a}of i){if(-1===t)continue;if(n===e)continue;const i="string"==typeof a?a:null,r=document.querySelector(`[data-element-id="${n}"]`);!r||Si.has(r)?s.push({id:n,exportValue:i,domElement:r}):et(`_getElementsByName - element not allowed: ${n}`)}return s}for(const i of document.getElementsByName(t)){const{exportValue:t}=i,n=i.getAttribute("data-element-id");n!==e&&(Si.has(i)&&s.push({id:n,exportValue:t,domElement:i}))}return s}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}get _isEditable(){return!1}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})})}}class Pi extends ki{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,s=document.createElement("a");s.setAttribute("data-element-id",t.id);let i=!1;return t.url?(e.addLinkAttributes(s,t.url,t.newWindow),i=!0):t.action?(this._bindNamedAction(s,t.action),i=!0):t.attachment?(this.#oi(s,t.attachment,t.attachmentDest),i=!0):t.setOCGState?(this.#hi(s,t.setOCGState),i=!0):t.dest?(this._bindLink(s,t.dest),i=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(s,t),i=!0),t.resetForm?(this._bindResetFormAction(s,t.resetForm),i=!0):this.isTooltipOnly&&!i&&(this._bindLink(s,""),i=!0)),this.container.classList.add("linkAnnotation"),i&&this.container.append(s),this.container}#li(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e){t.href=this.linkService.getDestinationHash(e),t.onclick=()=>(e&&this.linkService.goToDestination(e),!1),(e||""===e)&&this.#li()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),this.#li()}#oi(t,e,s=null){t.href=this.linkService.getAnchorUrl(""),e.description&&(t.title=e.description),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,s),!1),this.#li()}#hi(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),this.#li()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const s=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const i of Object.keys(e.actions)){const n=s.get(i);n&&(t[n]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:i}}),!1))}t.onclick||(t.onclick=()=>!1),this.#li()}_bindResetFormAction(t,e){const s=t.onclick;if(s||(t.href=this.linkService.getAnchorUrl("")),this.#li(),!this._fieldObjects)return et('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),void(s||(t.onclick=()=>!1));t.onclick=()=>{s?.();const{fields:t,refs:i,include:n}=e,a=[];if(0!==t.length||0!==i.length){const e=new Set(i);for(const s of t){const t=this._fieldObjects[s]||[];for(const{id:s}of t)e.add(s)}for(const t of Object.values(this._fieldObjects))for(const s of t)e.has(s.id)===n&&a.push(s)}else for(const t of Object.values(this._fieldObjects))a.push(...t);const r=this.annotationStorage,o=[];for(const t of a){const{id:e}=t;switch(o.push(e),t.type){case"text":{const s=t.defaultValue||"";r.setValue(e,{value:s});break}case"checkbox":case"radiobutton":{const s=t.defaultValue===t.exportValues;r.setValue(e,{value:s});break}case"combobox":case"listbox":{const s=t.defaultValue||"";r.setValue(e,{value:s});break}default:continue}const s=document.querySelector(`[data-element-id="${e}"]`);s&&(Si.has(s)?s.dispatchEvent(new Event("resetform")):et(`_bindResetFormAction - element not allowed: ${e}`))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}}),!1}}}class Ii extends ki{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");return t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(t),this.container}}class Ri extends ki{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&("CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return bt.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,s,i,n){s.includes("mouse")?t.addEventListener(s,t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})}):t.addEventListener(s,t=>{if("blur"===s){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===s){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(t)}})})}_setEventListeners(t,e,s,i){for(const[n,a]of s)("Action"===a||this.data.actions?.[a])&&("Focus"!==a&&"Blur"!==a||(e||={focused:!1}),this._setEventListener(t,e,n,a,i),"Focus"!==a||this.data.actions?.Blur?"Blur"!==a||this.data.actions?.Focus||this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null))}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":At.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:s}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||9,n=t.style;let r;const o=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(a*i))||1);r=Math.min(i,o(e/a))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);r=Math.min(i,o(t/a))}n.fontSize=`calc(${r}px * var(--scale-factor))`,n.color=At.makeHexColor(s[0],s[1],s[2]),null!==this.data.textAlignment&&(n.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class Di extends Ri{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,s,i){const n=this.annotationStorage;for(const a of this._getElementsByName(t.name,t.id))a.domElement&&(a.domElement[e]=s),n.setValue(a.id,{[i]:s})}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let s=null;if(this.renderForms){const i=t.getValue(e,{value:this.data.fieldValue});let n=i.value||"";const a=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;a&&n.length>a&&(n=n.slice(0,a));let r=i.formattedValue||this.data.textContent?.join("\n")||null;r&&this.data.comb&&(r=r.replaceAll(/\s+/g,""));const o={userValue:n,formattedValue:r,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(s=document.createElement("textarea"),s.textContent=r??n,this.data.doNotScroll&&(s.style.overflowY="hidden")):(s=document.createElement("input"),s.type="text",s.setAttribute("value",r??n),this.data.doNotScroll&&(s.style.overflowX="hidden")),this.data.hasOwnCanvas&&(s.hidden=!0),Si.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,s.name=this.data.fieldName,s.tabIndex=Ci,this._setRequired(s,this.data.required),a&&(s.maxLength=a),s.addEventListener("input",i=>{t.setValue(e,{value:i.target.value}),this.setPropertyOnSiblings(s,"value",i.target.value,"value"),o.formattedValue=null}),s.addEventListener("resetform",t=>{const e=this.data.defaultFieldValue??"";s.value=o.userValue=e,o.formattedValue=null});let h=t=>{const{formattedValue:e}=o;null!=e&&(t.target.value=e),t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){s.addEventListener("focus",t=>{if(o.focused)return;const{target:e}=t;o.userValue&&(e.value=o.userValue),o.lastCommittedValue=e.value,o.commitKey=1,this.data.actions?.Focus||(o.focused=!0)}),s.addEventListener("updatefromsandbox",s=>{this.showElementAndHideCanvas(s.target);const i={value(s){o.userValue=s.detail.value??"",t.setValue(e,{value:o.userValue.toString()}),s.target.value=o.userValue},formattedValue(s){const{formattedValue:i}=s.detail;o.formattedValue=i,null!=i&&s.target!==document.activeElement&&(s.target.value=i),t.setValue(e,{formattedValue:i})},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:s=>{const{charLimit:i}=s.detail,{target:n}=s;if(0===i)return void n.removeAttribute("maxLength");n.setAttribute("maxLength",i);let a=o.userValue;!a||a.length<=i||(a=a.slice(0,i),n.value=o.userValue=a,t.setValue(e,{value:a}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:a,willCommit:!0,commitKey:1,selStart:n.selectionStart,selEnd:n.selectionEnd}}))}};this._dispatchEventFromSandbox(i,s)}),s.addEventListener("keydown",t=>{o.commitKey=1;let s=-1;if("Escape"===t.key?s=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):s=2,-1===s)return;const{value:i}=t.target;o.lastCommittedValue!==i&&(o.lastCommittedValue=i,o.userValue=i,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:i,willCommit:!0,commitKey:s,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}))});const i=h;h=null,s.addEventListener("blur",t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{value:s}=t.target;o.userValue=s,o.lastCommittedValue!==s&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}),i(t)}),this.data.actions?.Keystroke&&s.addEventListener("beforeinput",t=>{o.lastCommittedValue=null;const{data:s,target:i}=t,{value:n,selectionStart:a,selectionEnd:r}=i;let h=a,l=r;switch(t.inputType){case"deleteWordBackward":{const t=n.substring(0,a).match(/\w*[^\w]*$/);t&&(h-=t[0].length);break}case"deleteWordForward":{const t=n.substring(a).match(/^[^\w]*\w*/);t&&(l+=t[0].length);break}case"deleteContentBackward":a===r&&(h-=1);break;case"deleteContentForward":a===r&&(l+=1)}t.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,change:s||"",willCommit:!1,selStart:h,selEnd:l}})}),this._setEventListeners(s,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.value)}if(h&&s.addEventListener("blur",h),this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/a;s.classList.add("comb"),s.style.letterSpacing=`calc(${t}px * var(--scale-factor) - 1ch)`}}else s=document.createElement("div"),s.textContent=this.data.fieldValue,s.style.verticalAlign="middle",s.style.display="table-cell",this.data.hasOwnCanvas&&(s.hidden=!0);return this._setTextStyle(s),this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class Li extends Ri{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class Fi extends Ri{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,s=e.id;let i=t.getValue(s,{value:e.exportValue===e.fieldValue}).value;"string"==typeof i&&(i="Off"!==i,t.setValue(s,{value:i})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");return Si.add(n),n.setAttribute("data-element-id",s),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="checkbox",n.name=e.fieldName,i&&n.setAttribute("checked",!0),n.setAttribute("exportValue",e.exportValue),n.tabIndex=Ci,n.addEventListener("change",i=>{const{name:n,checked:a}=i.target;for(const i of this._getElementsByName(n,s)){const s=a&&i.exportValue===e.exportValue;i.domElement&&(i.domElement.checked=s),t.setValue(i.id,{value:s})}t.setValue(s,{value:a})}),n.addEventListener("resetform",t=>{const s=e.defaultFieldValue||"Off";t.target.checked=s===e.exportValue}),this.enableScripting&&this.hasJSActions&&(n.addEventListener("updatefromsandbox",e=>{const i={value(e){e.target.checked="Off"!==e.detail.value,t.setValue(s,{value:e.target.checked})}};this._dispatchEventFromSandbox(i,e)}),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.checked)),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class Oi extends Ri{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,s=e.id;let i=t.getValue(s,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof i&&(i=i!==e.buttonValue,t.setValue(s,{value:i})),i)for(const i of this._getElementsByName(e.fieldName,s))t.setValue(i.id,{value:!1});const n=document.createElement("input");if(Si.add(n),n.setAttribute("data-element-id",s),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="radio",n.name=e.fieldName,i&&n.setAttribute("checked",!0),n.tabIndex=Ci,n.addEventListener("change",e=>{const{name:i,checked:n}=e.target;for(const e of this._getElementsByName(i,s))t.setValue(e.id,{value:!1});t.setValue(s,{value:n})}),n.addEventListener("resetform",t=>{const s=e.defaultFieldValue;t.target.checked=null!=s&&s===e.buttonValue}),this.enableScripting&&this.hasJSActions){const i=e.buttonValue;n.addEventListener("updatefromsandbox",e=>{const n={value:e=>{const n=i===e.detail.value;for(const i of this._getElementsByName(e.target.name)){const e=n&&i.id===s;i.domElement&&(i.domElement.checked=e),t.setValue(i.id,{value:e})}}};this._dispatchEventFromSandbox(n,e)}),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.checked)}return this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class Ni extends Pi{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;return this.enableScripting&&this.hasJSActions&&e&&(this._setDefaultPropertiesFromJS(e),e.addEventListener("updatefromsandbox",t=>{this._dispatchEventFromSandbox({},t)})),t}}class Bi extends Ri{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,s=t.getValue(e,{value:this.data.fieldValue}),i=document.createElement("select");Si.add(i),i.setAttribute("data-element-id",e),i.disabled=this.data.readOnly,this._setRequired(i,this.data.required),i.name=this.data.fieldName,i.tabIndex=Ci;let n=this.data.combo&&this.data.options.length>0;this.data.combo||(i.size=this.data.options.length,this.data.multiSelect&&(i.multiple=!0)),i.addEventListener("resetform",t=>{const e=this.data.defaultFieldValue;for(const t of i.options)t.selected=t.value===e});for(const t of this.data.options){const e=document.createElement("option");e.textContent=t.displayValue,e.value=t.exportValue,s.value.includes(t.exportValue)&&(e.setAttribute("selected",!0),n=!1),i.append(e)}let a=null;if(n){const t=document.createElement("option");t.value=" ",t.setAttribute("hidden",!0),t.setAttribute("selected",!0),i.prepend(t),a=()=>{t.remove(),i.removeEventListener("input",a),a=null},i.addEventListener("input",a)}const r=t=>{const e=t?"value":"textContent",{options:s,multiple:n}=i;return n?Array.prototype.filter.call(s,t=>t.selected).map(t=>t[e]):-1===s.selectedIndex?null:s[s.selectedIndex][e]};let o=r(!1);const h=t=>{const e=t.target.options;return Array.prototype.map.call(e,t=>({displayValue:t.textContent,exportValue:t.value}))};return this.enableScripting&&this.hasJSActions?(i.addEventListener("updatefromsandbox",s=>{const n={value(s){a?.();const n=s.detail.value,h=new Set(Array.isArray(n)?n:[n]);for(const t of i.options)t.selected=h.has(t.value);t.setValue(e,{value:r(!0)}),o=r(!1)},multipleSelection(t){i.multiple=!0},remove(s){const n=i.options,a=s.detail.remove;if(n[a].selected=!1,i.remove(a),n.length>0){-1===Array.prototype.findIndex.call(n,t=>t.selected)&&(n[0].selected=!0)}t.setValue(e,{value:r(!0),items:h(s)}),o=r(!1)},clear(s){for(;0!==i.length;)i.remove(0);t.setValue(e,{value:null,items:[]}),o=r(!1)},insert(s){const{index:n,displayValue:a,exportValue:l}=s.detail.insert,d=i.children[n],c=document.createElement("option");c.textContent=a,c.value=l,d?d.before(c):i.append(c),t.setValue(e,{value:r(!0),items:h(s)}),o=r(!1)},items(s){const{items:n}=s.detail;for(;0!==i.length;)i.remove(0);for(const t of n){const{displayValue:e,exportValue:s}=t,n=document.createElement("option");n.textContent=e,n.value=s,i.append(n)}i.options.length>0&&(i.options[0].selected=!0),t.setValue(e,{value:r(!0),items:h(s)}),o=r(!1)},indices(s){const i=new Set(s.detail.indices);for(const t of s.target.options)t.selected=i.has(t.index);t.setValue(e,{value:r(!0)}),o=r(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(n,s)}),i.addEventListener("input",s=>{const i=r(!0),n=r(!1);t.setValue(e,{value:i}),s.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:o,change:n,changeEx:i,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(i,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],t=>t.target.value)):i.addEventListener("input",function(s){t.setValue(e,{value:r(!0)})}),this.data.combo&&this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class Hi extends ki{constructor(t){const{data:e,elements:s}=t;super(t,{isRenderable:ki._hasPopupData(e)}),this.elements=s,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new zi({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),e=[];for(const s of this.elements)s.popup=t,e.push(s.data.id),s.addHighlightArea();return this.container.setAttribute("aria-controls",e.map(t=>`${xt}${t}`).join(",")),this.container}}class zi{#di=this.#ci.bind(this);#ui=this.#pi.bind(this);#gi=this.#mi.bind(this);#fi=this.#bi.bind(this);#vi=null;#ft=null;#Ai=null;#yi=null;#wi=null;#_i=null;#xi=null;#Ei=!1;#Ci=null;#E=null;#Si=null;#Ti=null;#Mi=null;#ii=null;#ki=!1;constructor({container:t,color:e,elements:s,titleObj:i,modificationDate:n,contentsObj:a,richText:r,parent:o,rect:h,parentRect:l,open:d}){this.#ft=t,this.#Mi=i,this.#Ai=a,this.#Ti=r,this.#_i=o,this.#vi=e,this.#Si=h,this.#xi=l,this.#wi=s,this.#yi=ee.toDateObject(n),this.trigger=s.flatMap(t=>t.getElementsToTriggerPopup());for(const t of this.trigger)t.addEventListener("click",this.#fi),t.addEventListener("mouseenter",this.#gi),t.addEventListener("mouseleave",this.#ui),t.classList.add("popupTriggerArea");for(const t of s)t.container?.addEventListener("keydown",this.#di);this.#ft.hidden=!0,d&&this.#bi()}render(){if(this.#Ci)return;const t=this.#Ci=document.createElement("div");if(t.className="popup",this.#vi){const e=t.style.outlineColor=At.makeHexColor(...this.#vi);if(CSS.supports("background-color","color-mix(in srgb, red 30%, white)"))t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`;else{const e=.7;t.style.backgroundColor=At.makeHexColor(...this.#vi.map(t=>Math.floor(e*(255-t)+t)))}}const e=document.createElement("span");e.className="header";const s=document.createElement("h1");if(e.append(s),({dir:s.dir,str:s.textContent}=this.#Mi),t.append(e),this.#yi){const t=document.createElement("span");t.classList.add("popupDate"),t.setAttribute("data-l10n-id","pdfjs-annotation-date-string"),t.setAttribute("data-l10n-args",JSON.stringify({date:this.#yi.toLocaleDateString(),time:this.#yi.toLocaleTimeString()})),e.append(t)}const i=this.#Pi;if(i)Ei.render({xfaHtml:i,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const e=this._formatContents(this.#Ai);t.append(e)}this.#ft.append(t)}get#Pi(){const t=this.#Ti,e=this.#Ai;return!t?.str||e?.str&&e.str!==t.str?null:this.#Ti.html||null}get#Ii(){return this.#Pi?.attributes?.style?.fontSize||0}get#Ri(){return this.#Pi?.attributes?.style?.color||null}#Di(t){const e=[],s={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},i={style:{color:this.#Ri,fontSize:this.#Ii?`calc(${this.#Ii}px * var(--scale-factor))`:""}};for(const s of t.split("\n"))e.push({name:"span",value:s,attributes:i});return s}_formatContents({str:t,dir:e}){const s=document.createElement("p");s.classList.add("popupContent"),s.dir=e;const i=t.split(/(?:\r\n?|\n)/);for(let t=0,e=i.length;t<e;++t){const n=i[t];s.append(document.createTextNode(n)),t<e-1&&s.append(document.createElement("br"))}return s}#ci(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||("Enter"===t.key||"Escape"===t.key&&this.#Ei)&&this.#bi()}updateEdited({rect:t,popupContent:e}){this.#ii||={contentsObj:this.#Ai,richText:this.#Ti},t&&(this.#E=null),e&&(this.#Ti=this.#Di(e),this.#Ai=null),this.#Ci?.remove(),this.#Ci=null}resetEdited(){this.#ii&&(({contentsObj:this.#Ai,richText:this.#Ti}=this.#ii),this.#ii=null,this.#Ci?.remove(),this.#Ci=null,this.#E=null)}#Li(){if(null!==this.#E)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:s,pageX:i,pageY:n}}}=this.#_i;let a=!!this.#xi,r=a?this.#xi:this.#Si;for(const t of this.#wi)if(!r||null!==At.intersect(t.data.rect,r)){r=t.data.rect,a=!0;break}const o=At.normalizeRect([r[0],t[3]-r[1]+t[1],r[2],t[3]-r[3]+t[1]]),h=a?r[2]-r[0]+5:0,l=o[0]+h,d=o[1];this.#E=[100*(l-i)/e,100*(d-n)/s];const{style:c}=this.#ft;c.left=`${this.#E[0]}%`,c.top=`${this.#E[1]}%`}#bi(){this.#Ei=!this.#Ei,this.#Ei?(this.#mi(),this.#ft.addEventListener("click",this.#fi),this.#ft.addEventListener("keydown",this.#di)):(this.#pi(),this.#ft.removeEventListener("click",this.#fi),this.#ft.removeEventListener("keydown",this.#di))}#mi(){this.#Ci||this.render(),this.isVisible?this.#Ei&&this.#ft.classList.add("focused"):(this.#Li(),this.#ft.hidden=!1,this.#ft.style.zIndex=parseInt(this.#ft.style.zIndex)+1e3)}#pi(){this.#ft.classList.remove("focused"),!this.#Ei&&this.isVisible&&(this.#ft.hidden=!0,this.#ft.style.zIndex=parseInt(this.#ft.style.zIndex)-1e3)}forceHide(){this.#ki=this.isVisible,this.#ki&&(this.#ft.hidden=!0)}maybeShow(){this.#ki&&(this.#Ci||this.#mi(),this.#ki=!1,this.#ft.hidden=!1)}get isVisible(){return!1===this.#ft.hidden}}class ji extends ki{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=g.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){const t=document.createElement("div");t.classList.add("annotationTextContent"),t.setAttribute("role","comment");for(const e of this.textContent){const s=document.createElement("span");s.textContent=e,t.append(s)}this.container.append(t)}return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}get _isEditable(){return this.data.hasOwnCanvas}}class Ui extends ki{#Fi=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const t=this.data,{width:e,height:s}=Ti(t.rect),i=this.svgFactory.create(e,s,!0),n=this.#Fi=this.svgFactory.createElement("svg:line");return n.setAttribute("x1",t.rect[2]-t.lineCoordinates[0]),n.setAttribute("y1",t.rect[3]-t.lineCoordinates[1]),n.setAttribute("x2",t.rect[2]-t.lineCoordinates[2]),n.setAttribute("y2",t.rect[3]-t.lineCoordinates[3]),n.setAttribute("stroke-width",t.borderStyle.width||1),n.setAttribute("stroke","transparent"),n.setAttribute("fill","transparent"),i.append(n),this.container.append(i),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#Fi}addHighlightArea(){this.container.classList.add("highlightArea")}}class $i extends ki{#Oi=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const t=this.data,{width:e,height:s}=Ti(t.rect),i=this.svgFactory.create(e,s,!0),n=t.borderStyle.width,a=this.#Oi=this.svgFactory.createElement("svg:rect");return a.setAttribute("x",n/2),a.setAttribute("y",n/2),a.setAttribute("width",e-n),a.setAttribute("height",s-n),a.setAttribute("stroke-width",n||1),a.setAttribute("stroke","transparent"),a.setAttribute("fill","transparent"),i.append(a),this.container.append(i),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#Oi}addHighlightArea(){this.container.classList.add("highlightArea")}}class Vi extends ki{#Ni=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const t=this.data,{width:e,height:s}=Ti(t.rect),i=this.svgFactory.create(e,s,!0),n=t.borderStyle.width,a=this.#Ni=this.svgFactory.createElement("svg:ellipse");return a.setAttribute("cx",e/2),a.setAttribute("cy",s/2),a.setAttribute("rx",e/2-n/2),a.setAttribute("ry",s/2-n/2),a.setAttribute("stroke-width",n||1),a.setAttribute("stroke","transparent"),a.setAttribute("fill","transparent"),i.append(a),this.container.append(i),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#Ni}addHighlightArea(){this.container.classList.add("highlightArea")}}class Gi extends ki{#Bi=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,vertices:e,borderStyle:s,popupRef:i}}=this;if(!e)return this.container;const{width:n,height:a}=Ti(t),r=this.svgFactory.create(n,a,!0);let o=[];for(let s=0,i=e.length;s<i;s+=2){const i=e[s]-t[0],n=t[3]-e[s+1];o.push(`${i},${n}`)}o=o.join(" ");const h=this.#Bi=this.svgFactory.createElement(this.svgElementName);return h.setAttribute("points",o),h.setAttribute("stroke-width",s.width||1),h.setAttribute("stroke","transparent"),h.setAttribute("fill","transparent"),r.append(h),this.container.append(r),!i&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#Bi}addHighlightArea(){this.container.classList.add("highlightArea")}}class Wi extends Gi{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class qi extends ki{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class Xi extends ki{#Hi=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=g.INK}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,inkLists:e,borderStyle:s,popupRef:i}}=this,{width:n,height:a}=Ti(t),r=this.svgFactory.create(n,a,!0);for(const n of e){let e=[];for(let s=0,i=n.length;s<i;s+=2){const i=n[s]-t[0],a=t[3]-n[s+1];e.push(`${i},${a}`)}e=e.join(" ");const a=this.svgFactory.createElement(this.svgElementName);this.#Hi.push(a),a.setAttribute("points",e),a.setAttribute("stroke-width",s.width||1),a.setAttribute("stroke","transparent"),a.setAttribute("fill","transparent"),!i&&this.hasPopupData&&this._createPopup(),r.append(a)}return this.container.append(r),this.container}getElementsToTriggerPopup(){return this.#Hi}addHighlightArea(){this.container.classList.add("highlightArea")}}class Ki extends ki{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this.container}}class Yi extends ki{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("underlineAnnotation"),this.container}}class Qi extends ki{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("squigglyAnnotation"),this.container}}class Ji extends ki{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("strikeoutAnnotation"),this.container}}class Zi extends ki{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("stampAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class tn extends ki{#zi=null;constructor(t){super(t,{isRenderable:!0});const{file:e}=this.data;this.filename=e.filename,this.content=e.content,this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,...e})}render(){this.container.classList.add("fileAttachmentAnnotation");const{container:t,data:e}=this;let s;e.hasAppearance||0===e.fillAlpha?s=document.createElement("div"):(s=document.createElement("img"),s.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(e.name)?"paperclip":"pushpin"}.svg`,e.fillAlpha&&e.fillAlpha<1&&(s.style=`filter: opacity(${Math.round(100*e.fillAlpha)}%);`)),s.addEventListener("dblclick",this.#ji.bind(this)),this.#zi=s;const{isMac:i}=bt.platform;return t.addEventListener("keydown",t=>{"Enter"===t.key&&(i?t.metaKey:t.ctrlKey)&&this.#ji()}),!e.popupRef&&this.hasPopupData?this._createPopup():s.classList.add("popupTriggerArea"),t.append(s),t}getElementsToTriggerPopup(){return this.#zi}addHighlightArea(){this.container.classList.add("highlightArea")}#ji(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class en{#Ui=null;#$i=null;#Vi=new Map;constructor({div:t,accessibilityManager:e,annotationCanvasMap:s,annotationEditorUIManager:i,page:n,viewport:a}){this.div=t,this.#Ui=e,this.#$i=s,this.page=n,this.viewport=a,this.zIndex=0,this._annotationEditorUIManager=i}#Gi(t,e){const s=t.firstChild||t;s.id=`${xt}${e}`,this.div.append(t),this.#Ui?.moveElementInDOM(this.div,t,s,!1)}async render(t){const{annotations:e}=t,s=this.div;re(s,this.viewport);const i=new Map,n={data:null,layer:s,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new $t,annotationStorage:t.annotationStorage||new Ee,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const t of e){if(t.noHTML)continue;const e=t.annotationType===H;if(e){const e=i.get(t.id);if(!e)continue;n.elements=e}else{const{width:e,height:s}=Ti(t.rect);if(e<=0||s<=0)continue}n.data=t;const s=Mi.create(n);if(!s.isRenderable)continue;if(!e&&t.popupRef){const e=i.get(t.popupRef);e?e.push(s):i.set(t.popupRef,[s])}const a=s.render();t.hidden&&(a.style.visibility="hidden"),this.#Gi(a,t.id),s.annotationEditorType>0&&(this.#Vi.set(s.data.id,s),this._annotationEditorUIManager?.renderAnnotationElement(s))}this.#Wi()}update({viewport:t}){const e=this.div;this.viewport=t,re(e,{rotation:t.rotation}),this.#Wi(),e.hidden=!1}#Wi(){if(!this.#$i)return;const t=this.div;for(const[e,s]of this.#$i){const i=t.querySelector(`[data-annotation-id="${e}"]`);if(!i)continue;s.className="annotationContent";const{firstChild:n}=i;n?"CANVAS"===n.nodeName?n.replaceWith(s):n.classList.contains("annotationContent")?n.after(s):n.before(s):i.append(s)}this.#$i.clear()}getEditableAnnotations(){return Array.from(this.#Vi.values())}getEditableAnnotation(t){return this.#Vi.get(t)}}const sn=/\r\n?|\n/g;class nn extends be{#qi=this.editorDivBlur.bind(this);#Xi=this.editorDivFocus.bind(this);#Ki=this.editorDivInput.bind(this);#Yi=this.editorDivKeydown.bind(this);#Qi=this.editorDivPaste.bind(this);#vi;#Ji="";#Zi=`${this.id}-editor`;#Ii;#tn=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=nn.prototype,e=t=>t.isEmpty(),s=me.TRANSLATE_SMALL,i=me.TRANSLATE_BIG;return at(this,"_keyboardManager",new pe([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-s,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[s,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[i,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-s],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:e}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,s],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,i],checker:e}]]))}static _type="freetext";static _editorType=g.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.#vi=t.color||nn._defaultColor||be._defaultLineColor,this.#Ii=t.fontSize||nn._defaultFontSize}static initialize(t,e){be.initialize(t,e,{strings:["pdfjs-free-text-default-content"]});const s=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(s.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case m.FREETEXT_SIZE:nn._defaultFontSize=e;break;case m.FREETEXT_COLOR:nn._defaultColor=e}}updateParams(t,e){switch(t){case m.FREETEXT_SIZE:this.#en(e);break;case m.FREETEXT_COLOR:this.#sn(e)}}static get defaultPropertiesToUpdate(){return[[m.FREETEXT_SIZE,nn._defaultFontSize],[m.FREETEXT_COLOR,nn._defaultColor||be._defaultLineColor]]}get propertiesToUpdate(){return[[m.FREETEXT_SIZE,this.#Ii],[m.FREETEXT_COLOR,this.#vi]]}#en(t){const e=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--scale-factor))`,this.translate(0,-(t-this.#Ii)*this.parentScale),this.#Ii=t,this.#in()},s=this.#Ii;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#sn(t){const e=t=>{this.#vi=this.editorDiv.style.color=t},s=this.#vi;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-nn._internalPadding*t,-(nn._internalPadding+this.#Ii)*t]}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1),this.parent.updateToolbar(g.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant");const t=this._uiManager._signal;this.editorDiv.addEventListener("keydown",this.#Yi,{signal:t}),this.editorDiv.addEventListener("focus",this.#Xi,{signal:t}),this.editorDiv.addEventListener("blur",this.#qi,{signal:t}),this.editorDiv.addEventListener("input",this.#Ki,{signal:t}),this.editorDiv.addEventListener("paste",this.#Qi,{signal:t})}disableEditMode(){this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#Zi),this._isDraggable=!0,this.editorDiv.removeEventListener("keydown",this.#Yi),this.editorDiv.removeEventListener("focus",this.#Xi),this.editorDiv.removeEventListener("blur",this.#qi),this.editorDiv.removeEventListener("input",this.#Ki),this.editorDiv.removeEventListener("paste",this.#Qi),this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(){this.width||(this.enableEditMode(),this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#nn(){const t=[];this.editorDiv.normalize();for(const e of this.editorDiv.childNodes)t.push(nn.#an(e));return t.join("\n")}#in(){const[t,e]=this.parentDimensions;let s;if(this.isAttachedToDOM)s=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,i=e.style.display,n=e.classList.contains("hidden");e.classList.remove("hidden"),e.style.display="hidden",t.div.append(this.div),s=e.getBoundingClientRect(),e.remove(),e.style.display=i,e.classList.toggle("hidden",n)}this.rotation%180==this.parentRotation%180?(this.width=s.width/t,this.height=s.height/e):(this.width=s.height/t,this.height=s.width/e),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=this.#Ji,e=this.#Ji=this.#nn().trimEnd();if(t===e)return;const s=t=>{this.#Ji=t,t?(this.#rn(),this._uiManager.rebuild(this),this.#in()):this.remove()};this.addCommands({cmd:()=>{s(e)},undo:()=>{s(t)},mustExec:!1}),this.#in()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(t){this.enterInEditMode()}keydown(t){t.target===this.div&&"Enter"===t.key&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){nn._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let t,e;this.width&&(t=this.x,e=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#Zi),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text"),this.enableEditing(),be._l10nPromise.get("pdfjs-free-text-default-content").then(t=>this.editorDiv?.setAttribute("default-content",t)),this.editorDiv.contentEditable=!0;const{style:s}=this.editorDiv;if(s.fontSize=`calc(${this.#Ii}px * var(--scale-factor))`,s.color=this.#vi,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),le(this,this.div,["dblclick","keydown"]),this.width){const[s,i]=this.parentDimensions;if(this.annotationElementId){const{position:n}=this.#tn;let[a,r]=this.getInitialTranslation();[a,r]=this.pageTranslationToScreen(a,r);const[o,h]=this.pageDimensions,[l,d]=this.pageTranslation;let c,u;switch(this.rotation){case 0:c=t+(n[0]-l)/o,u=e+this.height-(n[1]-d)/h;break;case 90:c=t+(n[0]-l)/o,u=e-(n[1]-d)/h,[a,r]=[r,-a];break;case 180:c=t-this.width+(n[0]-l)/o,u=e-(n[1]-d)/h,[a,r]=[-a,-r];break;case 270:c=t+(n[0]-l-this.height*h)/o,u=e+(n[1]-d-this.width*o)/h,[a,r]=[-r,a]}this.setAt(c*s,u*i,a,r)}else this.setAt(t*s,e*i,this.width*s,this.height*i);this.#rn(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#an(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(sn,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:s}=e;if(1===s.length&&"text/plain"===s[0])return;t.preventDefault();const i=nn.#on(e.getData("text")||"").replaceAll(sn,"\n");if(!i)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize(),n.deleteFromDocument();const a=n.getRangeAt(0);if(!i.includes("\n"))return a.insertNode(document.createTextNode(i)),this.editorDiv.normalize(),void n.collapseToStart();const{startContainer:r,startOffset:o}=a,h=[],l=[];if(r.nodeType===Node.TEXT_NODE){const t=r.parentElement;if(l.push(r.nodeValue.slice(o).replaceAll(sn,"")),t!==this.editorDiv){let e=h;for(const s of this.editorDiv.childNodes)s!==t?e.push(nn.#an(s)):e=l}h.push(r.nodeValue.slice(0,o).replaceAll(sn,""))}else if(r===this.editorDiv){let t=h,e=0;for(const s of this.editorDiv.childNodes)e++===o&&(t=l),t.push(nn.#an(s))}this.#Ji=`${h.join("\n")}${i}${l.join("\n")}`,this.#rn();const d=new Range;let c=h.reduce((t,e)=>t+e.length,0);for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(c<=e){d.setStart(t,c),d.setEnd(t,c);break}c-=e}n.removeAllRanges(),n.addRange(d)}#rn(){if(this.editorDiv.replaceChildren(),this.#Ji)for(const t of this.#Ji.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#hn(){return this.#Ji.replaceAll(" "," ")}static#on(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}static deserialize(t,e,s){let i=null;if(t instanceof ji){const{data:{defaultAppearanceData:{fontSize:e,fontColor:s},rect:n,rotation:a,id:r},textContent:o,textPosition:h,parent:{page:{pageNumber:l}}}=t;if(!o||0===o.length)return null;i=t={annotationType:g.FREETEXT,color:Array.from(s),fontSize:e,value:o.join("\n"),position:h,pageIndex:l-1,rect:n.slice(0),rotation:a,id:r,deleted:!1}}const n=super.deserialize(t,e,s);return n.#Ii=t.fontSize,n.#vi=At.makeHexColor(...t.color),n.#Ji=nn.#on(t.value),n.annotationElementId=t.id||null,n.#tn=i,n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return{pageIndex:this.pageIndex,id:this.annotationElementId,deleted:!0};const e=nn._internalPadding*this.parentScale,s=this.getRect(e,e),i=be._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#vi),n={annotationType:g.FREETEXT,color:i,fontSize:this.#Ii,value:this.#hn(),pageIndex:this.pageIndex,rect:s,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?n:this.annotationElementId&&!this.#ln(n)?null:(n.id=this.annotationElementId,n)}#ln(t){const{value:e,fontSize:s,color:i,pageIndex:n}=this.#tn;return this._hasBeenMoved||t.value!==e||t.fontSize!==s||t.color.some((t,e)=>t!==i[e])||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(this.deleted)return e;const{style:s}=e;s.fontSize=`calc(${this.#Ii}px * var(--scale-factor))`,s.color=this.#vi,e.replaceChildren();for(const t of this.#Ji.split("\n")){const s=document.createElement("div");s.append(t?document.createTextNode(t):document.createElement("br")),e.append(s)}const i=nn._internalPadding*this.parentScale;return t.updateEdited({rect:this.getRect(i,i),popupContent:this.#Ji}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class an{#dn;#cn=[];#un=[];constructor(t,e=0,s=0,i=!0){let n=1/0,a=-1/0,r=1/0,o=-1/0;const h=10**-4;for(const{x:s,y:i,width:l,height:d}of t){const t=Math.floor((s-e)/h)*h,c=Math.ceil((s+l+e)/h)*h,u=Math.floor((i-e)/h)*h,p=Math.ceil((i+d+e)/h)*h,g=[t,u,p,!0],m=[c,u,p,!1];this.#cn.push(g,m),n=Math.min(n,t),a=Math.max(a,c),r=Math.min(r,u),o=Math.max(o,p)}const l=a-n+2*s,d=o-r+2*s,c=n-s,u=r-s,p=this.#cn.at(i?-1:-2),g=[p[0],p[2]];for(const t of this.#cn){const[e,s,i]=t;t[0]=(e-c)/l,t[1]=(s-u)/d,t[2]=(i-u)/d}this.#dn={x:c,y:u,width:l,height:d,lastPoint:g}}getOutlines(){this.#cn.sort((t,e)=>t[0]-e[0]||t[1]-e[1]||t[2]-e[2]);const t=[];for(const e of this.#cn)e[3]?(t.push(...this.#pn(e)),this.#gn(e)):(this.#mn(e),t.push(...this.#pn(e)));return this.#fn(t)}#fn(t){const e=[],s=new Set;for(const s of t){const[t,i,n]=s;e.push([t,i,s],[t,n,s])}e.sort((t,e)=>t[1]-e[1]||t[0]-e[0]);for(let t=0,i=e.length;t<i;t+=2){const i=e[t][2],n=e[t+1][2];i.push(n),n.push(i),s.add(i),s.add(n)}const i=[];let n;for(;s.size>0;){const t=s.values().next().value;let[e,a,r,o,h]=t;s.delete(t);let l=e,d=a;for(n=[e,r],i.push(n);;){let t;if(s.has(o))t=o;else{if(!s.has(h))break;t=h}s.delete(t),[e,a,r,o,h]=t,l!==e&&(n.push(l,d,e,d===a?a:r),l=e),d=d===a?r:a}n.push(l,d)}return new on(i,this.#dn)}#bn(t){const e=this.#un;let s=0,i=e.length-1;for(;s<=i;){const n=s+i>>1,a=e[n][0];if(a===t)return n;a<t?s=n+1:i=n-1}return i+1}#gn([,t,e]){const s=this.#bn(t);this.#un.splice(s,0,[t,e])}#mn([,t,e]){const s=this.#bn(t);for(let i=s;i<this.#un.length;i++){const[s,n]=this.#un[i];if(s!==t)break;if(s===t&&n===e)return void this.#un.splice(i,1)}for(let i=s-1;i>=0;i--){const[s,n]=this.#un[i];if(s!==t)break;if(s===t&&n===e)return void this.#un.splice(i,1)}}#pn(t){const[e,s,i]=t,n=[[e,s,i]],a=this.#bn(i);for(let t=0;t<a;t++){const[s,i]=this.#un[t];for(let t=0,a=n.length;t<a;t++){const[,r,o]=n[t];if(!(i<=r||o<=s))if(r>=s)if(o>i)n[t][1]=i;else{if(1===a)return[];n.splice(t,1),t--,a--}else n[t][2]=s,o>i&&n.push([e,i,o])}}return n}}class rn{toSVGPath(){throw new Error("Abstract method `toSVGPath` must be implemented.")}get box(){throw new Error("Abstract getter `box` must be implemented.")}serialize(t,e){throw new Error("Abstract method `serialize` must be implemented.")}get free(){return this instanceof ln}}class on extends rn{#dn;#vn;constructor(t,e){super(),this.#vn=t,this.#dn=e}toSVGPath(){const t=[];for(const e of this.#vn){let[s,i]=e;t.push(`M${s} ${i}`);for(let n=2;n<e.length;n+=2){const a=e[n],r=e[n+1];a===s?(t.push(`V${r}`),i=r):r===i&&(t.push(`H${a}`),s=a)}t.push("Z")}return t.join(" ")}serialize([t,e,s,i],n){const a=[],r=s-t,o=i-e;for(const e of this.#vn){const s=new Array(e.length);for(let n=0;n<e.length;n+=2)s[n]=t+e[n]*r,s[n+1]=i-e[n+1]*o;a.push(s)}return a}get box(){return this.#dn}}class hn{#dn;#An=[];#yn;#wn;#_n=[];#xn=new Float64Array(18);#En;#Cn;#Sn;#Tn;#Mn;#kn;#Pn=[];static#In=8;static#Rn=2;static#Dn=hn.#In+hn.#Rn;constructor({x:t,y:e},s,i,n,a,r=0){this.#dn=s,this.#kn=n*i,this.#wn=a,this.#xn.set([NaN,NaN,NaN,NaN,t,e],6),this.#yn=r,this.#Tn=hn.#In*i,this.#Sn=hn.#Dn*i,this.#Mn=i,this.#Pn.push(t,e)}get free(){return!0}isEmpty(){return isNaN(this.#xn[8])}#Ln(){const t=this.#xn.subarray(4,6),e=this.#xn.subarray(16,18),[s,i,n,a]=this.#dn;return[(this.#En+(t[0]-e[0])/2-s)/n,(this.#Cn+(t[1]-e[1])/2-i)/a,(this.#En+(e[0]-t[0])/2-s)/n,(this.#Cn+(e[1]-t[1])/2-i)/a]}add({x:t,y:e}){this.#En=t,this.#Cn=e;const[s,i,n,a]=this.#dn;let[r,o,h,l]=this.#xn.subarray(8,12);const d=t-h,c=e-l,u=Math.hypot(d,c);if(u<this.#Sn)return!1;const p=u-this.#Tn,g=p/u,m=g*d,f=g*c;let b=r,v=o;r=h,o=l,h+=m,l+=f,this.#Pn?.push(t,e);const A=m/p,y=-f/p*this.#kn,w=A*this.#kn;if(this.#xn.set(this.#xn.subarray(2,8),0),this.#xn.set([h+y,l+w],4),this.#xn.set(this.#xn.subarray(14,18),12),this.#xn.set([h-y,l-w],16),isNaN(this.#xn[6]))return 0===this.#_n.length&&(this.#xn.set([r+y,o+w],2),this.#_n.push(NaN,NaN,NaN,NaN,(r+y-s)/n,(o+w-i)/a),this.#xn.set([r-y,o-w],14),this.#An.push(NaN,NaN,NaN,NaN,(r-y-s)/n,(o-w-i)/a)),this.#xn.set([b,v,r,o,h,l],6),!this.isEmpty();this.#xn.set([b,v,r,o,h,l],6);return Math.abs(Math.atan2(v-o,b-r)-Math.atan2(f,m))<Math.PI/2?([r,o,h,l]=this.#xn.subarray(2,6),this.#_n.push(NaN,NaN,NaN,NaN,((r+h)/2-s)/n,((o+l)/2-i)/a),[r,o,b,v]=this.#xn.subarray(14,18),this.#An.push(NaN,NaN,NaN,NaN,((b+r)/2-s)/n,((v+o)/2-i)/a),!0):([b,v,r,o,h,l]=this.#xn.subarray(0,6),this.#_n.push(((b+5*r)/6-s)/n,((v+5*o)/6-i)/a,((5*r+h)/6-s)/n,((5*o+l)/6-i)/a,((r+h)/2-s)/n,((o+l)/2-i)/a),[h,l,r,o,b,v]=this.#xn.subarray(12,18),this.#An.push(((b+5*r)/6-s)/n,((v+5*o)/6-i)/a,((5*r+h)/6-s)/n,((5*o+l)/6-i)/a,((r+h)/2-s)/n,((o+l)/2-i)/a),!0)}toSVGPath(){if(this.isEmpty())return"";const t=this.#_n,e=this.#An,s=this.#xn.subarray(4,6),i=this.#xn.subarray(16,18),[n,a,r,o]=this.#dn,[h,l,d,c]=this.#Ln();if(isNaN(this.#xn[6])&&!this.isEmpty())return`M${(this.#xn[2]-n)/r} ${(this.#xn[3]-a)/o} L${(this.#xn[4]-n)/r} ${(this.#xn[5]-a)/o} L${h} ${l} L${d} ${c} L${(this.#xn[16]-n)/r} ${(this.#xn[17]-a)/o} L${(this.#xn[14]-n)/r} ${(this.#xn[15]-a)/o} Z`;const u=[];u.push(`M${t[4]} ${t[5]}`);for(let e=6;e<t.length;e+=6)isNaN(t[e])?u.push(`L${t[e+4]} ${t[e+5]}`):u.push(`C${t[e]} ${t[e+1]} ${t[e+2]} ${t[e+3]} ${t[e+4]} ${t[e+5]}`);u.push(`L${(s[0]-n)/r} ${(s[1]-a)/o} L${h} ${l} L${d} ${c} L${(i[0]-n)/r} ${(i[1]-a)/o}`);for(let t=e.length-6;t>=6;t-=6)isNaN(e[t])?u.push(`L${e[t+4]} ${e[t+5]}`):u.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);return u.push(`L${e[4]} ${e[5]} Z`),u.join(" ")}getOutlines(){const t=this.#_n,e=this.#An,s=this.#xn,i=s.subarray(4,6),n=s.subarray(16,18),[a,r,o,h]=this.#dn,l=new Float64Array((this.#Pn?.length??0)+2);for(let t=0,e=l.length-2;t<e;t+=2)l[t]=(this.#Pn[t]-a)/o,l[t+1]=(this.#Pn[t+1]-r)/h;l[l.length-2]=(this.#En-a)/o,l[l.length-1]=(this.#Cn-r)/h;const[d,c,u,p]=this.#Ln();if(isNaN(s[6])&&!this.isEmpty()){const t=new Float64Array(36);return t.set([NaN,NaN,NaN,NaN,(s[2]-a)/o,(s[3]-r)/h,NaN,NaN,NaN,NaN,(s[4]-a)/o,(s[5]-r)/h,NaN,NaN,NaN,NaN,d,c,NaN,NaN,NaN,NaN,u,p,NaN,NaN,NaN,NaN,(s[16]-a)/o,(s[17]-r)/h,NaN,NaN,NaN,NaN,(s[14]-a)/o,(s[15]-r)/h],0),new ln(t,l,this.#dn,this.#Mn,this.#yn,this.#wn)}const g=new Float64Array(this.#_n.length+24+this.#An.length);let m=t.length;for(let e=0;e<m;e+=2)isNaN(t[e])?g[e]=g[e+1]=NaN:(g[e]=t[e],g[e+1]=t[e+1]);g.set([NaN,NaN,NaN,NaN,(i[0]-a)/o,(i[1]-r)/h,NaN,NaN,NaN,NaN,d,c,NaN,NaN,NaN,NaN,u,p,NaN,NaN,NaN,NaN,(n[0]-a)/o,(n[1]-r)/h],m),m+=24;for(let t=e.length-6;t>=6;t-=6)for(let s=0;s<6;s+=2)isNaN(e[t+s])?(g[m]=g[m+1]=NaN,m+=2):(g[m]=e[t+s],g[m+1]=e[t+s+1],m+=2);return g.set([NaN,NaN,NaN,NaN,e[4],e[5]],m),new ln(g,l,this.#dn,this.#Mn,this.#yn,this.#wn)}}class ln extends rn{#dn;#Fn=null;#yn;#wn;#Pn;#Mn;#On;constructor(t,e,s,i,n,a){super(),this.#On=t,this.#Pn=e,this.#dn=s,this.#Mn=i,this.#yn=n,this.#wn=a,this.#Nn(a);const{x:r,y:o,width:h,height:l}=this.#Fn;for(let e=0,s=t.length;e<s;e+=2)t[e]=(t[e]-r)/h,t[e+1]=(t[e+1]-o)/l;for(let t=0,s=e.length;t<s;t+=2)e[t]=(e[t]-r)/h,e[t+1]=(e[t+1]-o)/l}toSVGPath(){const t=[`M${this.#On[4]} ${this.#On[5]}`];for(let e=6,s=this.#On.length;e<s;e+=6)isNaN(this.#On[e])?t.push(`L${this.#On[e+4]} ${this.#On[e+5]}`):t.push(`C${this.#On[e]} ${this.#On[e+1]} ${this.#On[e+2]} ${this.#On[e+3]} ${this.#On[e+4]} ${this.#On[e+5]}`);return t.push("Z"),t.join(" ")}serialize([t,e,s,i],n){const a=s-t,r=i-e;let o,h;switch(n){case 0:o=this.#Bn(this.#On,t,i,a,-r),h=this.#Bn(this.#Pn,t,i,a,-r);break;case 90:o=this.#Hn(this.#On,t,e,a,r),h=this.#Hn(this.#Pn,t,e,a,r);break;case 180:o=this.#Bn(this.#On,s,e,-a,r),h=this.#Bn(this.#Pn,s,e,-a,r);break;case 270:o=this.#Hn(this.#On,s,i,-a,-r),h=this.#Hn(this.#Pn,s,i,-a,-r)}return{outline:Array.from(o),points:[Array.from(h)]}}#Bn(t,e,s,i,n){const a=new Float64Array(t.length);for(let r=0,o=t.length;r<o;r+=2)a[r]=e+t[r]*i,a[r+1]=s+t[r+1]*n;return a}#Hn(t,e,s,i,n){const a=new Float64Array(t.length);for(let r=0,o=t.length;r<o;r+=2)a[r]=e+t[r+1]*i,a[r+1]=s+t[r]*n;return a}#Nn(t){const e=this.#On;let s=e[4],i=e[5],n=s,a=i,r=s,o=i,h=s,l=i;const d=t?Math.max:Math.min;for(let t=6,c=e.length;t<c;t+=6){if(isNaN(e[t]))n=Math.min(n,e[t+4]),a=Math.min(a,e[t+5]),r=Math.max(r,e[t+4]),o=Math.max(o,e[t+5]),l<e[t+5]?(h=e[t+4],l=e[t+5]):l===e[t+5]&&(h=d(h,e[t+4]));else{const c=At.bezierBoundingBox(s,i,...e.slice(t,t+6));n=Math.min(n,c[0]),a=Math.min(a,c[1]),r=Math.max(r,c[2]),o=Math.max(o,c[3]),l<c[3]?(h=c[2],l=c[3]):l===c[3]&&(h=d(h,c[2]))}s=e[t+4],i=e[t+5]}const c=n-this.#yn,u=a-this.#yn,p=r-n+2*this.#yn,g=o-a+2*this.#yn;this.#Fn={x:c,y:u,width:p,height:g,lastPoint:[h,l]}}get box(){return this.#Fn}getNewOutline(t,e){const{x:s,y:i,width:n,height:a}=this.#Fn,[r,o,h,l]=this.#dn,d=n*h,c=a*l,u=s*h+r,p=i*l+o,g=new hn({x:this.#Pn[0]*d+u,y:this.#Pn[1]*c+p},this.#dn,this.#Mn,t,this.#wn,e??this.#yn);for(let t=2;t<this.#Pn.length;t+=2)g.add({x:this.#Pn[t]*d+u,y:this.#Pn[t+1]*c+p});return g.getOutlines()}}class dn{#di=this.#ci.bind(this);#zn=this.#o.bind(this);#jn=null;#Un=null;#$n;#Vn=null;#Gn=!1;#Wn=!1;#a=null;#qn;#p=null;#Xn;static get _keyboardManager(){return at(this,"_keyboardManager",new pe([[["Escape","mac+Escape"],dn.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],dn.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],dn.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],dn.prototype._moveToPrevious],[["Home","mac+Home"],dn.prototype._moveToBeginning],[["End","mac+End"],dn.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){t?(this.#Wn=!1,this.#Xn=m.HIGHLIGHT_COLOR,this.#a=t):(this.#Wn=!0,this.#Xn=m.HIGHLIGHT_DEFAULT_COLOR),this.#p=t?._uiManager||e,this.#qn=this.#p._eventBus,this.#$n=t?.color||this.#p?.highlightColors.values().next().value||"#FFFF98"}renderButton(){const t=this.#jn=document.createElement("button");t.className="colorPicker",t.tabIndex="0",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),t.setAttribute("aria-haspopup",!0);const e=this.#p._signal;t.addEventListener("click",this.#Kn.bind(this),{signal:e}),t.addEventListener("keydown",this.#di,{signal:e});const s=this.#Un=document.createElement("span");return s.className="swatch",s.setAttribute("aria-hidden",!0),s.style.backgroundColor=this.#$n,t.append(s),t}renderMainDropdown(){const t=this.#Vn=this.#Yn();return t.setAttribute("aria-orientation","horizontal"),t.setAttribute("aria-labelledby","highlightColorPickerLabel"),t}#Yn(){const t=document.createElement("div"),e=this.#p._signal;t.addEventListener("contextmenu",Jt,{signal:e}),t.className="dropdown",t.role="listbox",t.setAttribute("aria-multiselectable",!1),t.setAttribute("aria-orientation","vertical"),t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");for(const[s,i]of this.#p.highlightColors){const n=document.createElement("button");n.tabIndex="0",n.role="option",n.setAttribute("data-color",i),n.title=s,n.setAttribute("data-l10n-id",`pdfjs-editor-colorpicker-${s}`);const a=document.createElement("span");n.append(a),a.className="swatch",a.style.backgroundColor=i,n.setAttribute("aria-selected",i===this.#$n),n.addEventListener("click",this.#Qn.bind(this,i),{signal:e}),t.append(n)}return t.addEventListener("keydown",this.#di,{signal:e}),t}#Qn(t,e){e.stopPropagation(),this.#qn.dispatch("switchannotationeditorparams",{source:this,type:this.#Xn,value:t})}_colorSelectFromKeyboard(t){if(t.target===this.#jn)return void this.#Kn(t);const e=t.target.getAttribute("data-color");e&&this.#Qn(e,t)}_moveToNext(t){this.#Jn?t.target!==this.#jn?t.target.nextSibling?.focus():this.#Vn.firstChild?.focus():this.#Kn(t)}_moveToPrevious(t){t.target!==this.#Vn?.firstChild&&t.target!==this.#jn?(this.#Jn||this.#Kn(t),t.target.previousSibling?.focus()):this.#Jn&&this._hideDropdownFromKeyboard()}_moveToBeginning(t){this.#Jn?this.#Vn.firstChild?.focus():this.#Kn(t)}_moveToEnd(t){this.#Jn?this.#Vn.lastChild?.focus():this.#Kn(t)}#ci(t){dn._keyboardManager.exec(this,t)}#Kn(t){if(this.#Jn)return void this.hideDropdown();if(this.#Gn=0===t.detail,window.addEventListener("pointerdown",this.#zn,{signal:this.#p._signal}),this.#Vn)return void this.#Vn.classList.remove("hidden");const e=this.#Vn=this.#Yn();this.#jn.append(e)}#o(t){this.#Vn?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#Vn?.classList.add("hidden"),window.removeEventListener("pointerdown",this.#zn)}get#Jn(){return this.#Vn&&!this.#Vn.classList.contains("hidden")}_hideDropdownFromKeyboard(){this.#Wn||(this.#Jn?(this.hideDropdown(),this.#jn.focus({preventScroll:!0,focusVisible:this.#Gn})):this.#a?.unselect())}updateColor(t){if(this.#Un&&(this.#Un.style.backgroundColor=t),!this.#Vn)return;const e=this.#p.highlightColors.values();for(const s of this.#Vn.children)s.setAttribute("aria-selected",e.next().value===t)}destroy(){this.#jn?.remove(),this.#jn=null,this.#Un=null,this.#Vn?.remove(),this.#Vn=null}}class cn extends be{#Zn=null;#ta=0;#ea;#sa=null;#n=null;#ia=null;#na=null;#aa=0;#ra=null;#oa=null;#b=null;#ha=!1;#ot=this.#la.bind(this);#da=null;#ca;#ua=null;#pa="";#kn;#ga="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _l10nPromise;static _type="highlight";static _editorType=g.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=cn.prototype;return at(this,"_keyboardManager",new pe([[["ArrowLeft","mac+ArrowLeft"],t._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],t._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],t._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],t._moveCaret,{args:[3]}]]))}constructor(t){super({...t,name:"highlightEditor"}),this.color=t.color||cn._defaultColor,this.#kn=t.thickness||cn._defaultThickness,this.#ca=t.opacity||cn._defaultOpacity,this.#ea=t.boxes||null,this.#ga=t.methodOfCreation||"",this.#pa=t.text||"",this._isDraggable=!1,t.highlightId>-1?(this.#ha=!0,this.#ma(t),this.#fa()):(this.#Zn=t.anchorNode,this.#ta=t.anchorOffset,this.#na=t.focusNode,this.#aa=t.focusOffset,this.#ba(),this.#fa(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#ha?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#kn,methodOfCreation:this.#ga}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#ba(){const t=new an(this.#ea,.001);this.#oa=t.getOutlines(),({x:this.x,y:this.y,width:this.width,height:this.height}=this.#oa.box);const e=new an(this.#ea,.0025,.001,"ltr"===this._uiManager.direction);this.#ia=e.getOutlines();const{lastPoint:s}=this.#ia.box;this.#da=[(s[0]-this.x)/this.width,(s[1]-this.y)/this.height]}#ma({highlightOutlines:t,highlightId:e,clipPathId:s}){this.#oa=t;if(this.#ia=t.getNewOutline(this.#kn/2+1.5,.0025),e>=0)this.#b=e,this.#sa=s,this.parent.drawLayer.finalizeLine(e,t),this.#ua=this.parent.drawLayer.highlightOutline(this.#ia);else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(this.#b,t),this.parent.drawLayer.updateBox(this.#b,cn.#va(this.#oa.box,(e-this.rotation+360)%360)),this.parent.drawLayer.updateLine(this.#ua,this.#ia),this.parent.drawLayer.updateBox(this.#ua,cn.#va(this.#ia.box,e))}const{x:i,y:n,width:a,height:r}=t.box;switch(this.rotation){case 0:this.x=i,this.y=n,this.width=a,this.height=r;break;case 90:{const[t,e]=this.parentDimensions;this.x=n,this.y=1-i,this.width=a*e/t,this.height=r*t/e;break}case 180:this.x=1-i,this.y=1-n,this.width=a,this.height=r;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-n,this.y=i,this.width=a*e/t,this.height=r*t/e;break}}const{lastPoint:o}=this.#ia.box;this.#da=[(o[0]-i)/a,(o[1]-n)/r]}static initialize(t,e){be.initialize(t,e),cn._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case m.HIGHLIGHT_DEFAULT_COLOR:cn._defaultColor=e;break;case m.HIGHLIGHT_THICKNESS:cn._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#da}updateParams(t,e){switch(t){case m.HIGHLIGHT_COLOR:this.#sn(e);break;case m.HIGHLIGHT_THICKNESS:this.#Aa(e)}}static get defaultPropertiesToUpdate(){return[[m.HIGHLIGHT_DEFAULT_COLOR,cn._defaultColor],[m.HIGHLIGHT_THICKNESS,cn._defaultThickness]]}get propertiesToUpdate(){return[[m.HIGHLIGHT_COLOR,this.color||cn._defaultColor],[m.HIGHLIGHT_THICKNESS,this.#kn||cn._defaultThickness],[m.HIGHLIGHT_FREE,this.#ha]]}#sn(t){const e=t=>{this.color=t,this.parent?.drawLayer.changeColor(this.#b,t),this.#n?.updateColor(t)},s=this.color;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#Aa(t){const e=this.#kn,s=t=>{this.#kn=t,this.#ya(t)};this.addCommands({cmd:s.bind(this,t),undo:s.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}async addEditToolbar(){const t=await super.addEditToolbar();return t?(this._uiManager.highlightColors&&(this.#n=new dn({editor:this}),t.addColorPicker(this.#n)),t):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#wa())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#wa())}onceAdded(){this.parent.addUndoableEditor(this),this.div.focus()}remove(){this.#_a(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#fa(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#_a():t&&(this.#fa(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#ya(t){if(!this.#ha)return;this.#ma({highlightOutlines:this.#oa.getNewOutline(t/2)}),this.fixAndSetPosition();const[e,s]=this.parentDimensions;this.setDims(this.width*e,this.height*s)}#_a(){null!==this.#b&&this.parent&&(this.parent.drawLayer.remove(this.#b),this.#b=null,this.parent.drawLayer.remove(this.#ua),this.#ua=null)}#fa(t=this.parent){null===this.#b&&(({id:this.#b,clipPathId:this.#sa}=t.drawLayer.highlight(this.#oa,this.color,this.#ca)),this.#ua=t.drawLayer.highlightOutline(this.#ia),this.#ra&&(this.#ra.style.clipPath=this.#sa))}static#va({x:t,y:e,width:s,height:i},n){switch(n){case 90:return{x:1-e-i,y:t,width:i,height:s};case 180:return{x:1-t-s,y:1-e-i,width:s,height:i};case 270:return{x:e,y:1-t-s,width:i,height:s}}return{x:t,y:e,width:s,height:i}}rotate(t){const{drawLayer:e}=this.parent;let s;this.#ha?(t=(t-this.rotation+360)%360,s=cn.#va(this.#oa.box,t)):s=cn.#va(this,t),e.rotate(this.#b,t),e.rotate(this.#ua,t),e.updateBox(this.#b,s),e.updateBox(this.#ua,cn.#va(this.#ia.box,t))}render(){if(this.div)return this.div;const t=super.render();this.#pa&&(t.setAttribute("aria-label",this.#pa),t.setAttribute("role","mark")),this.#ha?t.classList.add("free"):this.div.addEventListener("keydown",this.#ot,{signal:this._uiManager._signal});const e=this.#ra=document.createElement("div");t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#sa;const[s,i]=this.parentDimensions;return this.setDims(this.width*s,this.height*i),le(this,this.#ra,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.parent.drawLayer.addClass(this.#ua,"hovered")}pointerleave(){this.parent.drawLayer.removeClass(this.#ua,"hovered")}#la(t){cn._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#xa(!0);break;case 1:case 3:this.#xa(!1)}}#xa(t){if(!this.#Zn)return;const e=window.getSelection();t?e.setPosition(this.#Zn,this.#ta):e.setPosition(this.#na,this.#aa)}select(){super.select(),this.#ua&&(this.parent?.drawLayer.removeClass(this.#ua,"hovered"),this.parent?.drawLayer.addClass(this.#ua,"selected"))}unselect(){super.unselect(),this.#ua&&(this.parent?.drawLayer.removeClass(this.#ua,"selected"),this.#ha||this.#xa(!1))}get _mustFixPosition(){return!this.#ha}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.show(this.#b,t),this.parent.drawLayer.show(this.#ua,t))}#wa(){return this.#ha?this.rotation:0}#Ea(){if(this.#ha)return null;const[t,e]=this.pageDimensions,s=this.#ea,i=new Float32Array(8*s.length);let n=0;for(const{x:a,y:r,width:o,height:h}of s){const s=a*t,l=(1-r-h)*e;i[n]=i[n+4]=s,i[n+1]=i[n+3]=l,i[n+2]=i[n+6]=s+o*t,i[n+5]=i[n+7]=l+h*e,n+=8}return i}#Ca(t){return this.#oa.serialize(t,this.#wa())}static startHighlighting(t,e,{target:s,x:i,y:n}){const{x:a,y:r,width:o,height:h}=s.getBoundingClientRect(),l=e=>{this.#Sa(t,e)},d=t._signal,c={capture:!0,passive:!1,signal:d},u=t=>{t.preventDefault(),t.stopPropagation()},p=e=>{s.removeEventListener("pointermove",l),window.removeEventListener("blur",p),window.removeEventListener("pointerup",p),window.removeEventListener("pointerdown",u,c),window.removeEventListener("contextmenu",Jt),this.#Ta(t,e)};window.addEventListener("blur",p,{signal:d}),window.addEventListener("pointerup",p,{signal:d}),window.addEventListener("pointerdown",u,c),window.addEventListener("contextmenu",Jt,{signal:d}),s.addEventListener("pointermove",l,{signal:d}),this._freeHighlight=new hn({x:i,y:n},[a,r,o,h],t.scale,this._defaultThickness/2,e,.001),({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.highlight(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0))}static#Sa(t,e){this._freeHighlight.add(e)&&t.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)}static#Ta(t,e){this._freeHighlight.isEmpty()?t.drawLayer.removeFreeHighlight(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static deserialize(t,e,s){const i=super.deserialize(t,e,s),{rect:[n,a,r,o],color:h,quadPoints:l}=t;i.color=At.makeHexColor(...h),i.#ca=t.opacity;const[d,c]=i.pageDimensions;i.width=(r-n)/d,i.height=(o-a)/c;const u=i.#ea=[];for(let t=0;t<l.length;t+=8)u.push({x:(l[4]-r)/d,y:(o-(1-l[t+5]))/c,width:(l[t+2]-l[t])/d,height:(l[t+5]-l[t+1])/c});return i.#ba(),i}serialize(t=!1){if(this.isEmpty()||t)return null;const e=this.getRect(0,0),s=be._colorManager.convert(this.color);return{annotationType:g.HIGHLIGHT,color:s,opacity:this.#ca,thickness:this.#kn,quadPoints:this.#Ea(),outlines:this.#Ca(e),pageIndex:this.pageIndex,rect:e,rotation:this.#wa(),structTreeParentId:this._structTreeParentId}}static canCreateNewEmptyEditor(){return!1}}class un extends be{#Ma=0;#ka=0;#Pa=this.canvasPointermove.bind(this);#Ia=this.canvasPointerleave.bind(this);#Ra=this.canvasPointerup.bind(this);#Da=this.canvasPointerdown.bind(this);#La=null;#Fa=new Path2D;#Oa=!1;#Na=!1;#Ba=!1;#Ha=null;#za=0;#ja=0;#Ua=null;static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=1;static _type="ink";static _editorType=g.INK;constructor(t){super({...t,name:"inkEditor"}),this.color=t.color||null,this.thickness=t.thickness||null,this.opacity=t.opacity||null,this.paths=[],this.bezierPath2D=[],this.allRawPaths=[],this.currentPath=[],this.scaleFactor=1,this.translationX=this.translationY=0,this.x=0,this.y=0,this._willKeepAspectRatio=!0}static initialize(t,e){be.initialize(t,e)}static updateDefaultParams(t,e){switch(t){case m.INK_THICKNESS:un._defaultThickness=e;break;case m.INK_COLOR:un._defaultColor=e;break;case m.INK_OPACITY:un._defaultOpacity=e/100}}updateParams(t,e){switch(t){case m.INK_THICKNESS:this.#Aa(e);break;case m.INK_COLOR:this.#sn(e);break;case m.INK_OPACITY:this.#$a(e)}}static get defaultPropertiesToUpdate(){return[[m.INK_THICKNESS,un._defaultThickness],[m.INK_COLOR,un._defaultColor||be._defaultLineColor],[m.INK_OPACITY,Math.round(100*un._defaultOpacity)]]}get propertiesToUpdate(){return[[m.INK_THICKNESS,this.thickness||un._defaultThickness],[m.INK_COLOR,this.color||un._defaultColor||be._defaultLineColor],[m.INK_OPACITY,Math.round(100*(this.opacity??un._defaultOpacity))]]}#Aa(t){const e=t=>{this.thickness=t,this.#Va()},s=this.thickness;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})}#sn(t){const e=t=>{this.color=t,this.#Ga()},s=this.color;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})}#$a(t){const e=t=>{this.opacity=t,this.#Ga()};t/=100;const s=this.opacity;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.canvas||(this.#Wa(),this.#qa()),this.isAttachedToDOM||(this.parent.add(this),this.#Xa()),this.#Va()))}remove(){null!==this.canvas&&(this.isEmpty()||this.commit(),this.canvas.width=this.canvas.height=0,this.canvas.remove(),this.canvas=null,this.#La&&(clearTimeout(this.#La),this.#La=null),this.#Ha?.disconnect(),this.#Ha=null,super.remove())}setParent(t){!this.parent&&t?this._uiManager.removeShouldRescale(this):this.parent&&null===t&&this._uiManager.addShouldRescale(this),super.setParent(t)}onScaleChanging(){const[t,e]=this.parentDimensions,s=this.width*t,i=this.height*e;this.setDimensions(s,i)}enableEditMode(){this.#Oa||null===this.canvas||(super.enableEditMode(),this._isDraggable=!1,this.canvas.addEventListener("pointerdown",this.#Da,{signal:this._uiManager._signal}))}disableEditMode(){this.isInEditMode()&&null!==this.canvas&&(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),this.canvas.removeEventListener("pointerdown",this.#Da))}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return 0===this.paths.length||1===this.paths.length&&0===this.paths[0].length}#Ka(){const{parentRotation:t,parentDimensions:[e,s]}=this;switch(t){case 90:return[0,s,s,e];case 180:return[e,s,e,s];case 270:return[e,0,s,e];default:return[0,0,e,s]}}#Ya(){const{ctx:t,color:e,opacity:s,thickness:i,parentScale:n,scaleFactor:a}=this;t.lineWidth=i*n/a,t.lineCap="round",t.lineJoin="round",t.miterLimit=10,t.strokeStyle=`${e}${function(t){return Math.round(Math.min(255,Math.max(1,255*t))).toString(16).padStart(2,"0")}(s)}`}#Qa(t,e){const s=this._uiManager._signal;this.canvas.addEventListener("contextmenu",Jt,{signal:s}),this.canvas.addEventListener("pointerleave",this.#Ia,{signal:s}),this.canvas.addEventListener("pointermove",this.#Pa,{signal:s}),this.canvas.addEventListener("pointerup",this.#Ra,{signal:s}),this.canvas.removeEventListener("pointerdown",this.#Da),this.isEditing=!0,this.#Ba||(this.#Ba=!0,this.#Xa(),this.thickness||=un._defaultThickness,this.color||=un._defaultColor||be._defaultLineColor,this.opacity??=un._defaultOpacity),this.currentPath.push([t,e]),this.#Na=!1,this.#Ya(),this.#Ua=()=>{this.#Ja(),this.#Ua&&window.requestAnimationFrame(this.#Ua)},window.requestAnimationFrame(this.#Ua)}#Za(t,e){const[s,i]=this.currentPath.at(-1);if(this.currentPath.length>1&&t===s&&e===i)return;const n=this.currentPath;let a=this.#Fa;if(n.push([t,e]),this.#Na=!0,n.length<=2)return a.moveTo(...n[0]),void a.lineTo(t,e);3===n.length&&(this.#Fa=a=new Path2D,a.moveTo(...n[0])),this.#tr(a,...n.at(-3),...n.at(-2),t,e)}#er(){if(0===this.currentPath.length)return;const t=this.currentPath.at(-1);this.#Fa.lineTo(...t)}#sr(t,e){let s;if(this.#Ua=null,t=Math.min(Math.max(t,0),this.canvas.width),e=Math.min(Math.max(e,0),this.canvas.height),this.#Za(t,e),this.#er(),1!==this.currentPath.length)s=this.#ir();else{const i=[t,e];s=[[i,i.slice(),i.slice(),i]]}const i=this.#Fa,n=this.currentPath;this.currentPath=[],this.#Fa=new Path2D;this.addCommands({cmd:()=>{this.allRawPaths.push(n),this.paths.push(s),this.bezierPath2D.push(i),this._uiManager.rebuild(this)},undo:()=>{this.allRawPaths.pop(),this.paths.pop(),this.bezierPath2D.pop(),0===this.paths.length?this.remove():(this.canvas||(this.#Wa(),this.#qa()),this.#Va())},mustExec:!0})}#Ja(){if(!this.#Na)return;this.#Na=!1;const t=Math.ceil(this.thickness*this.parentScale),e=this.currentPath.slice(-3),s=e.map(t=>t[0]),i=e.map(t=>t[1]),{ctx:n}=(Math.min(...s),Math.max(...s),Math.min(...i),Math.max(...i),this);n.save(),n.clearRect(0,0,this.canvas.width,this.canvas.height);for(const t of this.bezierPath2D)n.stroke(t);n.stroke(this.#Fa),n.restore()}#tr(t,e,s,i,n,a,r){const o=(e+i)/2,h=(s+n)/2,l=(i+a)/2,d=(n+r)/2;t.bezierCurveTo(o+2*(i-o)/3,h+2*(n-h)/3,l+2*(i-l)/3,d+2*(n-d)/3,l,d)}#ir(){const t=this.currentPath;if(t.length<=2)return[[t[0],t[0],t.at(-1),t.at(-1)]];const e=[];let s,[i,n]=t[0];for(s=1;s<t.length-2;s++){const[a,r]=t[s],[o,h]=t[s+1],l=(a+o)/2,d=(r+h)/2,c=[i+2*(a-i)/3,n+2*(r-n)/3],u=[l+2*(a-l)/3,d+2*(r-d)/3];e.push([[i,n],c,u,[l,d]]),[i,n]=[l,d]}const[a,r]=t[s],[o,h]=t[s+1],l=[i+2*(a-i)/3,n+2*(r-n)/3],d=[o+2*(a-o)/3,h+2*(r-h)/3];return e.push([[i,n],l,d,[o,h]]),e}#Ga(){if(this.isEmpty())return void this.#nr();this.#Ya();const{canvas:t,ctx:e}=this;e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t.width,t.height),this.#nr();for(const t of this.bezierPath2D)e.stroke(t)}commit(){this.#Oa||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),this.#Oa=!0,this.div.classList.add("disabled"),this.#Va(!0),this.select(),this.parent.addInkEditorIfNeeded(!0),this.moveInDOM(),this.div.focus({preventScroll:!0}))}focusin(t){this._focusEventsAllowed&&(super.focusin(t),this.enableEditMode())}canvasPointerdown(t){0===t.button&&this.isInEditMode()&&!this.#Oa&&(this.setInForeground(),t.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),this.#Qa(t.offsetX,t.offsetY))}canvasPointermove(t){t.preventDefault(),this.#Za(t.offsetX,t.offsetY)}canvasPointerup(t){t.preventDefault(),this.#ar(t)}canvasPointerleave(t){this.#ar(t)}#ar(t){this.canvas.removeEventListener("pointerleave",this.#Ia),this.canvas.removeEventListener("pointermove",this.#Pa),this.canvas.removeEventListener("pointerup",this.#Ra),this.canvas.addEventListener("pointerdown",this.#Da,{signal:this._uiManager._signal}),this.#La&&clearTimeout(this.#La),this.#La=setTimeout(()=>{this.#La=null,this.canvas.removeEventListener("contextmenu",Jt)},10),this.#sr(t.offsetX,t.offsetY),this.addToAnnotationStorage(),this.setInBackground()}#Wa(){this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=0,this.canvas.className="inkEditorCanvas",this.canvas.setAttribute("data-l10n-id","pdfjs-ink-canvas"),this.div.append(this.canvas),this.ctx=this.canvas.getContext("2d")}#qa(){this.#Ha=new ResizeObserver(t=>{const e=t[0].contentRect;e.width&&e.height&&this.setDimensions(e.width,e.height)}),this.#Ha.observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{this.#Ha?.disconnect(),this.#Ha=null},{once:!0})}get isResizable(){return!this.isEmpty()&&this.#Oa}render(){if(this.div)return this.div;let t,e;this.width&&(t=this.x,e=this.y),super.render(),this.div.setAttribute("data-l10n-id","pdfjs-ink");const[s,i,n,a]=this.#Ka();if(this.setAt(s,i,0,0),this.setDims(n,a),this.#Wa(),this.width){const[s,i]=this.parentDimensions;this.setAspectRatio(this.width*s,this.height*i),this.setAt(t*s,e*i,this.width*s,this.height*i),this.#Ba=!0,this.#Xa(),this.setDims(this.width*s,this.height*i),this.#Ga(),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return this.#qa(),this.div}#Xa(){if(!this.#Ba)return;const[t,e]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*t),this.canvas.height=Math.ceil(this.height*e),this.#nr()}setDimensions(t,e){const s=Math.round(t),i=Math.round(e);if(this.#za===s&&this.#ja===i)return;this.#za=s,this.#ja=i,this.canvas.style.visibility="hidden";const[n,a]=this.parentDimensions;this.width=t/n,this.height=e/a,this.fixAndSetPosition(),this.#Oa&&this.#rr(t,e),this.#Xa(),this.#Ga(),this.canvas.style.visibility="visible",this.fixDims()}#rr(t,e){const s=this.#or(),i=(t-s)/this.#ka,n=(e-s)/this.#Ma;this.scaleFactor=Math.min(i,n)}#nr(){const t=this.#or()/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+t,this.translationY*this.scaleFactor+t)}static#hr(t){const e=new Path2D;for(let s=0,i=t.length;s<i;s++){const[i,n,a,r]=t[s];0===s&&e.moveTo(...i),e.bezierCurveTo(n[0],n[1],a[0],a[1],r[0],r[1])}return e}static#lr(t,e,s){const[i,n,a,r]=e;switch(s){case 0:for(let e=0,s=t.length;e<s;e+=2)t[e]+=i,t[e+1]=r-t[e+1];break;case 90:for(let e=0,s=t.length;e<s;e+=2){const s=t[e];t[e]=t[e+1]+i,t[e+1]=s+n}break;case 180:for(let e=0,s=t.length;e<s;e+=2)t[e]=a-t[e],t[e+1]+=n;break;case 270:for(let e=0,s=t.length;e<s;e+=2){const s=t[e];t[e]=a-t[e+1],t[e+1]=r-s}break;default:throw new Error("Invalid rotation")}return t}static#dr(t,e,s){const[i,n,a,r]=e;switch(s){case 0:for(let e=0,s=t.length;e<s;e+=2)t[e]-=i,t[e+1]=r-t[e+1];break;case 90:for(let e=0,s=t.length;e<s;e+=2){const s=t[e];t[e]=t[e+1]-n,t[e+1]=s-i}break;case 180:for(let e=0,s=t.length;e<s;e+=2)t[e]=a-t[e],t[e+1]-=n;break;case 270:for(let e=0,s=t.length;e<s;e+=2){const s=t[e];t[e]=r-t[e+1],t[e+1]=a-s}break;default:throw new Error("Invalid rotation")}return t}#cr(t,e,s,i){const n=[],a=this.thickness/2,r=t*e+a,o=t*s+a;for(const e of this.paths){const s=[],a=[];for(let i=0,n=e.length;i<n;i++){const[h,l,d,c]=e[i];if(h[0]===c[0]&&h[1]===c[1]&&1===n){const e=t*h[0]+r,i=t*h[1]+o;s.push(e,i),a.push(e,i);break}const u=t*h[0]+r,p=t*h[1]+o,g=t*l[0]+r,m=t*l[1]+o,f=t*d[0]+r,b=t*d[1]+o,v=t*c[0]+r,A=t*c[1]+o;0===i&&(s.push(u,p),a.push(u,p)),s.push(g,m,f,b,v,A),a.push(g,m),i===n-1&&a.push(v,A)}n.push({bezier:un.#lr(s,i,this.rotation),points:un.#lr(a,i,this.rotation)})}return n}#ur(){let t=1/0,e=-1/0,s=1/0,i=-1/0;for(const n of this.paths)for(const[a,r,o,h]of n){const n=At.bezierBoundingBox(...a,...r,...o,...h);t=Math.min(t,n[0]),s=Math.min(s,n[1]),e=Math.max(e,n[2]),i=Math.max(i,n[3])}return[t,s,e,i]}#or(){return this.#Oa?Math.ceil(this.thickness*this.parentScale):0}#Va(t=!1){if(this.isEmpty())return;if(!this.#Oa)return void this.#Ga();const e=this.#ur(),s=this.#or();this.#ka=Math.max(be.MIN_SIZE,e[2]-e[0]),this.#Ma=Math.max(be.MIN_SIZE,e[3]-e[1]);const i=Math.ceil(s+this.#ka*this.scaleFactor),n=Math.ceil(s+this.#Ma*this.scaleFactor),[a,r]=this.parentDimensions;this.width=i/a,this.height=n/r,this.setAspectRatio(i,n);const o=this.translationX,h=this.translationY;this.translationX=-e[0],this.translationY=-e[1],this.#Xa(),this.#Ga(),this.#za=i,this.#ja=n,this.setDims(i,n);const l=t?s/this.scaleFactor/2:0;this.translate(o-this.translationX-l,h-this.translationY-l)}static deserialize(t,e,s){if(t instanceof Xi)return null;const i=super.deserialize(t,e,s);i.thickness=t.thickness,i.color=At.makeHexColor(...t.color),i.opacity=t.opacity;const[n,a]=i.pageDimensions,r=i.width*n,o=i.height*a,h=i.parentScale,l=t.thickness/2;i.#Oa=!0,i.#za=Math.round(r),i.#ja=Math.round(o);const{paths:d,rect:c,rotation:u}=t;for(let{bezier:t}of d){t=un.#dr(t,c,u);const e=[];i.paths.push(e);let s=h*(t[0]-l),n=h*(t[1]-l);for(let i=2,a=t.length;i<a;i+=6){const a=h*(t[i]-l),r=h*(t[i+1]-l),o=h*(t[i+2]-l),d=h*(t[i+3]-l),c=h*(t[i+4]-l),u=h*(t[i+5]-l);e.push([[s,n],[a,r],[o,d],[c,u]]),s=c,n=u}const a=this.#hr(e);i.bezierPath2D.push(a)}const p=i.#ur();return i.#ka=Math.max(be.MIN_SIZE,p[2]-p[0]),i.#Ma=Math.max(be.MIN_SIZE,p[3]-p[1]),i.#rr(r,o),i}serialize(){if(this.isEmpty())return null;const t=this.getRect(0,0),e=be._colorManager.convert(this.ctx.strokeStyle);return{annotationType:g.INK,color:e,thickness:this.thickness,opacity:this.opacity,paths:this.#cr(this.scaleFactor/this.parentScale,this.translationX,this.translationY,t),pageIndex:this.pageIndex,rect:t,rotation:this.rotation,structTreeParentId:this._structTreeParentId}}}class pn extends be{#pr=null;#gr=null;#mr=null;#fr=null;#br=null;#vr="";#Ar=null;#Ha=null;#yr=null;#wr=!1;#_r=!1;static _type="stamp";static _editorType=g.STAMP;constructor(t){super({...t,name:"stampEditor"}),this.#fr=t.bitmapUrl,this.#br=t.bitmapFile}static initialize(t,e){be.initialize(t,e)}static get supportedTypes(){return at(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map(t=>`image/${t}`))}static get supportedTypesStr(){return at(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(g.STAMP,{bitmapFile:t.getAsFile()})}#xr(t,e=!1){t?(this.#pr=t.bitmap,e||(this.#gr=t.id,this.#wr=t.isSvg),t.file&&(this.#vr=t.file.name),this.#Wa()):this.remove()}#Er(){this.#mr=null,this._uiManager.enableWaiting(!1),this.#Ar&&this.div.focus()}#Cr(){if(this.#gr)return this._uiManager.enableWaiting(!0),void this._uiManager.imageManager.getFromId(this.#gr).then(t=>this.#xr(t,!0)).finally(()=>this.#Er());if(this.#fr){const t=this.#fr;return this.#fr=null,this._uiManager.enableWaiting(!0),void(this.#mr=this._uiManager.imageManager.getFromUrl(t).then(t=>this.#xr(t)).finally(()=>this.#Er()))}if(this.#br){const t=this.#br;return this.#br=null,this._uiManager.enableWaiting(!0),void(this.#mr=this._uiManager.imageManager.getFromFile(t).then(t=>this.#xr(t)).finally(()=>this.#Er()))}const t=document.createElement("input");t.type="file",t.accept=pn.supportedTypesStr;const e=this._uiManager._signal;this.#mr=new Promise(s=>{t.addEventListener("change",async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this.#xr(e)}else this.remove();s()},{signal:e}),t.addEventListener("cancel",()=>{this.remove(),s()},{signal:e})}).finally(()=>this.#Er()),t.click()}remove(){this.#gr&&(this.#pr=null,this._uiManager.imageManager.deleteId(this.#gr),this.#Ar?.remove(),this.#Ar=null,this.#Ha?.disconnect(),this.#Ha=null,this.#yr&&(clearTimeout(this.#yr),this.#yr=null)),super.remove()}rebuild(){this.parent?(super.rebuild(),null!==this.div&&(this.#gr&&null===this.#Ar&&this.#Cr(),this.isAttachedToDOM||this.parent.add(this))):this.#gr&&this.#Cr()}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(this.#mr||this.#pr||this.#fr||this.#br||this.#gr)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this.width&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.addAltTextButton(),this.#pr?this.#Wa():this.#Cr(),this.width){const[s,i]=this.parentDimensions;this.setAt(t*s,e*i,this.width*s,this.height*i)}return this.div}#Wa(){const{div:t}=this;let{width:e,height:s}=this.#pr;const[i,n]=this.pageDimensions,a=.75;if(this.width)e=this.width*i,s=this.height*n;else if(e>a*i||s>a*n){const t=Math.min(a*i/e,a*n/s);e*=t,s*=t}const[r,o]=this.parentDimensions;this.setDims(e*r/i,s*o/n),this._uiManager.enableWaiting(!1);const h=this.#Ar=document.createElement("canvas");t.append(h),t.hidden=!1,this.#Sr(e,s),this.#qa(),this.#_r||(this.parent.addUndoableEditor(this),this.#_r=!0),this._reportTelemetry({action:"inserted_image"}),this.#vr&&h.setAttribute("aria-label",this.#vr)}#Tr(t,e){const[s,i]=this.parentDimensions;this.width=t/s,this.height=e/i,this.setDims(t,e),this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,null!==this.#yr&&clearTimeout(this.#yr);this.#yr=setTimeout(()=>{this.#yr=null,this.#Sr(t,e)},200)}#Mr(t,e){const{width:s,height:i}=this.#pr;let n=s,a=i,r=this.#pr;for(;n>2*t||a>2*e;){const s=n,i=a;n>2*t&&(n=n>=16384?Math.floor(n/2)-1:Math.ceil(n/2)),a>2*e&&(a=a>=16384?Math.floor(a/2)-1:Math.ceil(a/2));const o=new OffscreenCanvas(n,a);o.getContext("2d").drawImage(r,0,0,s,i,0,0,n,a),r=o.transferToImageBitmap()}return r}#Sr(t,e){t=Math.ceil(t),e=Math.ceil(e);const s=this.#Ar;if(!s||s.width===t&&s.height===e)return;s.width=t,s.height=e;const i=this.#wr?this.#pr:this.#Mr(t,e);if(this._uiManager.hasMLManager&&!this.hasAltText()){const s=new OffscreenCanvas(t,e).getContext("2d");s.drawImage(i,0,0,i.width,i.height,0,0,t,e),this._uiManager.mlGuess({service:"image-to-text",request:{data:s.getImageData(0,0,t,e).data,width:t,height:e,channels:4}}).then(t=>{const e=t?.output||"";this.parent&&e&&!this.hasAltText()&&(this.altTextData={altText:e,decorative:!1})})}const n=s.getContext("2d");n.filter=this._uiManager.hcmFilter,n.drawImage(i,0,0,i.width,i.height,0,0,t,e)}getImageForAltText(){return this.#Ar}#kr(t){if(t){if(this.#wr){const t=this._uiManager.imageManager.getSvgUrl(this.#gr);if(t)return t}const t=document.createElement("canvas");({width:t.width,height:t.height}=this.#pr);return t.getContext("2d").drawImage(this.#pr,0,0),t.toDataURL()}if(this.#wr){const[t,e]=this.pageDimensions,s=Math.round(this.width*t*Ht.PDF_TO_CSS_UNITS),i=Math.round(this.height*e*Ht.PDF_TO_CSS_UNITS),n=new OffscreenCanvas(s,i);return n.getContext("2d").drawImage(this.#pr,0,0,this.#pr.width,this.#pr.height,0,0,s,i),n.transferToImageBitmap()}return structuredClone(this.#pr)}#qa(){this._uiManager._signal&&(this.#Ha=new ResizeObserver(t=>{const e=t[0].contentRect;e.width&&e.height&&this.#Tr(e.width,e.height)}),this.#Ha.observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{this.#Ha?.disconnect(),this.#Ha=null},{once:!0}))}static deserialize(t,e,s){if(t instanceof Zi)return null;const i=super.deserialize(t,e,s),{rect:n,bitmapUrl:a,bitmapId:r,isSvg:o,accessibilityData:h}=t;r&&s.imageManager.isValidId(r)?i.#gr=r:i.#fr=a,i.#wr=o;const[l,d]=i.pageDimensions;return i.width=(n[2]-n[0])/l,i.height=(n[3]-n[1])/d,h&&(i.altTextData=h),i}serialize(t=!1,e=null){if(this.isEmpty())return null;const s={annotationType:g.STAMP,bitmapId:this.#gr,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#wr,structTreeParentId:this._structTreeParentId};if(t)return s.bitmapUrl=this.#kr(!0),s.accessibilityData=this.altTextData,s;const{decorative:i,altText:n}=this.altTextData;if(!i&&n&&(s.accessibilityData={type:"Figure",alt:n}),null===e)return s;e.stamps||=new Map;const a=this.#wr?(s.rect[2]-s.rect[0])*(s.rect[3]-s.rect[1]):null;if(e.stamps.has(this.#gr)){if(this.#wr){const t=e.stamps.get(this.#gr);a>t.area&&(t.area=a,t.serialized.bitmap.close(),t.serialized.bitmap=this.#kr(!1))}}else e.stamps.set(this.#gr,{area:a,serialized:s}),s.bitmap=this.#kr(!1);return s}}class gn{#Ui;#Pr=!1;#Ir=null;#Rr=null;#Dr=null;#Lr=null;#Fr=null;#Or=new Map;#Nr=!1;#Br=!1;#Hr=!1;#zr=null;#p;static _initialized=!1;static#N=new Map([nn,un,pn,cn].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:e,div:s,accessibilityManager:i,annotationLayer:n,drawLayer:a,textLayer:r,viewport:o,l10n:h}){const l=[...gn.#N.values()];if(!gn._initialized){gn._initialized=!0;for(const e of l)e.initialize(h,t)}t.registerEditorTypes(l),this.#p=t,this.pageIndex=e,this.div=s,this.#Ui=i,this.#Ir=n,this.viewport=o,this.#zr=r,this.drawLayer=a,this.#p.addLayer(this)}get isEmpty(){return 0===this.#Or.size}get isInvisible(){return this.isEmpty&&this.#p.getMode()===g.NONE}updateToolbar(t){this.#p.updateToolbar(t)}updateMode(t=this.#p.getMode()){switch(this.#jr(),t){case g.NONE:return this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),void this.disableClick();case g.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case g.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;for(const s of gn.#N.values())e.toggle(`${s._type}Editing`,t===s._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#zr?.div}addInkEditorIfNeeded(t){if(this.#p.getMode()!==g.INK)return;if(!t)for(const t of this.#Or.values())if(t.isEmpty())return void t.setInBackground();this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}setEditingState(t){this.#p.setEditingState(t)}addCommands(t){this.#p.addCommands(t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#Ir?.div.classList.toggle("disabled",!t)}enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const e of this.#Or.values())e.enableEditing(),e.show(!0),e.annotationElementId&&(this.#p.removeChangedExistingAnnotation(e),t.add(e.annotationElementId));if(!this.#Ir)return;const e=this.#Ir.getEditableAnnotations();for(const s of e){if(s.hide(),this.#p.isDeletedAnnotationElement(s.data.id))continue;if(t.has(s.data.id))continue;const e=this.deserialize(s);e&&(this.addOrRebuild(e),e.enableEditing())}}disable(){this.#Hr=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const s of this.#Or.values())s.disableEditing(),s.annotationElementId&&(null===s.serialize()?(e.set(s.annotationElementId,s),this.getEditableAnnotation(s.annotationElementId)?.show(),s.remove()):t.set(s.annotationElementId,s));if(this.#Ir){const s=this.#Ir.getEditableAnnotations();for(const i of s){const{id:s}=i.data;if(this.#p.isDeletedAnnotationElement(s))continue;let n=e.get(s);n?(n.resetAnnotationElement(i),n.show(!1),i.show()):(n=t.get(s),n&&(this.#p.addChangedExistingAnnotation(n),n.renderAnnotationElement(i),n.show(!1)),i.show())}}this.#jr(),this.isEmpty&&(this.div.hidden=!0);const{classList:s}=this.div;for(const t of gn.#N.values())s.remove(`${t._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#Hr=!1}getEditableAnnotation(t){return this.#Ir?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#p.getActive()!==t&&this.#p.setActiveEditor(t)}enableTextSelection(){this.div.tabIndex=-1,this.#zr?.div&&!this.#Lr&&(this.#Lr=this.#Ur.bind(this),this.#zr.div.addEventListener("pointerdown",this.#Lr,{signal:this.#p._signal}),this.#zr.div.classList.add("highlighting"))}disableTextSelection(){this.div.tabIndex=0,this.#zr?.div&&this.#Lr&&(this.#zr.div.removeEventListener("pointerdown",this.#Lr),this.#Lr=null,this.#zr.div.classList.remove("highlighting"))}#Ur(t){if(this.#p.unselectAll(),t.target===this.#zr.div){const{isMac:e}=bt.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#p.showAllEditors("highlight",!0,!0),this.#zr.div.classList.add("free"),cn.startHighlighting(this,"ltr"===this.#p.direction,t),this.#zr.div.addEventListener("pointerup",()=>{this.#zr.div.classList.remove("free")},{once:!0,signal:this.#p._signal}),t.preventDefault()}}enableClick(){if(this.#Dr)return;const t=this.#p._signal;this.#Dr=this.pointerdown.bind(this),this.#Rr=this.pointerup.bind(this),this.div.addEventListener("pointerdown",this.#Dr,{signal:t}),this.div.addEventListener("pointerup",this.#Rr,{signal:t})}disableClick(){this.#Dr&&(this.div.removeEventListener("pointerdown",this.#Dr),this.div.removeEventListener("pointerup",this.#Rr),this.#Dr=null,this.#Rr=null)}attach(t){this.#Or.set(t.id,t);const{annotationElementId:e}=t;e&&this.#p.isDeletedAnnotationElement(e)&&this.#p.removeDeletedAnnotationElement(t)}detach(t){this.#Or.delete(t.id),this.#Ui?.removePointerInTextLayer(t.contentDiv),!this.#Hr&&t.annotationElementId&&this.#p.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#p.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1,this.#Br||this.addInkEditorIfNeeded(!1)}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#p.addDeletedAnnotationElement(t.annotationElementId),be.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),t.parent?.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(t.parent!==this||!t.isAttachedToDOM){if(this.changeParent(t),this.#p.addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(),this.#p.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!this.#Fr&&(t._focusEventsAllowed=!1,this.#Fr=setTimeout(()=>{this.#Fr=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this.#p._signal}),e.focus())},0)),t._structTreeParentId=this.#Ui?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||=this,t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){this.addCommands({cmd:()=>t._uiManager.rebuild(t),undo:()=>{t.remove()},mustExec:!1})}getNextId(){return this.#p.getId()}get#$r(){return gn.#N.get(this.#p.getMode())}get _signal(){return this.#p._signal}#Vr(t){const e=this.#$r;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#$r?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#p.updateToolbar(t),this.#p.updateMode(t);const{offsetX:s,offsetY:i}=this.#Gr(),n=this.getNextId(),a=this.#Vr({parent:this,id:n,x:s,y:i,uiManager:this.#p,isCentered:!0,...e});a&&this.add(a)}deserialize(t){return gn.#N.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#p)||null}createAndAddNewEditor(t,e,s={}){const i=this.getNextId(),n=this.#Vr({parent:this,id:i,x:t.offsetX,y:t.offsetY,uiManager:this.#p,isCentered:e,...s});return n&&this.add(n),n}#Gr(){const{x:t,y:e,width:s,height:i}=this.div.getBoundingClientRect(),n=Math.max(0,t),a=Math.max(0,e),r=(n+Math.min(window.innerWidth,t+s))/2-t,o=(a+Math.min(window.innerHeight,e+i))/2-e,[h,l]=this.viewport.rotation%180==0?[r,o]:[o,r];return{offsetX:h,offsetY:l}}addNewEditor(){this.createAndAddNewEditor(this.#Gr(),!0)}setSelected(t){this.#p.setSelected(t)}toggleSelected(t){this.#p.toggleSelected(t)}isSelected(t){return this.#p.isSelected(t)}unselect(t){this.#p.unselect(t)}pointerup(t){const{isMac:e}=bt.platform;0!==t.button||t.ctrlKey&&e||t.target===this.div&&this.#Nr&&(this.#Nr=!1,this.#Pr?this.#p.getMode()!==g.STAMP?this.createAndAddNewEditor(t,!1):this.#p.unselectAll():this.#Pr=!0)}pointerdown(t){if(this.#p.getMode()===g.HIGHLIGHT&&this.enableTextSelection(),this.#Nr)return void(this.#Nr=!1);const{isMac:e}=bt.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;this.#Nr=!0;const s=this.#p.getActive();this.#Pr=!s||s.isEmpty()}findNewParent(t,e,s){const i=this.#p.findParent(e,s);return null!==i&&i!==this&&(i.changeParent(t),!0)}destroy(){this.#p.getActive()?.parent===this&&(this.#p.commitOrRemove(),this.#p.setActiveEditor(null)),this.#Fr&&(clearTimeout(this.#Fr),this.#Fr=null);for(const t of this.#Or.values())this.#Ui?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#Or.clear(),this.#p.removeLayer(this)}#jr(){this.#Br=!0;for(const t of this.#Or.values())t.isEmpty()&&t.remove();this.#Br=!1}render({viewport:t}){this.viewport=t,re(this.div,t);for(const t of this.#p.getEditors(this.pageIndex))this.add(t),t.rebuild();this.updateMode()}update({viewport:t}){this.#p.commitOrRemove(),this.#jr();const e=this.viewport.rotation,s=t.rotation;if(this.viewport=t,re(this.div,{rotation:s}),e!==s)for(const t of this.#Or.values())t.rotate(s);this.addInkEditorIfNeeded(!1)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#p.viewParameters.realScale}}class mn{#_i=null;#b=0;#Wr=new Map;#qr=new Map;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(this.#_i){if(this.#_i!==t){if(this.#Wr.size>0)for(const e of this.#Wr.values())e.remove(),t.append(e);this.#_i=t}}else this.#_i=t}static get _svgFactory(){return at(this,"_svgFactory",new $t)}static#Xr(t,{x:e=0,y:s=0,width:i=1,height:n=1}={}){const{style:a}=t;a.top=100*s+"%",a.left=100*e+"%",a.width=100*i+"%",a.height=100*n+"%"}#Kr(t){const e=mn._svgFactory.create(1,1,!0);return this.#_i.append(e),e.setAttribute("aria-hidden",!0),mn.#Xr(e,t),e}#Yr(t,e){const s=mn._svgFactory.createElement("clipPath");t.append(s);const i=`clip_${e}`;s.setAttribute("id",i),s.setAttribute("clipPathUnits","objectBoundingBox");const n=mn._svgFactory.createElement("use");return s.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),i}highlight(t,e,s,i=!1){const n=this.#b++,a=this.#Kr(t.box);a.classList.add("highlight"),t.free&&a.classList.add("free");const r=mn._svgFactory.createElement("defs");a.append(r);const o=mn._svgFactory.createElement("path");r.append(o);const h=`path_p${this.pageIndex}_${n}`;o.setAttribute("id",h),o.setAttribute("d",t.toSVGPath()),i&&this.#qr.set(n,o);const l=this.#Yr(r,h),d=mn._svgFactory.createElement("use");return a.append(d),a.setAttribute("fill",e),a.setAttribute("fill-opacity",s),d.setAttribute("href",`#${h}`),this.#Wr.set(n,a),{id:n,clipPathId:`url(#${l})`}}highlightOutline(t){const e=this.#b++,s=this.#Kr(t.box);s.classList.add("highlightOutline");const i=mn._svgFactory.createElement("defs");s.append(i);const n=mn._svgFactory.createElement("path");i.append(n);const a=`path_p${this.pageIndex}_${e}`;let r;if(n.setAttribute("id",a),n.setAttribute("d",t.toSVGPath()),n.setAttribute("vector-effect","non-scaling-stroke"),t.free){s.classList.add("free");const t=mn._svgFactory.createElement("mask");i.append(t),r=`mask_p${this.pageIndex}_${e}`,t.setAttribute("id",r),t.setAttribute("maskUnits","objectBoundingBox");const n=mn._svgFactory.createElement("rect");t.append(n),n.setAttribute("width","1"),n.setAttribute("height","1"),n.setAttribute("fill","white");const o=mn._svgFactory.createElement("use");t.append(o),o.setAttribute("href",`#${a}`),o.setAttribute("stroke","none"),o.setAttribute("fill","black"),o.setAttribute("fill-rule","nonzero"),o.classList.add("mask")}const o=mn._svgFactory.createElement("use");s.append(o),o.setAttribute("href",`#${a}`),r&&o.setAttribute("mask",`url(#${r})`);const h=o.cloneNode();return s.append(h),o.classList.add("mainOutline"),h.classList.add("secondaryOutline"),this.#Wr.set(e,s),e}finalizeLine(t,e){const s=this.#qr.get(t);this.#qr.delete(t),this.updateBox(t,e.box),s.setAttribute("d",e.toSVGPath())}updateLine(t,e){this.#Wr.get(t).firstChild.firstChild.setAttribute("d",e.toSVGPath())}removeFreeHighlight(t){this.remove(t),this.#qr.delete(t)}updatePath(t,e){this.#qr.get(t).setAttribute("d",e.toSVGPath())}updateBox(t,e){mn.#Xr(this.#Wr.get(t),e)}show(t,e){this.#Wr.get(t).classList.toggle("hidden",!e)}rotate(t,e){this.#Wr.get(t).setAttribute("data-main-rotation",e)}changeColor(t,e){this.#Wr.get(t).setAttribute("fill",e)}changeOpacity(t,e){this.#Wr.get(t).setAttribute("fill-opacity",e)}addClass(t,e){this.#Wr.get(t).classList.add(e)}removeClass(t,e){this.#Wr.get(t).classList.remove(e)}remove(t){null!==this.#_i&&(this.#Wr.get(t).remove(),this.#Wr.delete(t))}destroy(){this.#_i=null;for(const t of this.#Wr.values())t.remove();this.#Wr.clear()}}var fn=e.AbortException,bn=e.AnnotationEditorLayer,vn=e.AnnotationEditorParamsType,An=e.AnnotationEditorType,yn=e.AnnotationEditorUIManager,wn=e.AnnotationLayer,_n=e.AnnotationMode,xn=e.CMapCompressionType,En=e.ColorPicker,Cn=e.DOMSVGFactory,Sn=e.DrawLayer,Tn=e.FeatureTest,Mn=e.GlobalWorkerOptions,kn=e.ImageKind,Pn=e.InvalidPDFException,In=e.MissingPDFException,Rn=e.OPS,Dn=e.Outliner,Ln=e.PDFDataRangeTransport,Fn=e.PDFDateString,On=e.PDFWorker,Nn=e.PasswordResponses,Bn=e.PermissionFlag,Hn=e.PixelsPerInch,zn=e.RenderingCancelledException,jn=e.TextLayer,Un=e.UnexpectedResponseException,$n=e.Util,Vn=e.VerbosityLevel,Gn=e.XfaLayer,Wn=e.build,qn=e.createValidAbsoluteUrl,Xn=e.fetchData,Kn=e.getDocument,Yn=e.getFilenameFromUrl,Qn=e.getPdfFilenameFromUrl,Jn=e.getXfaPageViewport,Zn=e.isDataScheme,ta=e.isPdfFile,ea=e.noContextMenu,sa=e.normalizeUnicode,ia=e.renderTextLayer,na=e.setLayerDimensions,aa=e.shadow,ra=e.updateTextLayer,oa=e.version;export{fn as AbortException,bn as AnnotationEditorLayer,vn as AnnotationEditorParamsType,An as AnnotationEditorType,yn as AnnotationEditorUIManager,wn as AnnotationLayer,_n as AnnotationMode,xn as CMapCompressionType,En as ColorPicker,Cn as DOMSVGFactory,Sn as DrawLayer,Tn as FeatureTest,Mn as GlobalWorkerOptions,kn as ImageKind,Pn as InvalidPDFException,In as MissingPDFException,Rn as OPS,Dn as Outliner,Ln as PDFDataRangeTransport,Fn as PDFDateString,On as PDFWorker,Nn as PasswordResponses,Bn as PermissionFlag,Hn as PixelsPerInch,zn as RenderingCancelledException,jn as TextLayer,Un as UnexpectedResponseException,$n as Util,Vn as VerbosityLevel,Gn as XfaLayer,Wn as build,qn as createValidAbsoluteUrl,Xn as fetchData,Kn as getDocument,Yn as getFilenameFromUrl,Qn as getPdfFilenameFromUrl,Jn as getXfaPageViewport,Zn as isDataScheme,ta as isPdfFile,ea as noContextMenu,sa as normalizeUnicode,ia as renderTextLayer,na as setLayerDimensions,aa as shadow,ra as updateTextLayer,oa as version};